From 6c7dc2d2980533b8214d8664a51729e6ab15d766 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 09:18:08 -0500 Subject: [PATCH 001/267] fix(migrate): refuse an FK whose target columns are not a unique key An identity.reference with a dotted @references naming target fields that are not the target's primary key, a plain identity.secondary or a single @unique field passed load, and meta migrate emitted an FK the database refuses at apply time, after earlier statements had already run. buildExpectedSchema now throws FkTargetNotUniqueError first, naming the entity, the reference, the target and its fields, and saying to declare an identity.secondary. A partial or expression index is not a key an FK may reference, so it does not count. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + .../packages/migrate-ts/src/errors.ts | 27 ++++ .../migrate-ts/src/expected-schema.ts | 30 ++++- .../test/unit/fk-target-unique.test.ts | 126 ++++++++++++++++++ 4 files changed, 189 insertions(+), 1 deletion(-) create mode 100644 server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3631b5903c..470c351b70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,13 @@ here.** ### Changed +- **`meta migrate` refuses a foreign key that references columns the target does not hold unique.** + Behaviour change: an `identity.reference` whose dotted `@references` names target fields that are + not the target's primary key, a plain `identity.secondary` (no `@where`, no `@expr`) or a single + `@unique` field used to emit an FK the database refuses at apply time ("there is no unique + constraint matching given keys"), after earlier statements had already run. `meta migrate` and + `meta verify --db` now fail first with `FkTargetNotUniqueError`, naming the entity, the reference, + the target and its fields. Fix: declare an `identity.secondary` on those fields of the target. - **A prompt or output template that names a variable not on its payload now raises at render time.** Behaviour change: a generated render helper used to render `Hi {{nmae}}` as `Hi ` with no error when the payload declares `name`; it now raises `ERR_VAR_NOT_ON_PAYLOAD (nmae)` (`RenderError` in diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index 06d51a947a..a7dafdb2bc 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -35,6 +35,33 @@ export class SetNullNotNullableError extends Error { } } +/** + * Thrown by buildExpectedSchema() when an identity.reference targets fields the target + * table does not hold unique: not its primary key, not a plain identity.secondary, not a + * single @unique field. Postgres refuses such an FK at apply time, after earlier + * statements in the migration already ran; refusing here names the reference instead. + */ +export class FkTargetNotUniqueError extends Error { + override readonly name = "FkTargetNotUniqueError"; + readonly entityName: string; + readonly referenceName: string; + readonly targetEntityName: string; + readonly targetFields: string[]; + + constructor(entityName: string, referenceName: string, targetEntityName: string, targetFields: string[]) { + const fieldList = targetFields.join(", "); + super( + `Entity "${entityName}": reference "${referenceName}" targets [${fieldList}] on "${targetEntityName}", ` + + `which is not a unique key there (not its primary key, an identity.secondary without @where/@expr, or a @unique field). ` + + `A database refuses this foreign key. Fix: declare an identity.secondary on "${targetEntityName}" with @fields [${fieldList}].`, + ); + this.entityName = entityName; + this.referenceName = referenceName; + this.targetEntityName = targetEntityName; + this.targetFields = targetFields; + } +} + const ALLOW_OPTION_BY_KIND: Partial> = { "drop-column": "dropColumn", "drop-table": "dropTable", diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 6f41e955f7..13eef0aae9 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,4 +1,4 @@ -import { DuplicateSqlNameError } from "./errors.js"; +import { DuplicateSqlNameError, FkTargetNotUniqueError } from "./errors.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, } from "@metaobjectsdev/metadata"; @@ -1023,6 +1023,11 @@ function buildForeignKeys( const targetFieldNames = explicitTargetFields.length > 1 ? explicitTargetFields : [refChild.resolvedTargetPkField(root) ?? "id"]; + // Guard: an explicit target must be a unique key on the target, or the database + // refuses the FK at apply time. The bare form targets the primary key by construction. + if (explicitTargetFields.length > 0 && !isUniqueKeyOf(targetObj, explicitTargetFields)) { + throw new FkTargetNotUniqueError(holder.name, refChild.name, targetObj.name, explicitTargetFields); + } const refColumns = targetFieldNames.map((jsName) => { const targetField = findField(targetObj, jsName); return targetField @@ -1062,6 +1067,29 @@ function buildForeignKeys( return fks; } +/** + * True when `fieldNames` (in any order) are a key the target table holds unique: exactly its + * primary key, exactly a plain identity.secondary (a partial or expression index is not a key + * a foreign key may reference), or a single field declaring @unique. + */ +function isUniqueKeyOf(target: MetaObject, fieldNames: string[]): boolean { + const wanted = [...fieldNames].sort().join(","); + const same = (fields: string[]) => [...fields].sort().join(",") === wanted; + const primary = target.primaryIdentity(); + if (primary !== undefined && same(readIdentityFields(primary))) return true; + for (const secondary of target.secondaryIdentities()) { + // ADR-0039: resolving — @where / @expr may be inherited via extends. + if (secondary.attr(IDENTITY_ATTR_WHERE) !== undefined || secondary.attr(IDENTITY_ATTR_EXPR) !== undefined) continue; + if (same(readIdentityFields(secondary))) return true; + } + if (fieldNames.length === 1) { + const field = findField(target, fieldNames[0]!); + // ADR-0039: resolving — @unique may be inherited via extends. + if (field !== undefined && field.attr(FIELD_ATTR_UNIQUE) === true) return true; + } + return false; +} + /** * Expand a `field.object @storage "flattened"` into one ColumnDescriptor per * nested field of the referenced value-object, prefixed by the parent field's diff --git a/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts b/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts new file mode 100644 index 0000000000..ac2f8dacbe --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts @@ -0,0 +1,126 @@ +/** + * Guard: a foreign key must reference columns the target table holds unique. + * + * A reference whose dotted @references names target fields other than the target's + * primary key, with nothing declaring those fields unique, used to pass load and emit + * an FK Postgres refuses at apply time ("there is no unique constraint matching given + * keys for referenced table"). buildExpectedSchema() must refuse it before any SQL is + * emitted, naming the reference and the fix. + * + * Unique means: exactly the primary key's fields, exactly the fields of an + * identity.secondary that is a plain unique key (no @where, no @expr), or a single + * field carrying @unique. Field order does not matter; a subset or superset does. + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { FkTargetNotUniqueError } from "../../src/errors.js"; + +async function loadDoc(doc: unknown) { + const { root, errors } = await new MetaDataLoader().load([ + new InMemoryStringSource(JSON.stringify(doc)), + ]); + expect(errors).toHaveLength(0); + return root; +} + +/** A target entity (Person: id, region, code) and a holder (Visit) referencing it. */ +function makeDoc(options: { + references: string; + holderFields: string[]; + targetExtra?: unknown[]; + codeUnique?: boolean; +}) { + return { + "metadata.root": { + package: "acme", + children: [ + { + "object.entity": { + name: "Person", + children: [ + { "source.rdb": {} }, + { "field.long": { name: "id" } }, + { "field.long": { name: "region" } }, + { "field.string": { name: "code", ...(options.codeUnique ? { "@unique": true } : {}) } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ...(options.targetExtra ?? []), + ], + }, + }, + { + "object.entity": { + name: "Visit", + children: [ + { "source.rdb": {} }, + { "field.long": { name: "id" } }, + { "field.long": { name: "personId" } }, + { "field.long": { name: "personRegion" } }, + { "field.string": { name: "personCode" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { + "identity.reference": { + name: "ref_person", + "@fields": options.holderFields, + "@references": options.references, + }, + }, + ], + }, + }, + ], + }, + }; +} + +async function build(options: Parameters[0]) { + const root = await loadDoc(makeDoc(options)); + return () => buildExpectedSchema(root); +} + +describe("buildExpectedSchema — an FK must reference a unique key", () => { + test("a non-key target field with nothing unique on it → FkTargetNotUniqueError naming the fix", async () => { + const run = await build({ references: "Person.code", holderFields: ["personCode"] }); + + expect(run).toThrow(FkTargetNotUniqueError); + expect(run).toThrow(/Entity "Visit": reference "ref_person" targets \[code\] on "Person"/); + expect(run).toThrow(/identity\.secondary/); + }); + + test("a composite target that is not a declared key → throws", async () => { + const run = await build({ references: "Person.id,region", holderFields: ["personId", "personRegion"] }); + + expect(run).toThrow(FkTargetNotUniqueError); + }); + + test("a partial unique index is not a key an FK can reference → throws", async () => { + const run = await build({ + references: "Person.code", + holderFields: ["personCode"], + targetExtra: [{ "identity.secondary": { name: "ux_person_code", "@fields": ["code"], "@where": "\"region\" = 1" } }], + }); + + expect(run).toThrow(FkTargetNotUniqueError); + }); + + test("an identity.secondary on exactly the target fields, in any order → no throw", async () => { + const run = await build({ + references: "Person.id,region", + holderFields: ["personId", "personRegion"], + targetExtra: [{ "identity.secondary": { name: "ak_person_region_id", "@fields": ["region", "id"] } }], + }); + + expect(run).not.toThrow(); + }); + + test("a single target field with @unique → no throw", async () => { + const run = await build({ references: "Person.code", holderFields: ["personCode"], codeUnique: true }); + + expect(run).not.toThrow(); + }); + + test("the target's primary key, bare or dotted → no throw", async () => { + expect(await build({ references: "Person", holderFields: ["personId"] })).not.toThrow(); + expect(await build({ references: "Person.id", holderFields: ["personId"] })).not.toThrow(); + }); +}); From b10d73e4053286ac769a833ccefcf87467c80c0f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 09:26:28 -0500 Subject: [PATCH 002/267] fix(migrate): report every non-unique FK target at once, as a refusal FkTargetNotUniqueError now carries every offending reference across the model instead of the first, so a model with several is fixed in one pass. The expected-schema build collects them while building each table's FKs and throws once after all tables are built. meta migrate refuses it like a duplicate SQL name, with the engine's message and a hint, instead of labelling it an unexpected error. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- .../packages/cli/src/commands/migrate.ts | 5 ++ .../test/migrate-fk-target-not-unique.test.ts | 79 +++++++++++++++++++ .../packages/migrate-ts/src/errors.ts | 50 +++++++----- .../migrate-ts/src/expected-schema.ts | 19 +++-- .../packages/migrate-ts/src/index.ts | 2 + .../test/unit/fk-target-unique.test.ts | 27 +++++++ 7 files changed, 162 insertions(+), 26 deletions(-) create mode 100644 server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 470c351b70..5e1d9cc569 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,8 +39,10 @@ here.** not the target's primary key, a plain `identity.secondary` (no `@where`, no `@expr`) or a single `@unique` field used to emit an FK the database refuses at apply time ("there is no unique constraint matching given keys"), after earlier statements had already run. `meta migrate` and - `meta verify --db` now fail first with `FkTargetNotUniqueError`, naming the entity, the reference, - the target and its fields. Fix: declare an `identity.secondary` on those fields of the target. + `meta verify --db` now fail first with `FkTargetNotUniqueError`, which lists every offending + reference at once (entity, reference, target and fields), and `meta migrate` reports it as a + metadata refusal with a hint rather than an unexpected error. Fix: declare an + `identity.secondary` on those fields of the target. - **A prompt or output template that names a variable not on its payload now raises at render time.** Behaviour change: a generated render helper used to render `Hi {{nmae}}` as `Hi ` with no error when the payload declares `name`; it now raises `ERR_VAR_NOT_ON_PAYLOAD (nmae)` (`RenderError` in diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index ae661808de..b2165b157d 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -21,6 +21,7 @@ import { isPrimaryKeyChangeError, isDeclaredRenameError, isDuplicateSqlNameError, + isFkTargetNotUniqueError, buildExpectedSchemaWithProvenance, scopeExpectedSchema, scopedDiffInputs, @@ -367,6 +368,8 @@ const PK_CHANGE_HINT = "align the primary key manually, or reconcile the metadata identity to match the live table"; const DUPLICATE_SQL_NAME_HINT = "rename one of the colliding declarations; an index's database name is its identity.secondary / index.lookup name, not prefixed with its table"; +const FK_TARGET_NOT_UNIQUE_HINT = + "declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"; const DECLARED_RENAME_HINT = "fix or remove the --rename-table / --rename-column flag; a table's name is its name in the metadata (the new name when it is renamed too)"; @@ -1151,6 +1154,8 @@ export async function migrateCommand( if (err instanceof AlreadyEmittedError) return err.exitCode; // A metadata defect, not a tool failure: two declarations generate one database name. if (isDuplicateSqlNameError(err)) return refuseEngineError(err, DUPLICATE_SQL_NAME_HINT, fmt); + // A metadata defect too: a foreign key whose target columns are not a unique key there. + if (isFkTargetNotUniqueError(err)) return refuseEngineError(err, FK_TARGET_NOT_UNIQUE_HINT, fmt); // Unexpected error: emit structured error on stdout in the active format, then exit 1. const msg = describeError(err) ?? String(err); log.error(`migrate: unexpected error: ${msg}`); diff --git a/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts b/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts new file mode 100644 index 0000000000..f2bd3ba448 --- /dev/null +++ b/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts @@ -0,0 +1,79 @@ +/** + * An FK whose target columns are not a unique key is a metadata defect, not a tool + * failure: `meta migrate` refuses it with the engine's message and a hint, the way it + * refuses two declarations that generate one database name, never as an "unexpected error". + */ +import { describe, test, expect, afterAll, beforeEach, afterEach, spyOn } from "bun:test"; +import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { migrateCommand } from "../src/commands/migrate.js"; +import { log } from "../src/lib/log.js"; + +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +const MODEL = JSON.stringify({ + "metadata.root": { + package: "acme::platform", + children: [ + { + "object.entity": { + name: "Person", + children: [ + { "source.rdb": { name: "src", "@table": "people" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ], + }, + }, + { + "object.entity": { + name: "Visit", + children: [ + { "source.rdb": { name: "src", "@table": "visits" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "personCode" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "identity.reference": { name: "ref_person", "@fields": ["personCode"], "@references": "Person.code" } }, + ], + }, + }, + ], + }, +}); + +async function project(): Promise { + const root = await mkdtemp(join(tmpdir(), "fk-target-unique-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.platform.json"), MODEL, "utf8"); + await mkdir(join(root, ".metaobjects", "migrations"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, migrate: { dialect: "sqlite" } }), "utf8"); + return root; +} + +let out: string[] = []; +let infoSpy: ReturnType; +let errSpy: ReturnType; +beforeEach(() => { + out = []; + infoSpy = spyOn(log, "info").mockImplementation((m: string) => { out.push(String(m)); }); + errSpy = spyOn(log, "error").mockImplementation((m: string) => { out.push(String(m)); }); +}); +afterEach(() => { infoSpy.mockRestore(); errSpy.mockRestore(); }); + +describe("meta migrate refuses an FK to a non-unique target", () => { + test("exits 1 with the reference named and the fix, not as an unexpected error", async () => { + const root = await project(); + const code = await migrateCommand(["--from-db", "--db", `file:${join(root, "t.db")}`, "--dialect", "sqlite", "--dry-run"], root); + + const text = out.join("\n"); + expect(code).toBe(1); + expect(text).toContain('reference "ref_person" targets [code] on "Person"'); + expect(text).toContain("identity.secondary"); + expect(text).not.toContain("unexpected error"); + expect(text).not.toContain("CREATE TABLE"); + }); +}); diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index a7dafdb2bc..801eb47507 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -35,30 +35,37 @@ export class SetNullNotNullableError extends Error { } } +/** One identity.reference whose dotted @references names fields the target does not hold unique. */ +export interface FkTargetViolation { + entityName: string; + referenceName: string; + targetEntityName: string; + targetFields: string[]; +} + /** - * Thrown by buildExpectedSchema() when an identity.reference targets fields the target - * table does not hold unique: not its primary key, not a plain identity.secondary, not a - * single @unique field. Postgres refuses such an FK at apply time, after earlier - * statements in the migration already ran; refusing here names the reference instead. + * Thrown by buildExpectedSchema() when one or more identity.references target fields the + * target table does not hold unique: not its primary key, not a plain identity.secondary, + * not a single @unique field. A database refuses such an FK at apply time, after earlier + * statements in the migration already ran; refusing here names every offending reference + * at once, so a model with several is fixed in one pass rather than one run per reference. */ export class FkTargetNotUniqueError extends Error { override readonly name = "FkTargetNotUniqueError"; - readonly entityName: string; - readonly referenceName: string; - readonly targetEntityName: string; - readonly targetFields: string[]; + readonly violations: FkTargetViolation[]; - constructor(entityName: string, referenceName: string, targetEntityName: string, targetFields: string[]) { - const fieldList = targetFields.join(", "); - super( - `Entity "${entityName}": reference "${referenceName}" targets [${fieldList}] on "${targetEntityName}", ` + - `which is not a unique key there (not its primary key, an identity.secondary without @where/@expr, or a @unique field). ` + - `A database refuses this foreign key. Fix: declare an identity.secondary on "${targetEntityName}" with @fields [${fieldList}].`, - ); - this.entityName = entityName; - this.referenceName = referenceName; - this.targetEntityName = targetEntityName; - this.targetFields = targetFields; + constructor(violations: FkTargetViolation[]) { + const lines = violations.map((v) => { + const fieldList = v.targetFields.join(", "); + return `Entity "${v.entityName}": reference "${v.referenceName}" targets [${fieldList}] on "${v.targetEntityName}", ` + + `which is not a unique key there (not its primary key, an identity.secondary without @where/@expr, or a @unique field). ` + + `Fix: declare an identity.secondary on "${v.targetEntityName}" with @fields [${fieldList}].`; + }); + const head = violations.length === 1 + ? "A database refuses this foreign key." + : `A database refuses these ${violations.length} foreign keys.`; + super(`${head}\n${lines.map((l) => ` - ${l}`).join("\n")}`); + this.violations = violations; } } @@ -309,6 +316,11 @@ export function isDuplicateSqlNameError(err: unknown): err is DuplicateSqlNameEr return err instanceof Error && err.name === "DuplicateSqlNameError"; } +/** Is `err` the {@link FkTargetNotUniqueError} from FKs whose targets are not unique keys? */ +export function isFkTargetNotUniqueError(err: unknown): err is FkTargetNotUniqueError { + return err instanceof Error && err.name === "FkTargetNotUniqueError"; +} + /** Is `err` the {@link DeclaredRenameError} from a declared rename that does not apply? */ export function isDeclaredRenameError(err: unknown): err is DeclaredRenameError { return err instanceof Error && err.name === "DeclaredRenameError"; diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 13eef0aae9..82f9f1b0dd 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,4 +1,4 @@ -import { DuplicateSqlNameError, FkTargetNotUniqueError } from "./errors.js"; +import { DuplicateSqlNameError, FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, } from "@metaobjectsdev/metadata"; @@ -254,12 +254,14 @@ export function buildExpectedSchemaWithProvenance( // them — a TPH subtype, for one, shares its base's table and declares none of its own). const provenance = new Map(); - // Pass 2: build full descriptors with FK resolution. + // Pass 2: build full descriptors with FK resolution. Every FK whose target is not a + // unique key is collected here and refused once, after every table is built. + const fkTargetViolations: FkTargetViolation[] = []; // Schema is resolved here (not stored in Pass 1) to avoid exactOptionalPropertyTypes // issues with `string | undefined` vs `schema?: string`. const tables: TableDescriptor[] = entities.map(({ entity, tableName }) => { const t = buildTable( - entity, tableName, resolveTargetTable, root as MetaRoot, strategy, dialect, opts?.onReferentialActionConflict, + entity, tableName, resolveTargetTable, root as MetaRoot, strategy, dialect, fkTargetViolations, opts?.onReferentialActionConflict, ); const schema = resolveTableSchema(entity); if (schema !== undefined) t.schema = schema; @@ -267,6 +269,8 @@ export function buildExpectedSchemaWithProvenance( return t; }); + if (fkTargetViolations.length > 0) throw new FkTargetNotUniqueError(fkTargetViolations); + // Pass 3: dialect-specific SqlType normalization. if (dialect === "sqlite") { for (const table of tables) { @@ -518,6 +522,7 @@ function buildTable( root: MetaRoot, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, + fkTargetViolations: FkTargetViolation[], onConflict?: (conflict: ReferentialActionConflict) => void, ): TableDescriptor { // Use effective accessors so inherited fields/identities (from `extends:` / @@ -601,7 +606,7 @@ function buildTable( name: tableName, columns, indexes: buildSecondaryIndexes(entity, tableName, strategy), - foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, onConflict), + foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, fkTargetViolations, onConflict), checks: buildChecks(entity, tableName, strategy, dialect), primaryKey, }; @@ -975,6 +980,7 @@ function buildForeignKeys( resolveTargetTable: (target: MetaObject) => string | undefined, root: MetaRoot, strategy: ColumnNamingStrategy, + fkTargetViolations: FkTargetViolation[], onConflict?: (conflict: ReferentialActionConflict) => void, ): FkDescriptor[] { const fks: FkDescriptor[] = []; @@ -1026,7 +1032,10 @@ function buildForeignKeys( // Guard: an explicit target must be a unique key on the target, or the database // refuses the FK at apply time. The bare form targets the primary key by construction. if (explicitTargetFields.length > 0 && !isUniqueKeyOf(targetObj, explicitTargetFields)) { - throw new FkTargetNotUniqueError(holder.name, refChild.name, targetObj.name, explicitTargetFields); + fkTargetViolations.push({ + entityName: holder.name, referenceName: refChild.name, targetEntityName: targetObj.name, targetFields: explicitTargetFields, + }); + continue; } const refColumns = targetFieldNames.map((jsName) => { const targetField = findField(targetObj, jsName); diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 8104ab2dce..70fbd34765 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -57,6 +57,8 @@ export { DuplicateSqlNameError, allowOptionFor, isBlockedChangesError, isPrimaryKeyChangeError, isDeclaredRenameError, isDuplicateSqlNameError, + isFkTargetNotUniqueError, + FkTargetNotUniqueError, } from "./errors.js"; export type { SqlNameCollision } from "./errors.js"; diff --git a/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts b/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts index ac2f8dacbe..145fd35dc2 100644 --- a/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts @@ -87,6 +87,33 @@ describe("buildExpectedSchema — an FK must reference a unique key", () => { expect(run).toThrow(/identity\.secondary/); }); + test("every offending reference, across tables, in ONE error — not one per run", async () => { + const doc = makeDoc({ references: "Person.code", holderFields: ["personCode"] }); + const children = (doc["metadata.root"] as { children: unknown[] }).children; + children.push({ + "object.entity": { + name: "Badge", + children: [ + { "source.rdb": {} }, + { "field.long": { name: "id" } }, + { "field.long": { name: "ownerRegion" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "ref_owner", "@fields": ["ownerRegion"], "@references": "Person.region" } }, + ], + }, + }); + const root = await loadDoc(doc); + + let caught: unknown; + try { buildExpectedSchema(root); } catch (e) { caught = e; } + + expect(caught).toBeInstanceOf(FkTargetNotUniqueError); + const err = caught as FkTargetNotUniqueError; + expect(err.violations.map((v) => `${v.entityName}.${v.referenceName}`).sort()).toEqual(["Badge.ref_owner", "Visit.ref_person"]); + expect(err.message).toContain('reference "ref_person" targets [code] on "Person"'); + expect(err.message).toContain('reference "ref_owner" targets [region] on "Person"'); + }); + test("a composite target that is not a declared key → throws", async () => { const run = await build({ references: "Person.id,region", holderFields: ["personId", "personRegion"] }); From f1e9838e5c894e13a814acf17e7c2913b1b13712 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 09:35:53 -0500 Subject: [PATCH 003/267] fix(migrate): introspect composite Postgres FKs once per column, in order readPgForeignKeys joined key_column_usage to constraint_column_usage, which carries no column position, so a composite FK read back as the cross product of its columns and its referenced columns (2 -> 4, 3 -> 9). meta migrate reads the expected side back from the shadow database, so the doubled columns reached emitted DDL and Postgres refused it; verify --db misread every composite FK. Read pg_constraint instead, unnesting conkey with confkey so each pair and the FK's own order survive. A live-Postgres test pins a three-column FK listed in a different order from the target key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++ .../migrate-ts/src/introspect/postgres.ts | 47 ++++++++++--------- .../postgres-composite-fk-introspect.test.ts | 46 ++++++++++++++++++ 3 files changed, 79 insertions(+), 22 deletions(-) create mode 100644 server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e1d9cc569..80b55ed382 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,14 @@ here.** ### Fixed +- **Postgres introspection reads a composite foreign key's columns once each, in order.** It joined + `information_schema.key_column_usage` to `constraint_column_usage`, which has no column position, so + every FK column was paired with every referenced column: a two-column FK read back as four columns and + a three-column one as nine. `meta migrate` reads its expected side back from the shadow database, so + the doubled columns reached the emitted DDL, which Postgres refused ("foreign key referenced-columns + list must not contain duplicates"); `verify --db` misreported every composite FK. It now reads + `pg_constraint`, pairing `conkey` with `confkey` by position. + - **Python: an array field's `default` generated a string.** A model with `field.string[]: { default: "{}" }` generated `tags: list[str] = '{}'`, which fails on first use. It now generates `tags: list[str] = []`, from the same four spellings TypeScript accepts, or diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index 16008bfd43..080bef85a9 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -703,7 +703,7 @@ export function indexDefKeyExpr(indexdef: string): string { } async function readPgForeignKeys(k: RawKysely, schema: string, table: string): Promise { - // pg-mem gap: information_schema.referential_constraints is not supported — + // pg-mem gap: pg_constraint (and the information_schema views before it) is not supported — // the query returns empty rows or throws. We catch and return [] so other // tests still pass on pg-mem. Real PG (Postgres 16) handles this correctly. let rows: { rows: Array<{ fk_name: string; column_name: string; ref_table: string; ref_column: string; update_rule: string; delete_rule: string; ordinal: number }> }; @@ -717,27 +717,30 @@ async function readPgForeignKeys(k: RawKysely, schema: string, table: string): P delete_rule: string; ordinal: number; }>` - SELECT tc.constraint_name AS fk_name, - kcu.column_name, - ccu.table_name AS ref_table, - ccu.column_name AS ref_column, - rc.update_rule, - rc.delete_rule, - kcu.ordinal_position AS ordinal - FROM information_schema.table_constraints tc - JOIN information_schema.key_column_usage kcu - ON kcu.constraint_name = tc.constraint_name - AND kcu.table_schema = tc.table_schema - JOIN information_schema.referential_constraints rc - ON rc.constraint_name = tc.constraint_name - AND rc.constraint_schema = tc.table_schema - JOIN information_schema.constraint_column_usage ccu - ON ccu.constraint_name = tc.constraint_name - AND ccu.table_schema = tc.table_schema - WHERE tc.constraint_type = 'FOREIGN KEY' - AND tc.table_schema = ${schema} - AND tc.table_name = ${table} - ORDER BY tc.constraint_name, kcu.ordinal_position + -- pg_constraint, not information_schema: constraint_column_usage has no column + -- position, so joining it to key_column_usage paired every FK column with every + -- referenced column (a two-column FK read back as four). conkey and confkey are + -- parallel arrays; unnesting them together keeps each pair and the FK's order. + SELECT con.conname AS fk_name, + a.attname AS column_name, + rt.relname AS ref_table, + ra.attname AS ref_column, + CASE con.confupdtype WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'r' THEN 'RESTRICT' + WHEN 'd' THEN 'SET DEFAULT' ELSE 'NO ACTION' END AS update_rule, + CASE con.confdeltype WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'r' THEN 'RESTRICT' + WHEN 'd' THEN 'SET DEFAULT' ELSE 'NO ACTION' END AS delete_rule, + key.ord AS ordinal + FROM pg_constraint con + JOIN pg_class t ON t.oid = con.conrelid + JOIN pg_namespace n ON n.oid = t.relnamespace + JOIN pg_class rt ON rt.oid = con.confrelid + CROSS JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS key(attnum, refattnum, ord) + JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = key.attnum + JOIN pg_attribute ra ON ra.attrelid = con.confrelid AND ra.attnum = key.refattnum + WHERE con.contype = 'f' + AND n.nspname = ${schema} + AND t.relname = ${table} + ORDER BY con.conname, key.ord `.execute(k); } catch { // pg-mem: referential_constraints not supported — return empty FK list. diff --git a/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts b/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts new file mode 100644 index 0000000000..200716534f --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts @@ -0,0 +1,46 @@ +/** + * Composite foreign keys introspect as the columns they have, paired in order. + * + * information_schema.constraint_column_usage carries no column position, so joining it + * to key_column_usage pairs every FK column with every referenced column: a two-column + * FK read back as four columns, a three-column one as nine. `meta migrate` reads its + * expected side back from a shadow database, so the cross product reached the emitted + * DDL ("foreign key referenced-columns list must not contain duplicates"). The FK below + * also lists its columns in a different order from the target key, so a reader that + * pairs by position in the target rather than in the FK fails too. + */ +import { describe, test, expect } from "bun:test"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { Pool } from "pg"; +import { introspectPostgres } from "../../src/introspect/postgres.js"; + +const PG_URL = process.env.MIGRATE_TS_PG_URL; +const d = PG_URL ? describe : describe.skip; + +d("postgres composite FK introspection (real PG)", () => { + test("reads each composite FK column once, paired with its referenced column", async () => { + const k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: PG_URL }) }) }); + const p = "cfk_parent_" + Math.random().toString(36).slice(2, 8); + const c = "cfk_child_" + Math.random().toString(36).slice(2, 8); + try { + await sql.raw(`CREATE TABLE ${p} ( id INTEGER PRIMARY KEY, region INTEGER NOT NULL, kind INTEGER NOT NULL )`).execute(k); + await sql.raw(`CREATE UNIQUE INDEX ${p}_ak ON ${p} (id, region, kind)`).execute(k); + await sql.raw( + `CREATE TABLE ${c} ( id INTEGER PRIMARY KEY, p_kind INTEGER, p_id INTEGER, p_region INTEGER, ` + + `CONSTRAINT ${c}_fk FOREIGN KEY (p_kind, p_id, p_region) REFERENCES ${p} (kind, id, region) ON DELETE RESTRICT )`, + ).execute(k); + + const snap = await introspectPostgres(k); + const fk = snap.tables.find((x) => x.name === c)!.foreignKeys.find((f) => f.name === `${c}_fk`)!; + + expect(fk.columns).toEqual(["p_kind", "p_id", "p_region"]); + expect(fk.refColumns).toEqual(["kind", "id", "region"]); + expect(fk.refTable).toBe(p); + expect(fk.onDelete).toBe("restrict"); + } finally { + await sql.raw(`DROP TABLE IF EXISTS ${c}`).execute(k); + await sql.raw(`DROP TABLE IF EXISTS ${p}`).execute(k); + await k.destroy(); + } + }); +}); From b4437fd6646c71b66f87115aa1791c56c2ebe83b Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 10:01:56 -0500 Subject: [PATCH 004/267] fix(prerelease): only CHANGELOG sections on the released major line pick the base decideBase treated every [x.y.z] section newer than the released version as unpublished, and the CHANGELOG still carries the old Maven-only [7.x] sections, so with 1.2.0 released a cut proposed 7.20.12-rc.N. Filter the sections to the released major line, as latestReleaseTag already does for tags. An explicit --base is no longer refused for skipping a [7.x] section. Co-Authored-By: Claude Opus 5.5 --- scripts/prerelease-version.mjs | 7 ++++++- scripts/test-prerelease-version.mjs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/scripts/prerelease-version.mjs b/scripts/prerelease-version.mjs index ac359d4f11..c392a9d483 100644 --- a/scripts/prerelease-version.mjs +++ b/scripts/prerelease-version.mjs @@ -61,7 +61,12 @@ export function decideBase({ released, changelog, explicit }) { "Pass --base (the CHANGELOG section being prepared).", ); } - const unpublished = changelog.filter((v) => cmpVer(v, released) > 0).sort(cmpVer); + // Only sections on the released major line: the CHANGELOG also carries the old Maven-only + // [7.x] sections, which sort above every 1.x number and were proposed as the next base. + const major = Number(released.split(".")[0]); + const unpublished = changelog + .filter((v) => Number(v.split(".")[0]) === major && cmpVer(v, released) > 0) + .sort(cmpVer); if (explicit != null) { if (cmpVer(explicit, released) <= 0) throw new Error(`--base ${explicit} is not newer than the released ${released}`); diff --git a/scripts/test-prerelease-version.mjs b/scripts/test-prerelease-version.mjs index d417c7a0e5..e4b41383fc 100644 --- a/scripts/test-prerelease-version.mjs +++ b/scripts/test-prerelease-version.mjs @@ -7,6 +7,8 @@ // skips an unpublished CHANGELOG section (release prep bumped package.json to 1.1.0 and the // next rc went out as 1.2.0-rc.3). // P2 the iteration counter reads every page of the registry's listing. +// P4 only CHANGELOG sections on the released major line count; the old Maven-only [7.x] sections +// made a cut after 1.2.0 propose 7.20.12. // P3 a SIGTERM restores the version files, as exit and SIGINT already did, and stops a step that // is still running instead of letting the run publish the remaining registries first. import assert from "node:assert/strict"; @@ -36,6 +38,16 @@ await test("the release tag is the highest plain tag on the npm major line", () assert.equal(latestReleaseTag(["v7.20.12"], 1), null); }); +await test("P4: a section from another major line (the old Maven-only [7.x]) is never the base", () => { + // 1.2.0 released; the CHANGELOG still carries historical Maven-only sections such as [7.20.12], + // which sort above every 1.x number. The cut must be 1.3.0 (nothing on 1.x is unpublished), not 7.20.12. + const md = "## [Unreleased]\n\n## [1.2.0] — 2026-10-30\n\n## [1.1.4]\n\n## [7.20.12] — 2026-08-02\n"; + assert.deepEqual(decideBase({ released: "1.2.0", changelog: changelogVersions(md), explicit: null }), + { base: "1.3.0", source: "guessed from released 1.2.0" }); + // and an explicit --base is not refused for "skipping" a section on another line + assert.equal(decideBase({ released: "1.2.0", changelog: changelogVersions(md), explicit: "1.2.1" }).base, "1.2.1"); +}); + await test("P1: release prep's package.json bump does not make 1.1.0 'released'", () => { // package.json says 1.1.0 (the prep PR); npm and the tags say 1.0.13. const released = releasedVersion({ npmLatest: "1.0.13", tags: ["v1.0.13", "v1.1.0-rc.2"], major: 1 }); From bc26c29b3fd27671d8e9b45a34c6535f32b2464f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 10:05:29 -0500 Subject: [PATCH 005/267] feat(migrate): schema conventions for the objects no code addresses A SchemaConventions object decides primary-key and foreign-key constraint names, whether a foreign key gets an index and what it is called, and whether a unique key is an index or a constraint. buildExpectedSchema takes it as `conventions`; a declared @constraintName and an index node's name still win. Two presets: `default`, what migrate has always emitted (the expected schema is unchanged, so no snapshot churns), and `efcore`, EF Core's conventions (PK_/FK_/IX_ names with its 63-character `~` truncation, an index on every FK not led by an existing key, and alternate keys as UNIQUE constraints), so a database first built by EF Core migrations and one built by meta migrate have the same catalog. TableDescriptor gains primaryKeyName (absent = _pkey), rendered at create and not compared; an expected index may now carry constraint: "unique", rendered as ADD CONSTRAINT ... UNIQUE, still not compared. Co-Authored-By: Claude Opus 5.5 --- .../packages/migrate-ts/src/emit/postgres.ts | 15 ++- .../migrate-ts/src/expected-schema.ts | 68 ++++++++++- .../packages/migrate-ts/src/index.ts | 4 + .../migrate-ts/src/schema-conventions.ts | 102 ++++++++++++++++ .../packages/migrate-ts/src/types.ts | 15 ++- .../unit/expected-schema-conventions.test.ts | 111 ++++++++++++++++++ .../test/unit/schema-conventions.test.ts | 73 ++++++++++++ 7 files changed, 376 insertions(+), 12 deletions(-) create mode 100644 server/typescript/packages/migrate-ts/src/schema-conventions.ts create mode 100644 server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts create mode 100644 server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index 4f367f9344..f38f1d5b81 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -377,7 +377,10 @@ function renderDown(c: Change, recreated: ReadonlySet = new Set()): stri : `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} DROP DEFAULT;`; case "change-column-identity": return renderIdentity(c.table, c.schema, c.column, c.from); case "change-comment": return renderComment(c.table, c.schema, c.column, c.from); - case "add-index": return `DROP INDEX ${quoteIndexQualified(c.index.name, c.schema)};`; + case "add-index": + return isUniqueConstraint(c.index) + ? `ALTER TABLE ${quoteQualified(c.table, c.schema)} DROP CONSTRAINT ${quote(c.index.name)};` + : `DROP INDEX ${quoteIndexQualified(c.index.name, c.schema)};`; case "drop-index": // #285: the up dropped a CONSTRAINT, so the down must add one back — recreating a // bare unique index would leave the database in a different shape than it started @@ -432,7 +435,7 @@ function renderDown(c: Change, recreated: ReadonlySet = new Set()): stri function renderCreateTable(t: TableDescriptor): string { const colDefs = t.columns.map((c) => ` ${renderColumn(c)}`); if (t.primaryKey.length > 0) { - colDefs.push(` CONSTRAINT ${quote(t.name + "_pkey")} PRIMARY KEY (${t.primaryKey.map(quote).join(", ")})`); + colDefs.push(` CONSTRAINT ${quote(t.primaryKeyName ?? t.name + "_pkey")} PRIMARY KEY (${t.primaryKey.map(quote).join(", ")})`); } for (const chk of t.checks ?? []) { colDefs.push(` CONSTRAINT ${quote(chk.name)} CHECK (${chk.expression})`); @@ -543,7 +546,15 @@ function renderDefault(d: ColumnDefault): string { return `'${pgEscape(d.value)}'`; } +/** A unique key the schema conventions create as a constraint (only a plain column key can be one). */ +function isUniqueConstraint(ix: IndexDescriptor): boolean { + return ix.constraint === "unique" && ix.unique && ix.where === undefined && ix.expr === undefined; +} + function renderCreateIndex(table: string, schema: string | undefined, ix: IndexDescriptor): string { + if (isUniqueConstraint(ix)) { + return `ALTER TABLE ${quoteQualified(table, schema)} ADD CONSTRAINT ${quote(ix.name)} UNIQUE (${ix.columns.map(quote).join(", ")});`; + } const u = ix.unique ? "UNIQUE " : ""; // Key list: a raw expression (functional/expression index) takes precedence over // the per-column list. The expression is emitted verbatim (already valid SQL). diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 82f9f1b0dd..4d36683426 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,4 +1,5 @@ import { DuplicateSqlNameError, FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; +import { defaultConventions, type SchemaConventions } from "./schema-conventions.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, } from "@metaobjectsdev/metadata"; @@ -106,6 +107,12 @@ export interface BuildExpectedSchemaOptions { * Advisory: the schema built is the same with or without it. */ onReferentialActionConflict?: (conflict: ReferentialActionConflict) => void; + /** + * Names and physical choices for the objects no code addresses (PK and FK constraint + * names, FK indexes, unique key kind). Absent = `defaultConventions`, what migrate has + * always emitted. + */ + conventions?: SchemaConventions | undefined; } /** @@ -257,11 +264,13 @@ export function buildExpectedSchemaWithProvenance( // Pass 2: build full descriptors with FK resolution. Every FK whose target is not a // unique key is collected here and refused once, after every table is built. const fkTargetViolations: FkTargetViolation[] = []; + const conventions = opts?.conventions ?? defaultConventions; + const fkCtx: ForeignKeyBuildContext = { conventions, violations: fkTargetViolations }; // Schema is resolved here (not stored in Pass 1) to avoid exactOptionalPropertyTypes // issues with `string | undefined` vs `schema?: string`. const tables: TableDescriptor[] = entities.map(({ entity, tableName }) => { const t = buildTable( - entity, tableName, resolveTargetTable, root as MetaRoot, strategy, dialect, fkTargetViolations, opts?.onReferentialActionConflict, + entity, tableName, resolveTargetTable, root as MetaRoot, strategy, dialect, fkCtx, opts?.onReferentialActionConflict, ); const schema = resolveTableSchema(entity); if (schema !== undefined) t.schema = schema; @@ -270,6 +279,7 @@ export function buildExpectedSchemaWithProvenance( }); if (fkTargetViolations.length > 0) throw new FkTargetNotUniqueError(fkTargetViolations); + applySchemaConventions(tables, conventions); // Pass 3: dialect-specific SqlType normalization. if (dialect === "sqlite") { @@ -522,7 +532,7 @@ function buildTable( root: MetaRoot, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, - fkTargetViolations: FkTargetViolation[], + fkCtx: ForeignKeyBuildContext, onConflict?: (conflict: ReferentialActionConflict) => void, ): TableDescriptor { // Use effective accessors so inherited fields/identities (from `extends:` / @@ -606,7 +616,7 @@ function buildTable( name: tableName, columns, indexes: buildSecondaryIndexes(entity, tableName, strategy), - foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, fkTargetViolations, onConflict), + foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, fkCtx, onConflict), checks: buildChecks(entity, tableName, strategy, dialect), primaryKey, }; @@ -980,7 +990,7 @@ function buildForeignKeys( resolveTargetTable: (target: MetaObject) => string | undefined, root: MetaRoot, strategy: ColumnNamingStrategy, - fkTargetViolations: FkTargetViolation[], + fkCtx: ForeignKeyBuildContext, onConflict?: (conflict: ReferentialActionConflict) => void, ): FkDescriptor[] { const fks: FkDescriptor[] = []; @@ -1032,7 +1042,7 @@ function buildForeignKeys( // Guard: an explicit target must be a unique key on the target, or the database // refuses the FK at apply time. The bare form targets the primary key by construction. if (explicitTargetFields.length > 0 && !isUniqueKeyOf(targetObj, explicitTargetFields)) { - fkTargetViolations.push({ + fkCtx.violations.push({ entityName: holder.name, referenceName: refChild.name, targetEntityName: targetObj.name, targetFields: explicitTargetFields, }); continue; @@ -1056,7 +1066,7 @@ function buildForeignKeys( const constraintName = typeof constraintNameOverride === "string" && constraintNameOverride.length > 0 ? constraintNameOverride - : `${tableName}_${fkCols[0]}_fk`; + : fkCtx.conventions.foreignKeyName({ table: tableName, columns: fkCols, refTable, refColumns }); // Guard: ON DELETE SET NULL requires nullable FK columns. validateSetNullNullability(holder, refChild, onDelete, constraintName); @@ -1076,6 +1086,52 @@ function buildForeignKeys( return fks; } +/** What building a table's foreign keys needs beyond the table: the conventions, and where refusals go. */ +interface ForeignKeyBuildContext { + conventions: SchemaConventions; + violations: FkTargetViolation[]; +} + +/** + * The schema conventions' second pass, over every built table: the primary key's name, the + * kind of each unique key (an FK anywhere in the model may reference it), and the index each + * foreign key gets. FK names were decided while the FKs were built, where a declared + * `@constraintName` is known. The default conventions change nothing here. + */ +function applySchemaConventions(tables: TableDescriptor[], conventions: SchemaConventions): void { + const keyOf = (table: string, columns: readonly string[]) => `${table}|${[...columns].sort().join(",")}`; + const referenced = new Set(tables.flatMap((t) => t.foreignKeys.map((fk) => keyOf(fk.refTable, fk.refColumns)))); + for (const t of tables) { + if (t.primaryKey.length > 0) { + const pkName = conventions.primaryKeyName({ table: t.name, columns: t.primaryKey }); + if (pkName !== `${t.name}_pkey`) t.primaryKeyName = pkName; + } + for (const ix of t.indexes) { + if (!ix.unique || ix.where !== undefined || ix.expr !== undefined) continue; + const kind = conventions.uniqueKeyKind({ table: t.name, columns: ix.columns, referencedByForeignKey: referenced.has(keyOf(t.name, ix.columns)) }); + if (kind === "constraint") ix.constraint = "unique"; + } + for (const fk of t.foreignKeys) { + const index = conventions.foreignKeyIndex( + { table: t.name, columns: fk.columns, refTable: fk.refTable, refColumns: fk.refColumns }, + { primaryKey: t.primaryKey, indexes: t.indexes }, + ); + if (index === undefined) continue; + if (t.indexes.some((ix) => ix.name === index.name)) { + throw new DuplicateSqlNameError([{ + name: index.name, + owners: [ + `the ${conventions.id} conventions' index for foreign key "${fk.name}" on table "${t.name}"`, + `an index already named "${index.name}" on table "${t.name}"`, + ], + involvesIndex: true, + }]); + } + t.indexes.push({ name: index.name, columns: [...fk.columns], unique: false }); + } + } +} + /** * True when `fieldNames` (in any order) are a key the target table holds unique: exactly its * primary key, exactly a plain identity.secondary (a partial or expression index is not a key diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 70fbd34765..8329065195 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -17,6 +17,10 @@ export { export type { ExpectedSchemaWithProvenance, SchemaProvenance } from "./expected-schema.js"; export { introspect, introspectPostgres, introspectSqlite } from "./introspect/index.js"; export { diff } from "./diff/index.js"; +export { + defaultConventions, efcoreConventions, resolveSchemaConventions, SCHEMA_CONVENTION_PRESETS, + type SchemaConventions, type KeyContext, type ForeignKeyContext, type ExistingKeys, +} from "./schema-conventions.js"; export { collectUnmanagedNames } from "./unmanaged.js"; // Per-command scope (`migrate.scope`) — see scope.ts for why the suppression is // two-sided and why the pattern engine stays in @metaobjectsdev/sdk. diff --git a/server/typescript/packages/migrate-ts/src/schema-conventions.ts b/server/typescript/packages/migrate-ts/src/schema-conventions.ts new file mode 100644 index 0000000000..6b31d78b87 --- /dev/null +++ b/server/typescript/packages/migrate-ts/src/schema-conventions.ts @@ -0,0 +1,102 @@ +/** + * Schema conventions: the names and physical choices for database objects that NO CODE + * ADDRESSES — primary-key and foreign-key constraint names, whether a foreign key gets an + * index and what it is called, and whether a unique key is created as an index or a + * constraint. + * + * Names that code does address — tables, views, columns, and any constraint or index a + * program compares against — are not decided here. They resolve in core naming + * (`naming` in `.metaobjects/config.json`) and from metadata overrides, the same in every + * port. A metadata override always beats a convention: `@constraintName` on an + * `identity.reference`, and an index node's own name. + * + * Selected with `migrate.conventions` in `.metaobjects/config.json` (a preset name), or + * supplied as an object by the project (`migrate.conventions` in `metaobjects.config.ts`). + * `default` is what migrate has always emitted, so a project that sets nothing sees no + * change; `efcore` reproduces EF Core's conventions, for a database first built by EF + * Core migrations. + */ + +/** A key on one table: the table's database name and the key's columns, in key order. */ +export interface KeyContext { + table: string; + columns: readonly string[]; +} + +/** A foreign key: its own columns, and the table and columns it references. */ +export interface ForeignKeyContext extends KeyContext { + refTable: string; + refColumns: readonly string[]; +} + +/** What a table already has that may already serve as a foreign key's index. */ +export interface ExistingKeys { + primaryKey: readonly string[]; + indexes: readonly { columns: readonly string[]; where?: string; expr?: string }[]; +} + +export interface SchemaConventions { + /** Shown in diagnostics; a preset's name, or the project's own. */ + readonly id: string; + primaryKeyName(key: KeyContext): string; + /** Used when the identity.reference declares no `@constraintName`. */ + foreignKeyName(fk: ForeignKeyContext): string; + /** The index a foreign key gets, or undefined for none. */ + foreignKeyIndex(fk: ForeignKeyContext, existing: ExistingKeys): { name: string } | undefined; + /** How a unique key (`identity.secondary`) is created. A partial or expression key is always an index. */ + uniqueKeyKind(key: KeyContext & { referencedByForeignKey: boolean }): "index" | "constraint"; +} + +/** Postgres's identifier limit (NAMEDATALEN - 1). */ +const MAX_IDENTIFIER_LENGTH = 63; + +/** EF Core's truncation: a name over the limit keeps its first 62 characters and ends in `~`. */ +function efTruncate(name: string): string { + return name.length <= MAX_IDENTIFIER_LENGTH ? name : `${name.slice(0, MAX_IDENTIFIER_LENGTH - 1)}~`; +} + +/** True when `columns` are the leading columns of `key`, in order. */ +function startsWith(key: readonly string[], columns: readonly string[]): boolean { + return columns.length > 0 && columns.length <= key.length && columns.every((c, i) => key[i] === c); +} + +export const defaultConventions: SchemaConventions = { + id: "default", + primaryKeyName: ({ table }) => `${table}_pkey`, + foreignKeyName: ({ table, columns }) => `${table}_${columns[0]}_fk`, + foreignKeyIndex: () => undefined, + uniqueKeyKind: () => "index", +}; + +export const efcoreConventions: SchemaConventions = { + id: "efcore", + primaryKeyName: ({ table }) => efTruncate(`PK_${table}`), + foreignKeyName: ({ table, columns, refTable }) => efTruncate(`FK_${table}_${refTable}_${columns.join("_")}`), + // EF Core indexes every foreign key unless a key or index already starts with its columns. + foreignKeyIndex: (fk, existing) => { + if (startsWith(existing.primaryKey, fk.columns)) return undefined; + const covered = existing.indexes.some((ix) => ix.where === undefined && ix.expr === undefined && startsWith(ix.columns, fk.columns)); + return covered ? undefined : { name: efTruncate(`IX_${fk.table}_${fk.columns.join("_")}`) }; + }, + // An alternate key (one an FK references) is a UNIQUE constraint; any other unique key is an index. + uniqueKeyKind: ({ referencedByForeignKey }) => (referencedByForeignKey ? "constraint" : "index"), +}; + +const PRESETS: Readonly> = { + [defaultConventions.id]: defaultConventions, + [efcoreConventions.id]: efcoreConventions, +}; + +/** The preset names `migrate.conventions` accepts in `.metaobjects/config.json`. */ +export const SCHEMA_CONVENTION_PRESETS = Object.keys(PRESETS) as readonly string[]; + +/** A preset by name, a project-supplied object as itself, and nothing as `default`. */ +export function resolveSchemaConventions(selected: string | SchemaConventions | undefined): SchemaConventions { + if (selected === undefined) return defaultConventions; + if (typeof selected !== "string") return selected; + const preset = PRESETS[selected]; + if (preset === undefined) { + throw new Error(`unknown schema conventions "${selected}": expected one of ${SCHEMA_CONVENTION_PRESETS.join(", ")}`); + } + return preset; +} diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts index b08fb361db..29b32a2928 100644 --- a/server/typescript/packages/migrate-ts/src/types.ts +++ b/server/typescript/packages/migrate-ts/src/types.ts @@ -39,6 +39,12 @@ export interface TableDescriptor { foreignKeys: FkDescriptor[]; checks: CheckDescriptor[]; primaryKey: string[]; // column names; [] if none + /** + * The primary-key constraint's name, when the project's schema conventions name it + * something other than `
_pkey` (absent = `
_pkey`, which keeps every + * existing snapshot byte-identical). Rendered at create; not compared by the diff. + */ + primaryKeyName?: string; /** * Human-readable description threaded from entity `@description`. * Postgres: emitted as `COMMENT ON TABLE … IS '…';` after CREATE TABLE. @@ -112,10 +118,11 @@ export interface IndexDescriptor { * refuses `DROP INDEX` on such an index ("cannot drop index X because constraint * X on table Y requires it"), so the emitter must drop the CONSTRAINT instead. * - * Never authored in metadata and never present on the expected side — it describes - * how the database happens to hold an index, not what the model asks for. It is - * therefore deliberately NOT compared by `indexEquals`: a unique index and a unique - * constraint over the same columns are the same model-level thing. + * Never authored in metadata. On the expected side it is set only by the project's + * schema conventions (`uniqueKeyKind`), so the emitter creates the key as a UNIQUE + * constraint (EF Core's alternate keys are constraints). It is deliberately NOT + * compared by `indexEquals`: a unique index and a unique constraint over the same + * columns are the same model-level thing, so an existing database never churns. * * This matters far beyond an edge case: Drizzle's `unique()` produces constraints, * so every adopter migrating from a Drizzle-managed schema has constraint-backed diff --git a/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts new file mode 100644 index 0000000000..3f4efb5ec8 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts @@ -0,0 +1,111 @@ +/** + * buildExpectedSchema applies the project's schema conventions to the objects no code + * addresses, and the Postgres emitter renders what they decide. A metadata override + * (`@constraintName`, an index node's name) still wins, and the `default` conventions + * leave the expected schema exactly as it has always been. + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { efcoreConventions } from "../../src/schema-conventions.js"; +import { emit } from "../../src/emit/index.js"; +import { diff } from "../../src/diff/index.js"; + +const DOC = { + "metadata.root": { + package: "acme", + children: [ + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "Orders" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }, + { "object.entity": { name: "OrderLine", children: [ + { "source.rdb": { "@table": "OrderLines" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.long": { name: "orderId", "@column": "OrderId" } }, + { "field.long": { name: "replacesOrderId", "@column": "ReplacesOrderId" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "identity.reference": { name: "order", "@fields": ["orderId"], "@references": "Order" } }, + { "identity.reference": { name: "replaces", "@fields": ["replacesOrderId"], "@references": "Order", "@constraintName": "FK_Legacy_Name" } }, + ] } }, + { "object.entity": { name: "Region", children: [ + { "source.rdb": { "@table": "Regions" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.string": { name: "code", "@column": "Code" } }, + { "field.string": { name: "name", "@column": "Name" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "identity.secondary": { name: "AK_Regions_Code", "@fields": ["code"] } }, + { "identity.secondary": { name: "IX_Regions_Name", "@fields": ["name"] } }, + ] } }, + { "object.entity": { name: "Store", children: [ + { "source.rdb": { "@table": "Stores" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.string": { name: "regionCode", "@column": "RegionCode" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "index.lookup": { name: "IX_Stores_RegionCode_Id", "@fields": ["regionCode", "id"] } }, + { "identity.reference": { name: "region", "@fields": ["regionCode"], "@references": "Region.code" } }, + ] } }, + ], + }, +}; + +async function load() { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(DOC))]); + expect(errors).toHaveLength(0); + return root; +} + +const table = (s: ReturnType, name: string) => s.tables.find((t) => t.name === name)!; + +describe("buildExpectedSchema with the efcore conventions", () => { + test("PK and FK names follow EF Core; a declared @constraintName still wins", async () => { + const s = buildExpectedSchema(await load(), { conventions: efcoreConventions }); + + expect(table(s, "Orders").primaryKeyName).toBe("PK_Orders"); + expect(table(s, "OrderLines").foreignKeys.map((f) => f.name).sort()).toEqual(["FK_Legacy_Name", "FK_OrderLines_Orders_OrderId"]); + }); + + test("an FK gets an IX_ index unless an existing index already starts with its columns", async () => { + const s = buildExpectedSchema(await load(), { conventions: efcoreConventions }); + + expect(table(s, "OrderLines").indexes.map((i) => [i.name, i.columns, i.unique])).toEqual([ + ["IX_OrderLines_OrderId", ["OrderId"], false], + ["IX_OrderLines_ReplacesOrderId", ["ReplacesOrderId"], false], + ]); + // IX_Stores_RegionCode_Id already leads with RegionCode + expect(table(s, "Stores").indexes.map((i) => i.name)).toEqual(["IX_Stores_RegionCode_Id"]); + }); + + test("a unique key an FK references is a constraint; another stays an index", async () => { + const s = buildExpectedSchema(await load(), { conventions: efcoreConventions }); + const kinds = Object.fromEntries(table(s, "Regions").indexes.map((i) => [i.name, i.constraint ?? "index"])); + + expect(kinds).toEqual({ AK_Regions_Code: "unique", IX_Regions_Name: "index" }); + }); + + test("the Postgres emitter renders the PK name and the unique constraint", async () => { + const s = buildExpectedSchema(await load(), { conventions: efcoreConventions }); + const { changes } = await diff(s, { tables: [], views: [] }, { dialect: "postgres" }); + const { up, down } = emit(changes, { dialect: "postgres" }); + + expect(up).toContain('CONSTRAINT "PK_Orders" PRIMARY KEY ("Id")'); + expect(up).toContain('ALTER TABLE "Regions" ADD CONSTRAINT "AK_Regions_Code" UNIQUE ("Code");'); + expect(up).toContain('CREATE UNIQUE INDEX "IX_Regions_Name" ON "Regions" ("Name");'); + expect(up).toContain('CREATE INDEX "IX_OrderLines_OrderId" ON "OrderLines" ("OrderId");'); + expect(down).toContain('ALTER TABLE "Regions" DROP CONSTRAINT "AK_Regions_Code";'); + }); +}); + +describe("buildExpectedSchema with the default conventions", () => { + test("is exactly what it was without any conventions", async () => { + const root = await load(); + + expect(buildExpectedSchema(root, { conventions: undefined })).toEqual(buildExpectedSchema(root)); + const s = buildExpectedSchema(root); + expect(table(s, "Orders").primaryKeyName).toBeUndefined(); + expect(table(s, "OrderLines").foreignKeys.map((f) => f.name).sort()).toEqual(["FK_Legacy_Name", "OrderLines_OrderId_fk"]); + expect(table(s, "OrderLines").indexes).toEqual([]); + expect(table(s, "Regions").indexes.every((i) => i.constraint === undefined)).toBe(true); + }); +}); diff --git a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts new file mode 100644 index 0000000000..2e0568b48c --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts @@ -0,0 +1,73 @@ +/** + * Schema conventions: the names and physical choices for database objects that no code + * addresses — primary-key and foreign-key constraint names, whether a foreign key gets an + * index (and its name), and whether a unique key is an index or a constraint. + * + * `default` is what migrate has always emitted, so a project that sets nothing sees no + * change. `efcore` reproduces EF Core's own conventions, so a database first built by EF + * migrations and one built by `meta migrate` have the same catalog. + */ +import { describe, test, expect } from "bun:test"; +import { + defaultConventions, efcoreConventions, resolveSchemaConventions, SCHEMA_CONVENTION_PRESETS, +} from "../../src/schema-conventions.js"; + +const fk = { table: "OrderLines", columns: ["OrderId"], refTable: "Orders", refColumns: ["Id"] }; + +describe("efcore conventions", () => { + test("PK_{table}, FK_{table}_{principal}_{columns}, IX_{table}_{columns}", () => { + expect(efcoreConventions.primaryKeyName({ table: "Orders", columns: ["Id"] })).toBe("PK_Orders"); + expect(efcoreConventions.foreignKeyName(fk)).toBe("FK_OrderLines_Orders_OrderId"); + expect(efcoreConventions.foreignKeyName({ ...fk, columns: ["OrderId", "Region"], refColumns: ["Id", "Region"] })) + .toBe("FK_OrderLines_Orders_OrderId_Region"); + expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [] })).toEqual({ name: "IX_OrderLines_OrderId" }); + }); + + test("a name over 63 characters is cut to 62 and marked with ~, as EF Core does", () => { + const long = { table: "CaseSupportRequestedTypes", columns: ["SupportRequestedTypeId"], refTable: "SupportRequestedTypes", refColumns: ["Id"] }; + const name = efcoreConventions.foreignKeyName(long); + + expect(name).toBe("FK_CaseSupportRequestedTypes_SupportRequestedTypes_SupportRequ~"); + expect(name.length).toBe(63); + expect(efcoreConventions.primaryKeyName({ table: "A".repeat(61), columns: ["Id"] })).toBe(`PK_${"A".repeat(59)}~`); + }); + + test("no FK index when the primary key or an existing index already starts with the FK's columns", () => { + expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["OrderId", "LineNo"], indexes: [] })).toBeUndefined(); + expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [{ columns: ["OrderId", "Sku"] }] })).toBeUndefined(); + // an index that merely CONTAINS the columns later does not cover them + expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [{ columns: ["Sku", "OrderId"] }] })) + .toEqual({ name: "IX_OrderLines_OrderId" }); + // a partial or expression index does not cover them either + expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [{ columns: ["OrderId"], where: "x" }] })) + .toEqual({ name: "IX_OrderLines_OrderId" }); + }); + + test("a unique key an FK references is a constraint; any other is an index", () => { + expect(efcoreConventions.uniqueKeyKind({ table: "Orders", columns: ["Code"], referencedByForeignKey: true })).toBe("constraint"); + expect(efcoreConventions.uniqueKeyKind({ table: "Orders", columns: ["Code"], referencedByForeignKey: false })).toBe("index"); + }); +}); + +describe("default conventions (what migrate has always emitted)", () => { + test("{table}_pkey, {table}_{firstColumn}_fk, no FK index, unique keys are indexes", () => { + expect(defaultConventions.primaryKeyName({ table: "orders", columns: ["id"] })).toBe("orders_pkey"); + expect(defaultConventions.foreignKeyName({ ...fk, table: "order_lines", columns: ["order_id", "region"] })).toBe("order_lines_order_id_fk"); + expect(defaultConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [] })).toBeUndefined(); + expect(defaultConventions.uniqueKeyKind({ table: "orders", columns: ["code"], referencedByForeignKey: true })).toBe("index"); + }); +}); + +describe("resolveSchemaConventions", () => { + test("a preset by name, a supplied object as itself, nothing as default", () => { + expect(resolveSchemaConventions("efcore")).toBe(efcoreConventions); + expect(resolveSchemaConventions(undefined)).toBe(defaultConventions); + const custom = { ...defaultConventions, id: "acme" }; + expect(resolveSchemaConventions(custom)).toBe(custom); + }); + + test("an unknown preset is refused, naming the ones that exist", () => { + expect(() => resolveSchemaConventions("hibernate")).toThrow(/unknown schema conventions "hibernate".*default, efcore/); + expect(SCHEMA_CONVENTION_PRESETS).toEqual(["default", "efcore"]); + }); +}); From 7dc55e89894aeabc69f5facaa4d80e2ddc0e2c9b Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 10:12:26 -0500 Subject: [PATCH 006/267] feat(migrate): select schema conventions with migrate.conventions `.metaobjects/config.json` `migrate.conventions` names a preset; a project's own SchemaConventions object comes from metaobjects.config.ts (`schemaConventions`) and wins. The project-aware load carries the selection on the root, as it does `naming` and `wire`, so every expected-schema build of one model (migrate, verify --db, the advisories, gen's migrate advice) uses the same conventions without each call site threading them. An unknown preset is refused by name: meta migrate exits 2 with the presets listed, not "unexpected error". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++ docs/features/migrations-and-drift.md | 45 ++++++++++ .../packages/cli/src/commands/migrate.ts | 6 ++ .../cli/src/lib/collection-load-options.ts | 3 +- .../cli/src/lib/load-metaobjects-config.ts | 7 +- .../test/migrate-schema-conventions.test.ts | 84 +++++++++++++++++++ .../codegen-ts/src/metaobjects-config.ts | 8 ++ .../packages/metadata/src/shared/meta-root.ts | 9 ++ .../packages/migrate-ts/src/errors.ts | 13 +++ .../migrate-ts/src/expected-schema.ts | 7 +- .../packages/migrate-ts/src/index.ts | 2 + .../migrate-ts/src/schema-conventions.ts | 6 +- .../unit/expected-schema-conventions.test.ts | 20 +++++ .../test/unit/schema-conventions.test.ts | 2 +- .../typescript/packages/sdk/src/collection.ts | 5 ++ server/typescript/packages/sdk/src/config.ts | 4 + server/typescript/packages/sdk/src/memory.ts | 14 +++- .../test/schema-conventions-config.test.ts | 56 +++++++++++++ 18 files changed, 289 insertions(+), 11 deletions(-) create mode 100644 server/typescript/packages/cli/test/migrate-schema-conventions.test.ts create mode 100644 server/typescript/packages/sdk/test/schema-conventions-config.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 80b55ed382..cb7350f8ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ here.** and the `wire` setting, and a project on any port runs them through the Node `meta` CLI. They are reference helpers: opt-in, listed by `meta gen --list`, ejectable and gated by `verify --codegen` (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. +- **Schema conventions for the database objects no code addresses.** `migrate.conventions` in + `.metaobjects/config.json` picks how `meta migrate` names primary-key and foreign-key + constraints, whether each foreign key gets an index, and whether a unique key an FK references + is a constraint or an index. `default` is what migrate has always emitted, so nothing changes + unless you set it. `efcore` reproduces EF Core's conventions (`PK_`, `FK_`, `IX_`, its + 63-character `~` truncation, alternate keys as constraints), so a database built by EF Core + migrations and one built by `meta migrate` match. A project can supply its own conventions + object from `metaobjects.config.ts`. An unknown preset name is refused by name. See + `docs/features/migrations-and-drift.md`, "Schema conventions". - **A recipe for checking an API change against the last release.** Emit the document at the last tag and at `HEAD`, then run oasdiff. See `docs/recipes/check-api-against-last-release.md`. - **A `pydantic` extra on the Python package.** `pip install "metaobjects[pydantic]"` installs diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 790692ea09..fb1ee13c98 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -370,6 +370,51 @@ opened by an older SQLite (Python 3.10's stdlib, Ubuntu 22.04's `sqlite3`). The behind `--allow drop-check` and raises no data hazard, because the rule is the same — and the re-diff is empty afterwards. Postgres keeps `IS [NOT] DISTINCT FROM`. +## Schema conventions: names for objects no code addresses + +Some database objects have names that no program ever reads: a primary-key constraint, most +foreign-key constraints, the index on a foreign key. Their names, and a few physical choices, +come from the project's **schema conventions**, selected in `.metaobjects/config.json`: + +```json +{ "schema_version": 1, "migrate": { "conventions": "efcore" } } +``` + +| Decides | `default` (absent) | `efcore` | +|---|---|---| +| Primary-key constraint name | `
_pkey` | `PK_
` | +| Foreign-key constraint name | `
__fk` | `FK_
__` | +| Index on a foreign key | none | `IX_
_`, unless the primary key or an index already starts with the FK's columns | +| Unique key (`identity.secondary`) | a unique index | a UNIQUE constraint when a foreign key references it, else a unique index | + +`efcore` reproduces EF Core's own conventions, including its truncation of a name longer +than 63 characters to 62 characters and `~`, so a database first built by EF Core migrations +and one built by `meta migrate` have the same catalog. `default` is what migrate has always +emitted. + +Names code does address are not conventions. Tables, views and columns resolve in core +naming (`naming`, and `@table` / `@column`), the same in every port. A constraint or index a +program compares against (a unique-violation handler checking the constraint name) is +declared in metadata: `@constraintName` on an `identity.reference`, or the index node's own +name. A declared name always wins over a convention. + +A project can supply its own conventions from `metaobjects.config.ts`, which wins over the +preset name: + +```ts +import { defineConfig } from "@metaobjectsdev/cli"; +import { efcoreConventions } from "@metaobjectsdev/migrate-ts"; + +export default defineConfig({ + generators: [/* … */], + schemaConventions: { ...efcoreConventions, id: "acme", primaryKeyName: ({ table }) => `pk_${table}` }, +}); +``` + +The conventions shape what migrate creates. The PK name and whether a unique key is a +constraint or an index are not compared by the diff, so changing them never churns an +existing database; FK and index names are compared, as they always have been. + ## How CHECK constraints and expression indexes are compared Postgres rewrites an expression before it stores it (`"k" IN ('x')` becomes `k = 'x'::text`, diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index b2165b157d..f85c9b62cc 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -22,6 +22,7 @@ import { isDeclaredRenameError, isDuplicateSqlNameError, isFkTargetNotUniqueError, + isUnknownSchemaConventionsError, buildExpectedSchemaWithProvenance, scopeExpectedSchema, scopedDiffInputs, @@ -1156,6 +1157,11 @@ export async function migrateCommand( if (isDuplicateSqlNameError(err)) return refuseEngineError(err, DUPLICATE_SQL_NAME_HINT, fmt); // A metadata defect too: a foreign key whose target columns are not a unique key there. if (isFkTargetNotUniqueError(err)) return refuseEngineError(err, FK_TARGET_NOT_UNIQUE_HINT, fmt); + // A config error: `migrate.conventions` names a preset this version does not ship. + if (isUnknownSchemaConventionsError(err)) { + refuseEngineError(err, "set migrate.conventions in .metaobjects/config.json to one of the presets, or supply your own conventions from metaobjects.config.ts", fmt); + return 2; + } // Unexpected error: emit structured error on stdout in the active format, then exit 1. const msg = describeError(err) ?? String(err); log.error(`migrate: unexpected error: ${msg}`); diff --git a/server/typescript/packages/cli/src/lib/collection-load-options.ts b/server/typescript/packages/cli/src/lib/collection-load-options.ts index c86d74433e..78a7c91bf8 100644 --- a/server/typescript/packages/cli/src/lib/collection-load-options.ts +++ b/server/typescript/packages/cli/src/lib/collection-load-options.ts @@ -26,7 +26,7 @@ import type { Collection, LoadMemoryOptions } from "@metaobjectsdev/sdk"; */ export function collectionLoadOptions( collection: Collection, -): Required> { +): Required> & Pick { return { files: collection.files, fileIds: collection.fileIds, @@ -40,5 +40,6 @@ export function collectionLoadOptions( libraries: collection.libraries, physicalNaming: collection.physicalNaming, wireFormat: collection.wireFormat, + ...(collection.schemaConventions !== undefined ? { schemaConventions: collection.schemaConventions } : {}), }; } diff --git a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts index 848b1e4c30..8d399a0727 100644 --- a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts +++ b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts @@ -216,10 +216,13 @@ function rewriteImportSpecifiers(source: string, aliasMap: Record | undefined, -): { providers?: readonly MetaDataTypeProvider[] } { + cfg: Pick | undefined, +): { providers?: readonly MetaDataTypeProvider[]; schemaConventions?: unknown } { return { ...(cfg?.providers !== undefined ? { providers: cfg.providers } : {}), + // A project's own conventions object; spread after the collection's options, it wins + // over a `migrate.conventions` preset name in .metaobjects/config.json. + ...(cfg?.schemaConventions !== undefined ? { schemaConventions: cfg.schemaConventions } : {}), }; } diff --git a/server/typescript/packages/cli/test/migrate-schema-conventions.test.ts b/server/typescript/packages/cli/test/migrate-schema-conventions.test.ts new file mode 100644 index 0000000000..2fc52edb75 --- /dev/null +++ b/server/typescript/packages/cli/test/migrate-schema-conventions.test.ts @@ -0,0 +1,84 @@ +/** + * `migrate.conventions` reaches `meta migrate` through the project-aware load: an `efcore` + * project gets EF Core's database-only names (here, the index EF puts on every foreign + * key), and a preset name the tool does not know is refused by name, as a config error. + */ +import { describe, test, expect, afterAll, beforeEach, afterEach, spyOn } from "bun:test"; +import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { migrateCommand } from "../src/commands/migrate.js"; +import { log } from "../src/lib/log.js"; + +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +const MODEL = JSON.stringify({ + "metadata.root": { + package: "acme::platform", + children: [ + { "object.entity": { name: "Order", children: [ + { "source.rdb": { name: "src", "@table": "Orders" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ] } }, + { "object.entity": { name: "OrderLine", children: [ + { "source.rdb": { name: "src", "@table": "OrderLines" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.long": { name: "orderId", "@column": "OrderId" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "identity.reference": { name: "order", "@fields": ["orderId"], "@references": "Order" } }, + ] } }, + ], + }, +}); + +async function project(conventions: string | undefined): Promise { + const root = await mkdtemp(join(tmpdir(), "schema-conventions-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.platform.json"), MODEL, "utf8"); + await mkdir(join(root, ".metaobjects", "migrations"), { recursive: true }); + const migrate = conventions === undefined ? { dialect: "sqlite" } : { dialect: "sqlite", conventions }; + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, migrate }), "utf8"); + return root; +} + +let out: string[] = []; +let infoSpy: ReturnType; +let errSpy: ReturnType; +beforeEach(() => { + out = []; + infoSpy = spyOn(log, "info").mockImplementation((m: string) => { out.push(String(m)); }); + errSpy = spyOn(log, "error").mockImplementation((m: string) => { out.push(String(m)); }); +}); +afterEach(() => { infoSpy.mockRestore(); errSpy.mockRestore(); }); + +const dryRun = (root: string) => + migrateCommand(["--from-db", "--db", `file:${join(root, "t.db")}`, "--dialect", "sqlite", "--dry-run"], root); + +describe("meta migrate with migrate.conventions", () => { + test("efcore: the foreign key gets EF Core's IX_ index", async () => { + const root = await project("efcore"); + + expect(await dryRun(root)).toBe(0); + expect(out.join("\n")).toContain('CREATE INDEX "IX_OrderLines_OrderId" ON "OrderLines" ("OrderId");'); + }); + + test("no conventions set: no FK index, as before", async () => { + const root = await project(undefined); + + expect(await dryRun(root)).toBe(0); + expect(out.join("\n")).not.toContain("IX_OrderLines_OrderId"); + }); + + test("an unknown preset is refused by name, not as an unexpected error", async () => { + const root = await project("hibernate"); + + const code = await dryRun(root); + const text = out.join("\n"); + expect(code).toBe(2); + expect(text).toContain('migrate.conventions "hibernate" is not a schema-conventions preset: expected one of default, efcore'); + expect(text).not.toContain("unexpected error"); + }); +}); diff --git a/server/typescript/packages/codegen-ts/src/metaobjects-config.ts b/server/typescript/packages/codegen-ts/src/metaobjects-config.ts index 6fdd32a6ba..2e9394404a 100644 --- a/server/typescript/packages/codegen-ts/src/metaobjects-config.ts +++ b/server/typescript/packages/codegen-ts/src/metaobjects-config.ts @@ -1,3 +1,4 @@ +import type { SchemaConventions } from "@metaobjectsdev/migrate-ts"; import { physicalNamingRemovedMessage, type MetaDataTypeProvider } from "@metaobjectsdev/metadata"; import { physicalNamingGuideUrl } from "@metaobjectsdev/metadata/release-docs"; import type { RoutesExpose } from "./routes-expose.js"; @@ -181,6 +182,13 @@ export interface MetaobjectsGenConfig extends Omit diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index 801eb47507..dd8b4b685d 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -316,6 +316,19 @@ export function isDuplicateSqlNameError(err: unknown): err is DuplicateSqlNameEr return err instanceof Error && err.name === "DuplicateSqlNameError"; } +/** `migrate.conventions` names a schema-conventions preset that does not exist. */ +export class UnknownSchemaConventionsError extends Error { + override readonly name = "UnknownSchemaConventionsError"; + constructor(readonly selected: string, readonly presets: readonly string[]) { + super(`migrate.conventions "${selected}" is not a schema-conventions preset: expected one of ${presets.join(", ")}`); + } +} + +/** Is `err` the {@link UnknownSchemaConventionsError}? */ +export function isUnknownSchemaConventionsError(err: unknown): err is UnknownSchemaConventionsError { + return err instanceof Error && err.name === "UnknownSchemaConventionsError"; +} + /** Is `err` the {@link FkTargetNotUniqueError} from FKs whose targets are not unique keys? */ export function isFkTargetNotUniqueError(err: unknown): err is FkTargetNotUniqueError { return err instanceof Error && err.name === "FkTargetNotUniqueError"; diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 4d36683426..6e542992b7 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,5 +1,5 @@ import { DuplicateSqlNameError, FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; -import { defaultConventions, type SchemaConventions } from "./schema-conventions.js"; +import { resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, } from "@metaobjectsdev/metadata"; @@ -264,7 +264,10 @@ export function buildExpectedSchemaWithProvenance( // Pass 2: build full descriptors with FK resolution. Every FK whose target is not a // unique key is collected here and refused once, after every table is built. const fkTargetViolations: FkTargetViolation[] = []; - const conventions = opts?.conventions ?? defaultConventions; + // The caller's conventions, else the ones the project-aware load put on the root + // (`migrate.conventions`), else migrate's default. + const conventions = opts?.conventions + ?? resolveSchemaConventions((root.root() as { schemaConventions?: string | SchemaConventions }).schemaConventions); const fkCtx: ForeignKeyBuildContext = { conventions, violations: fkTargetViolations }; // Schema is resolved here (not stored in Pass 1) to avoid exactOptionalPropertyTypes // issues with `string | undefined` vs `schema?: string`. diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 8329065195..55b47b7435 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -62,6 +62,8 @@ export { allowOptionFor, isBlockedChangesError, isPrimaryKeyChangeError, isDeclaredRenameError, isDuplicateSqlNameError, isFkTargetNotUniqueError, + isUnknownSchemaConventionsError, + UnknownSchemaConventionsError, FkTargetNotUniqueError, } from "./errors.js"; export type { SqlNameCollision } from "./errors.js"; diff --git a/server/typescript/packages/migrate-ts/src/schema-conventions.ts b/server/typescript/packages/migrate-ts/src/schema-conventions.ts index 6b31d78b87..151210fc83 100644 --- a/server/typescript/packages/migrate-ts/src/schema-conventions.ts +++ b/server/typescript/packages/migrate-ts/src/schema-conventions.ts @@ -17,6 +17,8 @@ * Core migrations. */ +import { UnknownSchemaConventionsError } from "./errors.js"; + /** A key on one table: the table's database name and the key's columns, in key order. */ export interface KeyContext { table: string; @@ -95,8 +97,6 @@ export function resolveSchemaConventions(selected: string | SchemaConventions | if (selected === undefined) return defaultConventions; if (typeof selected !== "string") return selected; const preset = PRESETS[selected]; - if (preset === undefined) { - throw new Error(`unknown schema conventions "${selected}": expected one of ${SCHEMA_CONVENTION_PRESETS.join(", ")}`); - } + if (preset === undefined) throw new UnknownSchemaConventionsError(selected, SCHEMA_CONVENTION_PRESETS); return preset; } diff --git a/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts index 3f4efb5ec8..e57bb29b94 100644 --- a/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts @@ -8,6 +8,7 @@ import { describe, test, expect } from "bun:test"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildExpectedSchema } from "../../src/expected-schema.js"; import { efcoreConventions } from "../../src/schema-conventions.js"; +import { UnknownSchemaConventionsError } from "../../src/errors.js"; import { emit } from "../../src/emit/index.js"; import { diff } from "../../src/diff/index.js"; @@ -109,3 +110,22 @@ describe("buildExpectedSchema with the default conventions", () => { expect(table(s, "Regions").indexes.every((i) => i.constraint === undefined)).toBe(true); }); }); + +describe("the conventions the project-aware load put on the root", () => { + test("are used when the caller passes none", async () => { + const root = await load(); + (root as { schemaConventions?: unknown }).schemaConventions = "efcore"; + + expect(table(buildExpectedSchema(root), "Orders").primaryKeyName).toBe("PK_Orders"); + // `conventions: undefined` is "not given", so it does not mask the root + expect(table(buildExpectedSchema(root, { conventions: undefined }), "Orders").primaryKeyName).toBe("PK_Orders"); + }); + + test("an unknown preset name is refused, naming the ones that exist", async () => { + const root = await load(); + (root as { schemaConventions?: unknown }).schemaConventions = "hibernate"; + + expect(() => buildExpectedSchema(root)).toThrow(UnknownSchemaConventionsError); + expect(() => buildExpectedSchema(root)).toThrow(/migrate\.conventions "hibernate".*default, efcore/); + }); +}); diff --git a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts index 2e0568b48c..06eb9a1aa4 100644 --- a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts @@ -67,7 +67,7 @@ describe("resolveSchemaConventions", () => { }); test("an unknown preset is refused, naming the ones that exist", () => { - expect(() => resolveSchemaConventions("hibernate")).toThrow(/unknown schema conventions "hibernate".*default, efcore/); + expect(() => resolveSchemaConventions("hibernate")).toThrow(/migrate\.conventions "hibernate".*default, efcore/); expect(SCHEMA_CONVENTION_PRESETS).toEqual(["default", "efcore"]); }); }); diff --git a/server/typescript/packages/sdk/src/collection.ts b/server/typescript/packages/sdk/src/collection.ts index b0f10e0ce0..50d118374a 100644 --- a/server/typescript/packages/sdk/src/collection.ts +++ b/server/typescript/packages/sdk/src/collection.ts @@ -85,6 +85,8 @@ export interface Collection { readonly physicalNaming: PhysicalNaming; /** The `wire` block of the project config (ADR-0019 Amendment 2), default when absent. */ readonly wireFormat: WireFormat; + /** `migrate.conventions` of the project config — a schema-conventions preset name — when set. */ + readonly schemaConventions: string | undefined; /** FR-023 — the `FileSource` id each file loads under, for the dependency * ARTIFACTS only (`dep:/`); own files are absent and keep the * default `basename(path)`. Threaded to `loadMemory` so every node an artifact @@ -272,6 +274,7 @@ export async function resolveCollection( let libraries: readonly string[] = []; let physicalNaming: PhysicalNaming = DEFAULT_PHYSICAL_NAMING; let wireFormat: WireFormat = DEFAULT_WIRE_FORMAT; + let schemaConventions: string | undefined; if (hasConfig) { // No try/catch here: a config.json that EXISTS but fails to load @@ -288,6 +291,7 @@ export async function resolveCollection( libraries = cfg.libraries; physicalNaming = physicalNamingFromConfig(cfg); wireFormat = wireFormatFromConfig(cfg); + schemaConventions = cfg.migrate?.conventions; // An unknown token is a hard config error naming the valid ones, while // `librarySources` keeps skipping one silently for a programmatic caller. The two // are deliberately different: an API caller asking for a library this version does @@ -402,6 +406,7 @@ export async function resolveCollection( libraries, physicalNaming, wireFormat, + schemaConventions, fileIds: new Map(dependencies.map((d) => [d.artifactPath, d.sourceId])), importedPackages: [...importedPackages].sort(), importedNodes, diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts index c33e5397be..9d921302f7 100644 --- a/server/typescript/packages/sdk/src/config.ts +++ b/server/typescript/packages/sdk/src/config.ts @@ -80,6 +80,10 @@ const MigrateBlock = z.object({ * Include-only — there's no `migrate.scope.exclude`, since a migration run * is scoped to what it's touching, not filtered down from "everything". */ scope: z.array(z.string().min(1)), + /** Schema conventions for the database objects no code addresses: a preset name + * (`default`, `efcore`); meta migrate refuses a name it does not know. A project's own + * conventions object is supplied from metaobjects.config.ts instead. */ + conventions: z.string().min(1), // .strict() for the same reason as the top level and the source arms below, and // with sharper teeth here: `{ migrate: { scopee: [...], dialect: "postgres" } }` // used to parse to `{ dialect: "postgres" }`, so a typo'd `scope` key meant diff --git a/server/typescript/packages/sdk/src/memory.ts b/server/typescript/packages/sdk/src/memory.ts index 8facb118ed..d7332d650a 100644 --- a/server/typescript/packages/sdk/src/memory.ts +++ b/server/typescript/packages/sdk/src/memory.ts @@ -114,6 +114,12 @@ export interface LoadMemoryOptions { physicalNaming?: PhysicalNaming; /** The project wire format; defaults to the collection's (`resolveCollection(...).wireFormat`) when `files` is not passed. */ wireFormat?: WireFormat; + /** + * The schema conventions `meta migrate` names database-only objects with, set on the loaded + * root: a preset name, or a conventions object the project supplies. Defaults to the + * collection's `migrate.conventions` when `files` is not passed. + */ + schemaConventions?: unknown; } /** Default provider bundle threaded by {@link loadMemory} when no options @@ -169,7 +175,7 @@ export async function loadMemory( repoRoot: string, options?: LoadMemoryOptions, ): Promise { - const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat } = + const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, schemaConventions } = await loadCollectionRaw(repoRoot, options, options?.strict === true); if (result.errors.length > 0) { @@ -190,6 +196,7 @@ export async function loadMemory( if (physicalNaming !== undefined) result.root.physicalNaming = physicalNaming; if (wireFormat !== undefined) result.root.wireFormat = wireFormat; + if (schemaConventions !== undefined) result.root.schemaConventions = schemaConventions; return result.root; } @@ -264,6 +271,7 @@ async function loadCollectionRaw( libraries: readonly string[] | undefined; physicalNaming: PhysicalNaming | undefined; wireFormat: WireFormat | undefined; + schemaConventions: unknown; }> { const extra = options?.providers ?? []; let providers: readonly MetaDataTypeProvider[]; @@ -292,6 +300,7 @@ async function loadCollectionRaw( let libraries: readonly string[] | undefined = options?.libraries; let physicalNaming: PhysicalNaming | undefined = options?.physicalNaming; let wireFormat: WireFormat | undefined = options?.wireFormat; + let schemaConventions: unknown = options?.schemaConventions; if (options?.files !== undefined) { paths = [...options.files]; fileIds = options.fileIds; @@ -312,6 +321,7 @@ async function loadCollectionRaw( libraries ??= collection.libraries; physicalNaming ??= collection.physicalNaming; wireFormat ??= collection.wireFormat; + schemaConventions ??= collection.schemaConventions; } const loader = new MetaDataLoader({ @@ -337,7 +347,7 @@ async function loadCollectionRaw( return id === undefined ? new FileSource(p) : new FileSource(p, { id }); }), ]); - return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat }; + return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, schemaConventions }; } /** Every source file that contributed to a node, across the envelope variants that diff --git a/server/typescript/packages/sdk/test/schema-conventions-config.test.ts b/server/typescript/packages/sdk/test/schema-conventions-config.test.ts new file mode 100644 index 0000000000..59cbda7a7b --- /dev/null +++ b/server/typescript/packages/sdk/test/schema-conventions-config.test.ts @@ -0,0 +1,56 @@ +// `migrate.conventions` in .metaobjects/config.json: the schema conventions meta migrate +// names database-only objects with. The project-aware load carries the selection on the root, +// as it does `naming` and `wire`, so every expected-schema build of one loaded model — migrate, +// verify --db, the advisories — uses the same conventions. A project's own conventions object +// (from metaobjects.config.ts) arrives as a load option and wins over the preset name. + +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ConfigSchema } from "../src/config.js"; +import { loadMemory } from "../src/memory.js"; + +const MODEL = { "metadata.root": { package: "w", children: [ + { "object.entity": { name: "Thing", children: [{ "field.string": { name: "id" } }] } }, +] } }; + +async function withProject(config: Record, fn: (dir: string) => Promise): Promise { + const dir = mkdtempSync(join(tmpdir(), "mo-conventions-")); + try { + mkdirSync(join(dir, ".metaobjects")); + mkdirSync(join(dir, "metaobjects")); + writeFileSync(join(dir, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, ...config })); + writeFileSync(join(dir, "metaobjects", "meta.w.json"), JSON.stringify(MODEL)); + return await fn(dir); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +describe("migrate.conventions", () => { + test("is a string in the config schema", () => { + expect(ConfigSchema.safeParse({ schema_version: 1, migrate: { conventions: "efcore" } }).success).toBe(true); + expect(ConfigSchema.safeParse({ schema_version: 1, migrate: { conventions: 3 } }).success).toBe(false); + expect(ConfigSchema.safeParse({ schema_version: 1, migrate: { conventions: "" } }).success).toBe(false); + }); + + test("the project-aware load carries it on the root", async () => { + await withProject({ migrate: { conventions: "efcore" } }, async (dir) => { + expect((await loadMemory(dir)).schemaConventions).toBe("efcore"); + }); + }); + + test("absent, the root carries nothing (migrate's own default applies)", async () => { + await withProject({}, async (dir) => { + expect((await loadMemory(dir)).schemaConventions).toBeUndefined(); + }); + }); + + test("a conventions object passed to the load wins over the preset name", async () => { + const own = { id: "acme" }; + await withProject({ migrate: { conventions: "efcore" } }, async (dir) => { + expect((await loadMemory(dir, { schemaConventions: own })).schemaConventions).toBe(own); + }); + }); +}); From 051afafb59c68f9c2fbf872a0c71599f5fa00923 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 10:17:20 -0500 Subject: [PATCH 007/267] fix(migrate): introspect a primary key's name when it is not
_pkey meta migrate reads its expected side back from the shadow database, and introspection did not read the PK constraint's name, so a PK the schema conventions named (PK_
under efcore) came back nameless and the emitted DDL fell back to
_pkey. Read the name with the columns and record it when it differs from Postgres's default, as the expected side does, so a database built without conventions reads back unchanged. Co-Authored-By: Claude Opus 5.5 --- .../migrate-ts/src/introspect/postgres.ts | 13 +++++++----- .../postgres-composite-fk-introspect.test.ts | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index 080bef85a9..a2c174c297 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -50,7 +50,7 @@ export async function introspectPostgres(db: Kysely>): P for (const { schema, name } of tableRefs) { const columns = await readColumns(k, schema, name); - const primaryKey = await readPrimaryKey(k, schema, name); + const { columns: primaryKey, name: primaryKeyName } = await readPrimaryKey(k, schema, name); const description = await readPgCatalogColumnFacts(k, schema, name, columns); tables.push({ name, @@ -60,6 +60,9 @@ export async function introspectPostgres(db: Kysely>): P foreignKeys: await readPgForeignKeys(k, schema, name), checks: await readPgChecks(k, schema, name), primaryKey, + // Only a name other than Postgres's default `
_pkey`, as the expected side + // records it — a database built without schema conventions reads back unchanged. + ...(primaryKeyName !== undefined && primaryKeyName !== `${name}_pkey` ? { primaryKeyName } : {}), ...(description !== undefined ? { description } : {}), }); } @@ -534,11 +537,11 @@ async function readPgCatalogColumnFacts( type RawKysely = Kysely; // eslint-disable-next-line @typescript-eslint/no-explicit-any -async function readPrimaryKey(k: Kysely, schema: string, tableName: string): Promise { +async function readPrimaryKey(k: Kysely, schema: string, tableName: string): Promise<{ columns: string[]; name: string | undefined }> { // Uses information_schema only — avoids pg_attribute / pg_constraint joins // that are either missing or return empty in pg-mem. - const rows = await sql<{ column_name: string; ordinal_position: number }>` - SELECT kcu.column_name, kcu.ordinal_position + const rows = await sql<{ column_name: string; ordinal_position: number; constraint_name: string }>` + SELECT kcu.column_name, kcu.ordinal_position, tc.constraint_name FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name @@ -549,7 +552,7 @@ async function readPrimaryKey(k: Kysely, schema: string, tableName: string) AND tc.table_name = ${tableName} ORDER BY kcu.ordinal_position `.execute(k); - return rows.rows.map((r) => r.column_name); + return { columns: rows.rows.map((r) => r.column_name), name: rows.rows[0]?.constraint_name }; } async function readPgIndexes(k: RawKysely, schema: string, table: string): Promise { diff --git a/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts b/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts index 200716534f..bfd50c20a7 100644 --- a/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts @@ -43,4 +43,24 @@ d("postgres composite FK introspection (real PG)", () => { await k.destroy(); } }); + + test("reads a primary key's constraint name when it is not
_pkey", async () => { + const k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: PG_URL }) }) }); + const named = "pkn_" + Math.random().toString(36).slice(2, 8); + const plain = "pkp_" + Math.random().toString(36).slice(2, 8); + try { + await sql.raw(`CREATE TABLE ${named} ( id INTEGER, CONSTRAINT "PK_${named}" PRIMARY KEY (id) )`).execute(k); + await sql.raw(`CREATE TABLE ${plain} ( id INTEGER PRIMARY KEY )`).execute(k); + + const snap = await introspectPostgres(k); + + expect(snap.tables.find((x) => x.name === named)!.primaryKeyName).toBe(`PK_${named}`); + // the default name is left absent, so a snapshot without conventions is unchanged + expect(snap.tables.find((x) => x.name === plain)!.primaryKeyName).toBeUndefined(); + } finally { + await sql.raw(`DROP TABLE IF EXISTS ${named}`).execute(k); + await sql.raw(`DROP TABLE IF EXISTS ${plain}`).execute(k); + await k.destroy(); + } + }); }); From 669d6fd50dda6233bd82d3422b6a4b8118491acf Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 10:45:31 -0500 Subject: [PATCH 008/267] fix(migrate): check FK targets against built tables; rename name-only changes Review fixes for the FK-target guard and the conventions switch. - The guard now runs after every table is built, against the target table's real keys (PK, unique indexes with no predicate or expression, as column sets). A key declared on a TPH subtype is not emitted, so it no longer passes (the message points at the base); a bare reference into a composite PK with one FK field is caught; a target the model does not build (@unmanaged) is skipped, as before the guard existed. - buildExpectedSchemaWithProvenance returns the violations instead of throwing; scopeExpectedSchema refuses the ones on governed tables and returns the rest, which meta migrate warns about. buildExpectedSchema still refuses them all. - Postgres: a drop plus an add of the same definition under another name, on a table that is not renamed, folds into a new rename-constraints change (RENAME CONSTRAINT / ALTER INDEX RENAME), so switching conventions no longer drops and rebuilds every FK. The #285 regression now redefines the key (partial) so it still drops; a new real-engine test pins the rename. - meta verify reports both new errors as refusals (exit 1 / exit 2), and refuses an unknown migrate.conventions preset on every run, not only --db. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 ++- .../packages/cli/src/commands/migrate.ts | 14 +++ .../packages/cli/src/commands/verify.ts | 26 ++++ .../typescript/packages/cli/src/lib/allow.ts | 2 + .../test/migrate-fk-target-not-unique.test.ts | 18 ++- .../cli/test/verify-schema-refusals.test.ts | 81 +++++++++++++ .../packages/migrate-ts/src/diff/index.ts | 38 +++++- .../packages/migrate-ts/src/diff/status.ts | 1 + .../packages/migrate-ts/src/emit/postgres.ts | 18 +++ .../packages/migrate-ts/src/emit/sqlite.ts | 6 + .../packages/migrate-ts/src/errors.ts | 17 ++- .../migrate-ts/src/expected-schema.ts | 111 ++++++++++++------ .../packages/migrate-ts/src/index.ts | 1 + .../packages/migrate-ts/src/scope.ts | 26 +++- .../packages/migrate-ts/src/types.ts | 13 ++ .../pg-constraint-backed-index-285.test.ts | 51 ++++++-- .../test/unit/diff-rename-constraints.test.ts | 89 ++++++++++++++ .../test/unit/fk-target-unique.test.ts | 70 +++++++++++ 18 files changed, 535 insertions(+), 63 deletions(-) create mode 100644 server/typescript/packages/cli/test/verify-schema-refusals.test.ts create mode 100644 server/typescript/packages/migrate-ts/test/unit/diff-rename-constraints.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index cb7350f8ad..013c6b93da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,9 +49,19 @@ here.** `@unique` field used to emit an FK the database refuses at apply time ("there is no unique constraint matching given keys"), after earlier statements had already run. `meta migrate` and `meta verify --db` now fail first with `FkTargetNotUniqueError`, which lists every offending - reference at once (entity, reference, target and fields), and `meta migrate` reports it as a - metadata refusal with a hint rather than an unexpected error. Fix: declare an - `identity.secondary` on those fields of the target. + reference at once (entity, reference, target and fields); both report it as a metadata refusal + with a hint. The check is against the table the model actually builds: a key declared on a TPH + subtype is not emitted, so it does not count (the message says to declare it on the base), and + a bare reference into a composite primary key with fewer FK fields is caught too. An FK on a + table this run does not govern (imported, or outside `migrate.scope`) is warned about, not + refused, and an FK into a table the model does not build (`@unmanaged`) is not checked. Fix: + declare an `identity.secondary` on those fields of the target. +- **A constraint or index whose only change is its name is renamed in place on Postgres.** A + drop plus an add of the same definition under another name, on a table that is not itself + renamed (switching schema conventions renames every FK), used to be a gated `drop-fk` / + `drop-index` that dropped and rebuilt the object. It is now one `rename-constraints` change: + `ALTER TABLE … RENAME CONSTRAINT` / `ALTER INDEX … RENAME`, and the down renames it back. SQLite + cannot rename a constraint and keeps the rebuild. - **A prompt or output template that names a variable not on its payload now raises at render time.** Behaviour change: a generated render helper used to render `Hi {{nmae}}` as `Hi ` with no error when the payload declares `name`; it now raises `ERR_VAR_NOT_ON_PAYLOAD (nmae)` (`RenderError` in diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index f85c9b62cc..7f875c97bc 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -22,6 +22,8 @@ import { isDeclaredRenameError, isDuplicateSqlNameError, isFkTargetNotUniqueError, + FkTargetNotUniqueError, + type FkTargetViolation, isUnknownSchemaConventionsError, buildExpectedSchemaWithProvenance, scopeExpectedSchema, @@ -359,6 +361,16 @@ function mapOnAmbiguous(v: "abort" | "rename" | "drop-add"): AmbiguousResolution * for scope. The engine's guards (`isPrimaryKeyChangeError` et al.) narrow at the catch * site; only the hint varies by refusal, so each hint is written once. */ +/** + * FKs whose target is not a unique key, on tables this run does not govern (imported, or + * outside migrate.scope). This project never emits them, so they are reported, not refused. + */ +function warnUngovernedFkTargets(violations: readonly FkTargetViolation[] | undefined): void { + if (violations === undefined || violations.length === 0) return; + log.warn(`migrate: ${new FkTargetNotUniqueError([...violations]).message}`); + log.warn(`migrate: the table(s) holding ${violations.length === 1 ? "that foreign key are" : "those foreign keys are"} not governed by this run (imported, or outside migrate.scope), so nothing is refused.`); +} + function refuseEngineError(err: Error, hint: string, fmt: OutputFormat): number { log.error(`migrate: ${err.message}`); emitStructuredError(`migrate: ${err.message}`, hint, fmt); @@ -822,6 +834,7 @@ export async function migrateCommand( const scoped = scopeExpectedSchema(built, collection.inMigrateScope, importedOption(collection)); const expected = scoped.snapshot; logOutOfScope(scoped.outOfScope, scoped.importedOutOfScope ?? [], fmt); + warnUngovernedFkTargets(scoped.ungovernedFkTargetViolations); let actual; try { actual = await introspect(kysely.db, kysely.dialect); @@ -1815,6 +1828,7 @@ async function runD1Migrate( const scoped = scopeExpectedSchema(built, collection.inMigrateScope, importedOption(collection)); const expected = scoped.snapshot; logOutOfScope(scoped.outOfScope, scoped.importedOutOfScope ?? [], fmt); + warnUngovernedFkTargets(scoped.ungovernedFkTargetViolations); let actual; try { actual = await introspectD1({ diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 991aebeaea..c3c6c3058a 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -91,6 +91,10 @@ import { postgresExprCanonProbe, type ShadowSchemaSource, withoutFlywayHistory, + isFkTargetNotUniqueError, + isUnknownSchemaConventionsError, + resolveSchemaConventions, + type SchemaConventions, } from "@metaobjectsdev/migrate-ts"; import { DEFAULT_METAOBJECTS_DIR, @@ -390,6 +394,17 @@ export async function verifyCommand( return 1; } + // A `migrate.conventions` preset this version does not ship is a config error on every + // verify run, not only one that builds the expected schema (a typo'd preset otherwise + // passes `meta verify` and changes nothing until `meta migrate`). + try { + resolveSchemaConventions((root as { schemaConventions?: string | SchemaConventions }).schemaConventions); + } catch (err) { + if (!isUnknownSchemaConventionsError(err)) throw err; + log.error(`verify: ${err.message}`); + return 2; + } + // The schema gate governs exactly the objects `meta migrate` governs — ONE // declaration (`migrate.scope`), not a second key: a drift gate that fails on // tables migrate deliberately does not own is incoherent. Undefined ⇒ everything @@ -1387,6 +1402,16 @@ export async function verifyCommand( ...importedOption(collection), }); } catch (err) { + // Metadata refusals raised while building the expected side, not introspection failures. + if (isFkTargetNotUniqueError(err)) { + log.error(`verify: ${err.message}`); + log.error("verify: declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"); + return 1; + } + if (isUnknownSchemaConventionsError(err)) { + log.error(`verify: ${err.message}`); + return 2; + } schemaRunError = `failed to introspect ${kysely.displayUrl}: ${describeError(err)}`; log.error(`verify: ${schemaRunError}`); return 1; @@ -1874,6 +1899,7 @@ const DRIFT_PRESENTATION: Record `${r.from} → ${r.to}`).join(", ")}`; case "add-column": return `${c.table}.${c.column.name}`; case "drop-column": return `${c.table}.${c.column}`; case "rename-column": return `${c.table}.${c.from} → ${c.table}.${c.to}`; diff --git a/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts b/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts index f2bd3ba448..2dd4285c00 100644 --- a/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts +++ b/server/typescript/packages/cli/test/migrate-fk-target-not-unique.test.ts @@ -44,25 +44,27 @@ const MODEL = JSON.stringify({ }, }); -async function project(): Promise { +async function project(migrate: Record = { dialect: "sqlite" }): Promise { const root = await mkdtemp(join(tmpdir(), "fk-target-unique-")); dirs.push(root); await mkdir(join(root, "metaobjects"), { recursive: true }); await writeFile(join(root, "metaobjects", "meta.platform.json"), MODEL, "utf8"); await mkdir(join(root, ".metaobjects", "migrations"), { recursive: true }); - await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, migrate: { dialect: "sqlite" } }), "utf8"); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, migrate }), "utf8"); return root; } let out: string[] = []; let infoSpy: ReturnType; let errSpy: ReturnType; +let warnSpy: ReturnType; beforeEach(() => { out = []; infoSpy = spyOn(log, "info").mockImplementation((m: string) => { out.push(String(m)); }); errSpy = spyOn(log, "error").mockImplementation((m: string) => { out.push(String(m)); }); + warnSpy = spyOn(log, "warn").mockImplementation((m: string) => { out.push(String(m)); }); }); -afterEach(() => { infoSpy.mockRestore(); errSpy.mockRestore(); }); +afterEach(() => { infoSpy.mockRestore(); errSpy.mockRestore(); warnSpy.mockRestore(); }); describe("meta migrate refuses an FK to a non-unique target", () => { test("exits 1 with the reference named and the fix, not as an unexpected error", async () => { @@ -76,4 +78,14 @@ describe("meta migrate refuses an FK to a non-unique target", () => { expect(text).not.toContain("unexpected error"); expect(text).not.toContain("CREATE TABLE"); }); + + test("a holder outside migrate.scope is not this run's to fix: warned, and the run goes on", async () => { + const root = await project({ dialect: "sqlite", scope: ["acme::platform::Person"] }); + const code = await migrateCommand(["--from-db", "--db", `file:${join(root, "t.db")}`, "--dialect", "sqlite", "--dry-run"], root); + + const text = out.join("\n"); + expect(code).toBe(0); + expect(text).toContain('reference "ref_person" targets [code] on "Person"'); + expect(text).toContain("not governed by this run"); + }); }); diff --git a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts new file mode 100644 index 0000000000..73ffa397cb --- /dev/null +++ b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts @@ -0,0 +1,81 @@ +/** + * `meta verify` reports the two metadata/config refusals the expected-schema build can raise + * as what they are, the way `meta migrate` does: an FK whose target is not a unique key + * (exit 1, the reference named), and an unknown `migrate.conventions` preset (exit 2, the + * presets named). Neither is "failed to introspect", and a typo'd preset is refused even + * on a run with no --db. + */ +import { describe, test, expect, afterAll } from "bun:test"; +import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { verifyCommand } from "../src/commands/verify.js"; + +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +function model(references: string): string { + return JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Person", children: [ + { "source.rdb": { "@table": "people" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ] } }, + { "object.entity": { name: "Visit", children: [ + { "source.rdb": { "@table": "visits" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "personCode" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "identity.reference": { name: "ref_person", "@fields": ["personCode"], "@references": references } }, + ] } }, + ] } }); +} + +async function project(references: string, migrate: Record = {}): Promise { + const root = await mkdtemp(join(tmpdir(), "verify-schema-refusals-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), model(references), "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, migrate }), "utf8"); + return root; +} + +async function capture(fn: () => Promise): Promise<{ code: number; out: string }> { + const lines: string[] = []; + const log = console.log; + const err = console.error; + console.log = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + console.error = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + try { + const code = await fn(); + return { code, out: lines.join("\n") }; + } finally { + console.log = log; + console.error = err; + } +} + +describe("meta verify — schema refusals", () => { + test("--db: an FK to a non-unique target is refused by name, not as an introspection failure", async () => { + const root = await project("Person.code"); + const { code, out } = await capture(() => verifyCommand(["--db", `file:${join(root, "t.db")}`], root)); + + expect(code).toBe(1); + expect(out).toContain('reference "ref_person" targets [code] on "Person"'); + expect(out).not.toContain("failed to introspect"); + }); + + test("an unknown migrate.conventions preset is refused with exit 2, with or without --db", async () => { + const root = await project("Person", { conventions: "hibernate" }); + + const plain = await capture(() => verifyCommand([], root)); + expect(plain.code).toBe(2); + expect(plain.out).toContain('migrate.conventions "hibernate" is not a schema-conventions preset'); + + const withDb = await capture(() => verifyCommand(["--db", `file:${join(root, "t.db")}`], root)); + expect(withDb.code).toBe(2); + expect(withDb.out).not.toContain("failed to introspect"); + }); +}); diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index d73e4b0c30..d82dfe1f1e 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -285,7 +285,23 @@ export async function diff( const actualTable = actualTables.get(id); if (!actualTable) continue; // An FK onto a renamed table follows the rename in the engine — compare it as such. - diffTablePair(expectedTable, withRenamedRefTables(actualTable, renamed), changes, args.dialect, canon); + if (args.dialect !== "postgres") { + diffTablePair(expectedTable, withRenamedRefTables(actualTable, renamed), changes, args.dialect, canon); + continue; + } + // Postgres: a constraint or index whose only change is its name is renamed in place. + const tableChanges: Change[] = []; + diffTablePair(expectedTable, withRenamedRefTables(actualTable, renamed), tableChanges, args.dialect, canon); + const { constraintRenames, indexRenames, rest } = pairNameOnlyChanges(tableChanges, textColumnsOf(actualTable), canon); + if (constraintRenames.length > 0 || indexRenames.length > 0) { + changes.push({ + kind: "rename-constraints", table: expectedTable.name, ...schemaSpread(expectedTable.schema), + ...(constraintRenames.length > 0 ? { constraintRenames } : {}), + ...(indexRenames.length > 0 ? { indexRenames } : {}), + status: ALLOWED, + }); + } + changes.push(...rest); } // Pass 2b: views. Identity is (schema, name). How "changed" is decided is @@ -540,6 +556,21 @@ function foldNameOnlyChanges( textColumns: ReadonlySet, canon: ExprCanon, ): Change[] { + const { constraintRenames, indexRenames, rest } = pairNameOnlyChanges(tableChanges, textColumns, canon); + if (constraintRenames.length > 0) r.constraintRenames = constraintRenames; + if (indexRenames.length > 0) r.indexRenames = indexRenames; + return rest; +} + +/** + * Pair each drop of a constraint or index with an add of the SAME definition under another + * name. The pairs are name changes; `rest` is every other change, in order. + */ +function pairNameOnlyChanges( + tableChanges: Change[], + textColumns: ReadonlySet, + canon: ExprCanon, +): { constraintRenames: NameChange[]; indexRenames: NameChange[]; rest: Change[] } { const constraintRenames: NameChange[] = []; const indexRenames: NameChange[] = []; const folded = new Set(); @@ -567,10 +598,7 @@ function foldNameOnlyChanges( } } } - if (folded.size === 0) return tableChanges; - if (constraintRenames.length > 0) r.constraintRenames = constraintRenames; - if (indexRenames.length > 0) r.indexRenames = indexRenames; - return tableChanges.filter((c) => !folded.has(c)); + return { constraintRenames, indexRenames, rest: folded.size === 0 ? tableChanges : tableChanges.filter((c) => !folded.has(c)) }; } function idOfChange(c: Change): string | undefined { diff --git a/server/typescript/packages/migrate-ts/src/diff/status.ts b/server/typescript/packages/migrate-ts/src/diff/status.ts index 672bb42b17..41e19013b5 100644 --- a/server/typescript/packages/migrate-ts/src/diff/status.ts +++ b/server/typescript/packages/migrate-ts/src/diff/status.ts @@ -179,6 +179,7 @@ function blockFor( // Always-allowed kinds case "create-table": case "rename-table": + case "rename-constraints": case "add-column": case "rename-column": case "add-index": diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index f38f1d5b81..8f640cfa34 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -37,6 +37,8 @@ import { dataHazardOf } from "../hazards.js"; const STAGE_ORDER: Record = { "drop-view": 0, "rename-table": 0.5, + // After a table rename (its new name is the one this change addresses), before every drop/add. + "rename-constraints": 0.6, "drop-fk": 1, "drop-check": 1, "create-table": 1, "drop-index": 1.5, @@ -230,6 +232,7 @@ function renderUp(c: Change, recreated: ReadonlySet = new Set()): string // so a no-op down would still record the rollback as done. case "drop-table": return `DROP TABLE IF EXISTS ${quoteQualified(c.table, c.schema)};`; case "rename-table": return renderRenameTable(c, "up"); + case "rename-constraints": return renderRenameConstraints(c, "up"); case "add-column": { const base = `ALTER TABLE ${quoteQualified(c.table, c.schema)} ADD COLUMN ${renderColumn(c.column)};`; if (!c.column.description) return base; @@ -339,6 +342,20 @@ function renderRenameTable(c: Extract, dir: "u return (up ? lines : [...lines].reverse()).join("\n\n"); } +/** Constraints and indexes renamed in place on a table that keeps its name; the down renames them back. */ +function renderRenameConstraints(c: Extract, dir: "up" | "down"): string { + const up = dir === "up"; + const table = quoteQualified(c.table, c.schema); + const flip = (r: NameChange): NameChange => (up ? r : { from: r.to, to: r.from }); + const lines = [ + ...(c.constraintRenames ?? []).map(flip).map((r) => + `ALTER TABLE ${table} RENAME CONSTRAINT ${quote(r.from)} TO ${quote(r.to)};`), + ...(c.indexRenames ?? []).map(flip).map((r) => + `ALTER INDEX ${quoteIndexQualified(r.from, c.schema)} RENAME TO ${quote(r.to)};`), + ]; + return (up ? lines : [...lines].reverse()).join("\n\n"); +} + function renderDown(c: Change, recreated: ReadonlySet = new Set()): string { switch (c.kind) { case "create-table": return `DROP TABLE ${quoteQualified(c.table.name, c.table.schema)};`; @@ -360,6 +377,7 @@ function renderDown(c: Change, recreated: ReadonlySet = new Set()): stri return parts.join("\n"); } case "rename-table": return renderRenameTable(c, "down"); + case "rename-constraints": return renderRenameConstraints(c, "down"); case "add-column": return `ALTER TABLE ${quoteQualified(c.table, c.schema)} DROP COLUMN ${quote(c.column.name)};`; case "drop-column": return c.restore diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts index afeeb6811e..9290fa2681 100644 --- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts +++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts @@ -41,6 +41,7 @@ const STAGE_ORDER: Record = { // rename-table runs before every other table change (mirrors postgres): changes on a // renamed table — including its recreate-and-copy — are keyed by the NEW name. "rename-table": 0.5, + "rename-constraints": 0.6, "drop-fk": 1, "drop-check": 1, "create-table": 1, "drop-index": 1.5, @@ -151,6 +152,7 @@ export function changeTable(c: Change): string | undefined { case "create-table": return c.table.name; case "drop-table": return c.table; case "rename-table": return c.from; // applies to source table + case "rename-constraints": return c.table; case "add-column": case "drop-column": case "rename-column": @@ -390,6 +392,8 @@ function renderUpNative(c: Change): string { assertNoCarriedRenames(c); return `ALTER TABLE ${quote(c.from)} RENAME TO ${quote(c.to)};`; } + case "rename-constraints": + throw new Error("rename-constraints is postgres-only — the sqlite/d1 diff never produces it (sqlite cannot rename a constraint)"); case "add-column": return `ALTER TABLE ${quote(c.table)} ADD COLUMN ${renderColumnInline(c.column)};`; case "drop-column": return `ALTER TABLE ${quote(c.table)} DROP COLUMN ${quote(c.column)};`; case "rename-column": { @@ -438,6 +442,8 @@ function renderDownNative(c: Change): string { assertNoCarriedRenames(c); return `ALTER TABLE ${quote(c.to)} RENAME TO ${quote(c.from)};`; } + case "rename-constraints": + throw new Error("rename-constraints is postgres-only — the sqlite/d1 diff never produces it (sqlite cannot rename a constraint)"); case "add-column": return `ALTER TABLE ${quote(c.table)} DROP COLUMN ${quote(c.column.name)};`; case "drop-column": return `-- WARNING: down migration cannot restore data\n-- TODO: re-add dropped column "${c.column}" manually`; case "rename-column": { diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index dd8b4b685d..dae730384a 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -35,12 +35,16 @@ export class SetNullNotNullableError extends Error { } } -/** One identity.reference whose dotted @references names fields the target does not hold unique. */ +/** One identity.reference whose target fields are not a unique key on the table it references. */ export interface FkTargetViolation { + /** The holder's table, qualified (`.
`): what `scopeExpectedSchema` governs by. */ + table: string; entityName: string; referenceName: string; targetEntityName: string; targetFields: string[]; + /** Set when the target is a TPH subtype: the entity whose table it is stored in. */ + storedIn?: string; } /** @@ -57,9 +61,12 @@ export class FkTargetNotUniqueError extends Error { constructor(violations: FkTargetViolation[]) { const lines = violations.map((v) => { const fieldList = v.targetFields.join(", "); - return `Entity "${v.entityName}": reference "${v.referenceName}" targets [${fieldList}] on "${v.targetEntityName}", ` + - `which is not a unique key there (not its primary key, an identity.secondary without @where/@expr, or a @unique field). ` + - `Fix: declare an identity.secondary on "${v.targetEntityName}" with @fields [${fieldList}].`; + const head = `Entity "${v.entityName}": reference "${v.referenceName}" targets [${fieldList}] on "${v.targetEntityName}", ` + + `which is not a unique key of its table (its primary key, an identity.secondary without @where/@expr, or a @unique field). `; + return v.storedIn !== undefined + ? head + `"${v.targetEntityName}" is stored in the table of "${v.storedIn}", and a key declared on a TPH subtype is not emitted: ` + + `declare it on "${v.storedIn}" (an identity.secondary with @fields [${fieldList}]).` + : head + `Fix: declare an identity.secondary on "${v.targetEntityName}" with @fields [${fieldList}], or reference its whole primary key.`; }); const head = violations.length === 1 ? "A database refuses this foreign key." @@ -117,6 +124,8 @@ function changeLocator(c: Change): string { case "drop-table": case "rename-table": return c.kind === "drop-table" ? c.table : `${c.from}→${c.to}`; + case "rename-constraints": + return `${c.table}: ${[...(c.constraintRenames ?? []), ...(c.indexRenames ?? [])].map((r) => `${r.from}→${r.to}`).join(", ")}`; case "create-table": return c.table.name; case "add-index": diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 6e542992b7..34ced0a6f3 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -151,6 +151,13 @@ export type SchemaProvenance = ReadonlyMap; export interface ExpectedSchemaWithProvenance { snapshot: SchemaSnapshot; provenance: SchemaProvenance; + /** + * Foreign keys whose target columns are not a unique key of the table they reference. + * Not thrown here: `scopeExpectedSchema` refuses the ones on governed tables and returns + * the rest (an imported or out-of-scope holder is not this project's to fix), and + * {@link buildExpectedSchema} refuses them all. Absent when there are none. + */ + fkTargetViolations?: FkTargetViolation[]; } /** @@ -161,7 +168,10 @@ export function buildExpectedSchema( root: MetaData, opts?: BuildExpectedSchemaOptions, ): SchemaSnapshot { - return buildExpectedSchemaWithProvenance(root, opts).snapshot; + const built = buildExpectedSchemaWithProvenance(root, opts); + // No scope here: every FK whose target is not a unique key is refused. + if (built.fkTargetViolations !== undefined) throw new FkTargetNotUniqueError(built.fkTargetViolations); + return built.snapshot; } /** @@ -261,14 +271,12 @@ export function buildExpectedSchemaWithProvenance( // them — a TPH subtype, for one, shares its base's table and declares none of its own). const provenance = new Map(); - // Pass 2: build full descriptors with FK resolution. Every FK whose target is not a - // unique key is collected here and refused once, after every table is built. - const fkTargetViolations: FkTargetViolation[] = []; + // Pass 2: build full descriptors with FK resolution. // The caller's conventions, else the ones the project-aware load put on the root // (`migrate.conventions`), else migrate's default. const conventions = opts?.conventions ?? resolveSchemaConventions((root.root() as { schemaConventions?: string | SchemaConventions }).schemaConventions); - const fkCtx: ForeignKeyBuildContext = { conventions, violations: fkTargetViolations }; + const fkCtx: ForeignKeyBuildContext = { conventions, origins: new Map() }; // Schema is resolved here (not stored in Pass 1) to avoid exactOptionalPropertyTypes // issues with `string | undefined` vs `schema?: string`. const tables: TableDescriptor[] = entities.map(({ entity, tableName }) => { @@ -281,7 +289,9 @@ export function buildExpectedSchemaWithProvenance( return t; }); - if (fkTargetViolations.length > 0) throw new FkTargetNotUniqueError(fkTargetViolations); + // Checked against the BUILT tables, before the conventions add FK indexes: a key the model + // declares but never emits (on a TPH subtype) is no key a database can reference. + const fkTargetViolations = collectFkTargetViolations(tables, fkCtx.origins, provenance); applySchemaConventions(tables, conventions); // Pass 3: dialect-specific SqlType normalization. @@ -425,7 +435,7 @@ export function buildExpectedSchemaWithProvenance( })); if (collisions.length > 0) throw new DuplicateSqlNameError(collisions); - return { snapshot: { tables, views }, provenance }; + return { snapshot: { tables, views }, provenance, ...(fkTargetViolations.length > 0 ? { fkTargetViolations } : {}) }; } /** @@ -1042,14 +1052,6 @@ function buildForeignKeys( const targetFieldNames = explicitTargetFields.length > 1 ? explicitTargetFields : [refChild.resolvedTargetPkField(root) ?? "id"]; - // Guard: an explicit target must be a unique key on the target, or the database - // refuses the FK at apply time. The bare form targets the primary key by construction. - if (explicitTargetFields.length > 0 && !isUniqueKeyOf(targetObj, explicitTargetFields)) { - fkCtx.violations.push({ - entityName: holder.name, referenceName: refChild.name, targetEntityName: targetObj.name, targetFields: explicitTargetFields, - }); - continue; - } const refColumns = targetFieldNames.map((jsName) => { const targetField = findField(targetObj, jsName); return targetField @@ -1085,6 +1087,10 @@ function buildForeignKeys( // Two subtypes may declare the same FK column; it folds to ONE column, so ONE constraint. if (fks.some((existing) => existing.name === fk.name)) continue; fks.push(fk); + fkCtx.origins.set(fk, { + entityName: holder.name, referenceName: refChild.name, targetEntityName: targetObj.name, + targetKey: targetObj.resolutionKey(), targetFields: targetFieldNames, + }); } return fks; } @@ -1092,7 +1098,58 @@ function buildForeignKeys( /** What building a table's foreign keys needs beyond the table: the conventions, and where refusals go. */ interface ForeignKeyBuildContext { conventions: SchemaConventions; - violations: FkTargetViolation[]; + /** Where each built FK came from, for the target check that runs once every table is built. */ + origins: Map; +} + +interface FkOrigin { + entityName: string; + referenceName: string; + targetEntityName: string; + /** The target entity's resolution key, to tell a TPH subtype from the entity owning the table. */ + targetKey: string; + targetFields: string[]; +} + +/** + * Every built FK whose referenced columns are not a unique key of the BUILT target table: its + * primary key, or a unique index with no predicate or expression, as a column set (Postgres + * accepts any order). A target this model does not build — an @unmanaged table, another + * owner's — is skipped: its keys are not known here, and the database is the judge. + */ +function collectFkTargetViolations( + tables: TableDescriptor[], + origins: ReadonlyMap, + provenance: ReadonlyMap, +): FkTargetViolation[] { + const setOf = (columns: readonly string[]) => [...columns].sort().join(","); + const violations: FkTargetViolation[] = []; + for (const t of tables) { + for (const fk of t.foreignKeys) { + // The emitter assumes the referenced table lives in the holder's schema. + const target = tables.find((x) => x.name === fk.refTable && x.schema === t.schema); + if (target === undefined) continue; + const wanted = setOf(fk.refColumns); + const keys = [ + target.primaryKey, + ...target.indexes.filter((ix) => ix.unique && ix.where === undefined && ix.expr === undefined).map((ix) => ix.columns), + ]; + if (keys.some((k) => k.length > 0 && setOf(k) === wanted)) continue; + const origin = origins.get(fk); + if (origin === undefined) continue; + const owner = provenance.get(qualifiedDbName(target)); + const storedIn = owner !== undefined && owner !== origin.targetKey ? owner.split("::").pop() : undefined; + violations.push({ + table: qualifiedDbName(t), + entityName: origin.entityName, + referenceName: origin.referenceName, + targetEntityName: origin.targetEntityName, + targetFields: origin.targetFields, + ...(storedIn !== undefined ? { storedIn } : {}), + }); + } + } + return violations; } /** @@ -1135,28 +1192,6 @@ function applySchemaConventions(tables: TableDescriptor[], conventions: SchemaCo } } -/** - * True when `fieldNames` (in any order) are a key the target table holds unique: exactly its - * primary key, exactly a plain identity.secondary (a partial or expression index is not a key - * a foreign key may reference), or a single field declaring @unique. - */ -function isUniqueKeyOf(target: MetaObject, fieldNames: string[]): boolean { - const wanted = [...fieldNames].sort().join(","); - const same = (fields: string[]) => [...fields].sort().join(",") === wanted; - const primary = target.primaryIdentity(); - if (primary !== undefined && same(readIdentityFields(primary))) return true; - for (const secondary of target.secondaryIdentities()) { - // ADR-0039: resolving — @where / @expr may be inherited via extends. - if (secondary.attr(IDENTITY_ATTR_WHERE) !== undefined || secondary.attr(IDENTITY_ATTR_EXPR) !== undefined) continue; - if (same(readIdentityFields(secondary))) return true; - } - if (fieldNames.length === 1) { - const field = findField(target, fieldNames[0]!); - // ADR-0039: resolving — @unique may be inherited via extends. - if (field !== undefined && field.attr(FIELD_ATTR_UNIQUE) === true) return true; - } - return false; -} /** * Expand a `field.object @storage "flattened"` into one ColumnDescriptor per diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 55b47b7435..f46d86cb90 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -65,6 +65,7 @@ export { isUnknownSchemaConventionsError, UnknownSchemaConventionsError, FkTargetNotUniqueError, + type FkTargetViolation, } from "./errors.js"; export type { SqlNameCollision } from "./errors.js"; diff --git a/server/typescript/packages/migrate-ts/src/scope.ts b/server/typescript/packages/migrate-ts/src/scope.ts index b6f4dbb786..2fb10f8b82 100644 --- a/server/typescript/packages/migrate-ts/src/scope.ts +++ b/server/typescript/packages/migrate-ts/src/scope.ts @@ -52,6 +52,7 @@ import { DEFAULT_DB_SCHEMA_POSTGRES } from "@metaobjectsdev/metadata"; import type { DiffArgs } from "./diff/index.js"; import type { ExpectedSchemaWithProvenance } from "./expected-schema.js"; +import { FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; import { qualifiedDbName } from "./qualified-name.js"; import type { SchemaSnapshot } from "./types.js"; @@ -96,6 +97,12 @@ export interface ScopedExpectedSchema { * declares no dependencies. */ importedOutOfScope?: string[]; + /** + * FKs whose target is not a unique key, on tables this run does NOT govern (imported, or + * outside `migrate.scope`): never emitted by this project, so reported rather than + * refused. The ones on governed tables are refused by `scopeExpectedSchema` itself. + */ + ungovernedFkTargetViolations?: FkTargetViolation[]; } /** @@ -277,7 +284,7 @@ export function scopeExpectedSchema( ): ScopedExpectedSchema { const imported = opts?.imported; if (inScope === undefined && imported === undefined) { - return { snapshot: built.snapshot, outOfScope: [] }; + return withFkTargetVerdict(built, { snapshot: built.snapshot, outOfScope: [] }); } // PASS 1 — the import partition. An imported object survives only when the @@ -321,7 +328,7 @@ export function scopeExpectedSchema( return false; }; - return { + return withFkTargetVerdict(built, { snapshot: { ...remainder, tables: remainder.tables.filter(governed), @@ -332,5 +339,18 @@ export function scopeExpectedSchema( outOfScope: [...importedOutOfScope, ...scopeOutOfScope], ...(declared.length > 0 ? { declaredSchemas: declared } : {}), ...(imported !== undefined ? { importedOutOfScope } : {}), - }; + }); +} + +/** + * Refuse every FK-target violation on a table the scoped run governs (its FK would be + * emitted and fail at apply), and return the others for the caller to report. + */ +function withFkTargetVerdict(built: ExpectedSchemaWithProvenance, scoped: ScopedExpectedSchema): ScopedExpectedSchema { + const violations = built.fkTargetViolations ?? []; + if (violations.length === 0) return scoped; + const governedTables = new Set(scoped.snapshot.tables.map(qualifiedDbName)); + const governed = violations.filter((v) => governedTables.has(v.table)); + if (governed.length > 0) throw new FkTargetNotUniqueError(governed); + return { ...scoped, ungovernedFkTargetViolations: violations }; } diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts index 29b32a2928..36954922d7 100644 --- a/server/typescript/packages/migrate-ts/src/types.ts +++ b/server/typescript/packages/migrate-ts/src/types.ts @@ -258,6 +258,19 @@ export type Change = indexRenames?: NameChange[]; status: ChangeStatus; } + | { + kind: "rename-constraints"; table: string; schema?: string; + /** + * Constraints (FK / CHECK / constraint-backed index) on a table that is NOT renamed, + * whose definition is unchanged and whose name differs — e.g. after the project's + * schema conventions changed. Renamed in place, never dropped and re-created. + * Postgres only; sqlite/d1 cannot rename a constraint and keep the drop+add. + */ + constraintRenames?: NameChange[]; + /** Plain indexes on that table whose definition is unchanged and whose name differs. Postgres only. */ + indexRenames?: NameChange[]; + status: ChangeStatus; + } | { kind: "add-column"; table: string; schema?: string; column: ColumnDescriptor; status: ChangeStatus } | { kind: "drop-column"; table: string; schema?: string; column: string; restore?: ColumnDescriptor; status: ChangeStatus } | { diff --git a/server/typescript/packages/migrate-ts/test/integration/pg-constraint-backed-index-285.test.ts b/server/typescript/packages/migrate-ts/test/integration/pg-constraint-backed-index-285.test.ts index 09c1af2cdb..943ff89712 100644 --- a/server/typescript/packages/migrate-ts/test/integration/pg-constraint-backed-index-285.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/pg-constraint-backed-index-285.test.ts @@ -19,7 +19,9 @@ * The gate is a REAL engine, per this package's doctrine — emitted-SQL inspection is * exactly what missed the bug, since the SQL looked perfectly reasonable: * 1. Build the live shape the way Drizzle does (a UNIQUE *constraint*). - * 2. Diff against metadata that names the key differently → drop-index + add-index. + * 2. Diff against metadata whose key is DEFINED differently (here: partial) → drop-index + * + add-index. (A key that differs only in NAME is renamed in place — RENAME + * CONSTRAINT — and never dropped; the last test below gates that.) * 3. APPLY to the real engine. Pre-fix this throws; that is the regression. * 4. Re-introspect and re-diff → MUST be empty (convergence, not just "it ran"). * 5. Prove uniqueness is still enforced afterwards — a dropped constraint that took @@ -40,8 +42,9 @@ import { emit } from "../../src/emit/index.js"; const PG_URL = process.env["MIGRATE_TS_PG_URL"]; // `identity.secondary` names the unique key `byMessageId`, while the live constraint is -// called `work_item_message_id_unique` — the rename that triggers drop+add. -const META = JSON.stringify({ +// called `work_item_message_id_unique`. META_PARTIAL also makes the key partial — a change +// of DEFINITION, which is what drops it; META alone is a pure rename. +const meta = (secondary: Record) => JSON.stringify({ "metadata.root": { package: "acme", children: [ @@ -53,13 +56,15 @@ const META = JSON.stringify({ { "field.long": { name: "id" } }, { "field.string": { name: "messageId", "@column": "message_id", "@required": true } }, { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, - { "identity.secondary": { name: "byMessageId", "@fields": ["messageId"] } }, + { "identity.secondary": { name: "byMessageId", "@fields": ["messageId"], ...secondary } }, ], }, }, ], }, }); +const META = meta({}); +const META_PARTIAL = meta({ "@where": "message_id <> ''" }); async function applyRaw(k: Kysely>, sqlText: string): Promise { for (const stmt of sqlText.split(";").map((s) => s.trim()).filter((s) => s.length > 0)) { @@ -115,7 +120,7 @@ describe("#285 — constraint-backed index drops as a constraint (PG)", () => { expect(bare?.constraint).toBeUndefined(); }); - test("REGRESSION: the rename applies against a real engine, converges, and keeps uniqueness", async () => { + test("REGRESSION: a redefined key is dropped as a constraint, applies, converges, and keeps uniqueness", async () => { await sql.raw("DROP TABLE IF EXISTS work_item CASCADE").execute(kysely); await sql .raw( @@ -127,14 +132,14 @@ describe("#285 — constraint-backed index drops as a constraint (PG)", () => { ) .execute(kysely); - const loaded = await new MetaDataLoader().load([new InMemoryStringSource(META)]); + const loaded = await new MetaDataLoader().load([new InMemoryStringSource(META_PARTIAL)]); expect(loaded.errors).toEqual([]); const expectedSchema = buildExpectedSchema(loaded.root, { dialect: "postgres" }); const actual = await introspectPostgres(kysely); const d = await diff({ expected: expectedSchema, actual, dialect: "postgres", allow: { dropIndex: true } }); - // The rename really does present as drop+add — the precondition for the bug. + // The redefinition really does present as drop+add — the precondition for the bug. expect(d.changes.some((c) => c.kind === "drop-index")).toBe(true); const sqlText = emit(d.changes, { dialect: "postgres" }).up; @@ -163,4 +168,36 @@ describe("#285 — constraint-backed index drops as a constraint (PG)", () => { sql.raw(`INSERT INTO work_item (message_id) VALUES ('m-1')`).execute(kysely), ).rejects.toThrow(/unique|duplicate key/i); }); + + test("a key that differs only in NAME is renamed in place: RENAME CONSTRAINT, converges, still unique", async () => { + await sql.raw("DROP TABLE IF EXISTS work_item CASCADE").execute(kysely); + await sql + .raw( + `CREATE TABLE work_item ( + id serial PRIMARY KEY, + message_id text NOT NULL, + CONSTRAINT work_item_message_id_unique UNIQUE (message_id) + )`, + ) + .execute(kysely); + const loaded = await new MetaDataLoader().load([new InMemoryStringSource(META)]); + expect(loaded.errors).toEqual([]); + const expectedSchema = buildExpectedSchema(loaded.root, { dialect: "postgres" }); + + const d = await diff({ expected: expectedSchema, actual: await introspectPostgres(kysely), dialect: "postgres" }); + // (The fixture's `serial` id against the model's long also yields a column-type change.) + expect(d.changes.filter((c) => c.kind === "rename-constraints")).toHaveLength(1); + expect(d.changes.some((c) => c.kind === "drop-index" || c.kind === "add-index")).toBe(false); + const sqlText = emit(d.changes, { dialect: "postgres" }).up; + expect(sqlText).toContain('RENAME CONSTRAINT "work_item_message_id_unique" TO "byMessageId"'); + expect(sqlText).not.toMatch(/DROP (INDEX|CONSTRAINT)/); + + await applyRaw(kysely, sqlText); + const reDiff = await diff({ expected: expectedSchema, actual: await introspectPostgres(kysely), dialect: "postgres" }); + expect(reDiff.changes.map((c) => c.kind)).toEqual([]); + await sql.raw(`INSERT INTO work_item (message_id) VALUES ('m-1')`).execute(kysely); + await expect( + sql.raw(`INSERT INTO work_item (message_id) VALUES ('m-1')`).execute(kysely), + ).rejects.toThrow(/unique|duplicate key/i); + }); }); diff --git a/server/typescript/packages/migrate-ts/test/unit/diff-rename-constraints.test.ts b/server/typescript/packages/migrate-ts/test/unit/diff-rename-constraints.test.ts new file mode 100644 index 0000000000..9ef6479824 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/diff-rename-constraints.test.ts @@ -0,0 +1,89 @@ +/** + * A constraint or index whose definition is unchanged and whose NAME differs is renamed, + * not dropped and re-created — on a table that is not itself renamed, too. + * + * Switching a project's schema conventions (default → efcore) renames every FK. Before + * this, each one became a gated `drop-fk` plus an `add-fk`: the migration was blocked + * behind `--allow drop-fk`, and allowing it dropped and rebuilt every foreign key on a + * live database. On Postgres the pair is one `ALTER TABLE … RENAME CONSTRAINT`, the same + * fold a table rename already gets. SQLite cannot rename a constraint, so it keeps the + * rebuild there. + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { defaultConventions, efcoreConventions } from "../../src/schema-conventions.js"; +import { diff } from "../../src/diff/index.js"; +import { emit } from "../../src/emit/index.js"; + +const DOC = { + "metadata.root": { + package: "acme", + children: [ + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "Orders" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }, + { "object.entity": { name: "OrderLine", children: [ + { "source.rdb": { "@table": "OrderLines" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.long": { name: "orderId", "@column": "OrderId" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "index.lookup": { name: "IX_OrderLines_OrderId", "@fields": ["orderId"] } }, + { "identity.reference": { name: "order", "@fields": ["orderId"], "@references": "Order" } }, + ] } }, + ], + }, +}; + +async function schemas() { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(DOC))]); + expect(errors).toHaveLength(0); + return { + live: buildExpectedSchema(root, { conventions: defaultConventions }), + wanted: buildExpectedSchema(root, { conventions: efcoreConventions }), + }; +} + +describe("an FK whose only change is its name", () => { + test("Postgres: one rename-constraints change, no drop-fk / add-fk", async () => { + const { live, wanted } = await schemas(); + const { changes } = await diff(wanted, live, { dialect: "postgres" }); + + expect(changes.filter((c) => c.kind === "drop-fk" || c.kind === "add-fk")).toEqual([]); + const renames = changes.filter((c) => c.kind === "rename-constraints"); + expect(renames).toHaveLength(1); + expect(renames[0]).toMatchObject({ + table: "OrderLines", + constraintRenames: [{ from: "OrderLines_OrderId_fk", to: "FK_OrderLines_Orders_OrderId" }], + }); + }); + + test("Postgres: rendered as RENAME CONSTRAINT, and the down renames it back", async () => { + const { live, wanted } = await schemas(); + const { changes } = await diff(wanted, live, { dialect: "postgres" }); + const { up, down } = emit(changes, { dialect: "postgres" }); + + expect(up).toContain('ALTER TABLE "OrderLines" RENAME CONSTRAINT "OrderLines_OrderId_fk" TO "FK_OrderLines_Orders_OrderId";'); + expect(down).toContain('ALTER TABLE "OrderLines" RENAME CONSTRAINT "FK_OrderLines_Orders_OrderId" TO "OrderLines_OrderId_fk";'); + expect(up).not.toContain("DROP CONSTRAINT"); + }); + + test("an FK whose definition also changed is still dropped and re-added", async () => { + const { live, wanted } = await schemas(); + const actual = structuredClone(live); + actual.tables.find((t) => t.name === "OrderLines")!.foreignKeys[0]!.onDelete = "cascade"; + const { changes } = await diff(wanted, actual, { dialect: "postgres" }); + + expect(changes.some((c) => c.kind === "drop-fk")).toBe(true); + expect(changes.some((c) => c.kind === "rename-constraints")).toBe(false); + }); + + test("SQLite does not fold (it cannot rename a constraint)", async () => { + const { live, wanted } = await schemas(); + const { changes } = await diff(wanted, live, { dialect: "sqlite" }); + + expect(changes.some((c) => c.kind === "rename-constraints")).toBe(false); + }); +}); diff --git a/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts b/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts index 145fd35dc2..558a8a5719 100644 --- a/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/fk-target-unique.test.ts @@ -15,6 +15,8 @@ import { describe, test, expect } from "bun:test"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildExpectedSchema } from "../../src/expected-schema.js"; import { FkTargetNotUniqueError } from "../../src/errors.js"; +import { buildExpectedSchemaWithProvenance } from "../../src/expected-schema.js"; +import { scopeExpectedSchema } from "../../src/scope.js"; async function loadDoc(doc: unknown) { const { root, errors } = await new MetaDataLoader().load([ @@ -150,4 +152,72 @@ describe("buildExpectedSchema — an FK must reference a unique key", () => { expect(await build({ references: "Person", holderFields: ["personId"] })).not.toThrow(); expect(await build({ references: "Person.id", holderFields: ["personId"] })).not.toThrow(); }); + + test("a TPH subtype's unique key is not emitted, so it does not count — the hint names the base", async () => { + const doc = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Party", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "parties" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "kind", "@values": ["Carrier", "Broker"] } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.entity": { name: "Carrier", extends: "Party", "@discriminatorValue": "Carrier", children: [ + { "field.string": { name: "code" } }, + { "identity.secondary": { name: "ux_carrier_code", "@fields": ["code"] } }, + ] } }, + { "object.entity": { name: "Policy", children: [ + { "source.rdb": { "@table": "policies" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "carrierCode" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "ref_carrier", "@fields": ["carrierCode"], "@references": "Carrier.code" } }, + ] } }, + ] } }; + const root = await loadDoc(doc); + + expect(() => buildExpectedSchema(root)).toThrow(FkTargetNotUniqueError); + expect(() => buildExpectedSchema(root)).toThrow(/stored in the table of "Party".*declare it on "Party"/); + }); + + test("a bare reference into a composite primary key with one FK field is refused", async () => { + const doc = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Line", children: [ + { "source.rdb": {} }, + { "field.long": { name: "orderId" } }, + { "field.int": { name: "lineNo" } }, + { "identity.primary": { name: "pk", "@fields": ["orderId", "lineNo"] } }, + ] } }, + { "object.entity": { name: "Note", children: [ + { "source.rdb": {} }, + { "field.long": { name: "id" } }, + { "field.long": { name: "lineOrderId" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "identity.reference": { name: "ref_line", "@fields": ["lineOrderId"], "@references": "Line" } }, + ] } }, + ] } }; + + const root = await loadDoc(doc); + + expect(() => buildExpectedSchema(root)).toThrow(FkTargetNotUniqueError); + expect(() => buildExpectedSchema(root)).toThrow(/reference "ref_line" targets \[orderId\] on "Line"/); + }); + + test("a target this model does not build (@unmanaged) is not refused: its keys are not known here", async () => { + const doc = makeDoc({ references: "Person.code", holderFields: ["personCode"] }); + const person = (doc["metadata.root"].children[0] as { "object.entity": { children: unknown[] } })["object.entity"]; + person.children[0] = { "source.rdb": { "@unmanaged": true } }; + const root = await loadDoc(doc); + + expect(() => buildExpectedSchema(root)).not.toThrow(); + }); + + test("through scopeExpectedSchema only a governed holder is refused; the others are returned", async () => { + const root = await loadDoc(makeDoc({ references: "Person.code", holderFields: ["personCode"] })); + const built = buildExpectedSchemaWithProvenance(root); + + expect(built.fkTargetViolations?.map((v) => v.referenceName)).toEqual(["ref_person"]); + expect(() => scopeExpectedSchema(built, undefined)).toThrow(FkTargetNotUniqueError); + const outside = scopeExpectedSchema(built, (fqn) => !fqn.endsWith("Visit")); + expect(outside.ungovernedFkTargetViolations?.map((v) => v.referenceName)).toEqual(["ref_person"]); + }); }); From db95122ce74327fb9f0a8d55896dd133ceb63ef4 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 10:59:28 -0500 Subject: [PATCH 009/267] fix(migrate): review fixes for schema conventions and FK introspection - Postgres FK introspection reads same-schema FKs only again: pg_constraint also returns cross-schema ones, which (with no referenced schema in the descriptor) read as FKs to a same-named table and showed up as drift. - efcore FK indexes are decided per table (foreignKeyIndexes): a partial index covers an FK, as EF Core's AreIndexedBy ignores filters, and an FK index another FK index covers is dropped, so FK order no longer matters. - A unique key with a DESC column or a non-btree @using stays an index under efcore; referenced-key detection is schema-qualified. - A project's conventions object missing a member is refused by name (InvalidSchemaConventionsError), not a TypeError mid-build. - meta migrate warns when metaobjects.config.ts exists but does not load, naming what the run goes without; @metaobjectsdev/migrate-ts is aliased for configs, so importing a preset resolves under any install layout. - prerelease: a section for the next major is still the base; doc comments updated. - Docs and CHANGELOG say what the conventions match and what a switch on an existing database does. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++-- docs/features/migrations-and-drift.md | 29 ++++++---- scripts/prerelease-version.mjs | 10 ++-- scripts/prerelease.mjs | 3 +- scripts/test-prerelease-version.mjs | 10 +++- .../packages/cli/src/commands/migrate.ts | 10 +++- .../cli/src/lib/load-metaobjects-config.ts | 19 +++++++ .../test/migrate-schema-conventions.test.ts | 27 +++++++++- .../packages/migrate-ts/src/emit/postgres.ts | 3 +- .../packages/migrate-ts/src/errors.ts | 14 ++++- .../migrate-ts/src/expected-schema.ts | 31 ++++++----- .../packages/migrate-ts/src/index.ts | 3 +- .../migrate-ts/src/introspect/postgres.ts | 4 ++ .../migrate-ts/src/schema-conventions.ts | 54 ++++++++++++++----- .../postgres-composite-fk-introspect.test.ts | 21 ++++++++ .../unit/expected-schema-conventions.test.ts | 43 +++++++++++++++ .../test/unit/schema-conventions.test.ts | 41 ++++++++++---- 17 files changed, 269 insertions(+), 62 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 013c6b93da..551cd3e917 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,8 +27,10 @@ here.** unless you set it. `efcore` reproduces EF Core's conventions (`PK_`, `FK_`, `IX_`, its 63-character `~` truncation, alternate keys as constraints), so a database built by EF Core migrations and one built by `meta migrate` match. A project can supply its own conventions - object from `metaobjects.config.ts`. An unknown preset name is refused by name. See - `docs/features/migrations-and-drift.md`, "Schema conventions". + object from `metaobjects.config.ts`; an unknown preset name, or an object missing a member, is + refused by name. The PK name is now introspected too, so a `baseline --from-db` snapshot of a + database whose primary keys are not named `
_pkey` records their names (not compared; + nothing churns). See `docs/features/migrations-and-drift.md`, "Schema conventions". - **A recipe for checking an API change against the last release.** Emit the document at the last tag and at `HEAD`, then run oasdiff. See `docs/recipes/check-api-against-last-release.md`. - **A `pydantic` extra on the Python package.** `pip install "metaobjects[pydantic]"` installs @@ -85,7 +87,8 @@ here.** a three-column one as nine. `meta migrate` reads its expected side back from the shadow database, so the doubled columns reached the emitted DDL, which Postgres refused ("foreign key referenced-columns list must not contain duplicates"); `verify --db` misreported every composite FK. It now reads - `pg_constraint`, pairing `conkey` with `confkey` by position. + `pg_constraint`, pairing `conkey` with `confkey` by position. As before, only same-schema foreign + keys are read (the FK descriptor carries no referenced schema). - **Python: an array field's `default` generated a string.** A model with `field.string[]: { default: "{}" }` generated `tags: list[str] = '{}'`, which fails on first use. diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index fb1ee13c98..d5282d43dc 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -384,13 +384,17 @@ come from the project's **schema conventions**, selected in `.metaobjects/config |---|---|---| | Primary-key constraint name | `
_pkey` | `PK_
` | | Foreign-key constraint name | `
__fk` | `FK_
__` | -| Index on a foreign key | none | `IX_
_`, unless the primary key or an index already starts with the FK's columns | -| Unique key (`identity.secondary`) | a unique index | a UNIQUE constraint when a foreign key references it, else a unique index | - -`efcore` reproduces EF Core's own conventions, including its truncation of a name longer -than 63 characters to 62 characters and `~`, so a database first built by EF Core migrations -and one built by `meta migrate` have the same catalog. `default` is what migrate has always -emitted. +| Index on a foreign key | none | `IX_
_`, unless the primary key or another index (a partial one included) already starts with the FK's columns; an FK index another FK index covers is dropped, so FK order does not matter | +| Unique key (`identity.secondary`, a `@unique` field) | a unique index | a UNIQUE constraint when a foreign key references it, else a unique index | + +`efcore` follows EF Core's own conventions on PostgreSQL (Npgsql), including its truncation of a +name longer than 63 characters to 62 characters and `~`. A database first built by EF Core +migrations and one built by `meta migrate` then agree on these objects. Where the EF Core model +carried something its conventions do not (a hand-named key, an index dropped by raw SQL), declare +it in metadata. A unique key keeps the name its metadata node declares (EF Core would call an +alternate key `AK_…`; name the node that if you want EF's). A key with a `DESC` column or a +non-btree `@using` stays an index, since a UNIQUE constraint carries neither. `default` is what +migrate has always emitted. Names code does address are not conventions. Tables, views and columns resolve in core naming (`naming`, and `@table` / `@column`), the same in every port. A constraint or index a @@ -399,7 +403,8 @@ declared in metadata: `@constraintName` on an `identity.reference`, or the index name. A declared name always wins over a convention. A project can supply its own conventions from `metaobjects.config.ts`, which wins over the -preset name: +preset name. Start from a preset so every member is present; an object missing one is refused +by name: ```ts import { defineConfig } from "@metaobjectsdev/cli"; @@ -411,9 +416,11 @@ export default defineConfig({ }); ``` -The conventions shape what migrate creates. The PK name and whether a unique key is a -constraint or an index are not compared by the diff, so changing them never churns an -existing database; FK and index names are compared, as they always have been. +**Changing the conventions of an existing database.** On Postgres, an FK, CHECK or index whose +definition is unchanged and whose name differs is renamed in place (`RENAME CONSTRAINT` / +`ALTER INDEX … RENAME`), never dropped and re-created; new FK indexes are created. The PK name +and whether a unique key is a constraint or an index are not compared by the diff, so they only +shape what migrate creates. SQLite cannot rename a constraint and rebuilds the table instead. ## How CHECK constraints and expression indexes are compared diff --git a/scripts/prerelease-version.mjs b/scripts/prerelease-version.mjs index c392a9d483..e54510abf0 100644 --- a/scripts/prerelease-version.mjs +++ b/scripts/prerelease-version.mjs @@ -46,7 +46,8 @@ export function releasedVersion({ npmLatest, tags, major }) { * The version this cut is FOR: `{ base, source }`, or throws an Error whose message says why not. * * - A CHANGELOG section newer than the release is unpublished work; the lowest one is the next - * release, and the cut is for it. + * release, and the cut is for it. Only sections on the released major line or the next one + * count: the historical Maven-only [7.x] sections are not this line's work. * - `--base` may name that version, or any version when every section is published. It may not * name an already released version, and it may not SKIP an unpublished section: that is the * mis-numbering this exists to refuse, reached by hand instead of by guess. @@ -61,11 +62,12 @@ export function decideBase({ released, changelog, explicit }) { "Pass --base (the CHANGELOG section being prepared).", ); } - // Only sections on the released major line: the CHANGELOG also carries the old Maven-only - // [7.x] sections, which sort above every 1.x number and were proposed as the next base. + // Only sections on the released major line or the next one (a major being prepared): the + // CHANGELOG also carries the old Maven-only [7.x] sections, which sort above every 1.x + // number and were proposed as the next base. const major = Number(released.split(".")[0]); const unpublished = changelog - .filter((v) => Number(v.split(".")[0]) === major && cmpVer(v, released) > 0) + .filter((v) => Number(v.split(".")[0]) <= major + 1 && cmpVer(v, released) > 0) .sort(cmpVer); if (explicit != null) { if (cmpVer(explicit, released) <= 0) diff --git a/scripts/prerelease.mjs b/scripts/prerelease.mjs index e9a1b284da..ea129bfe49 100644 --- a/scripts/prerelease.mjs +++ b/scripts/prerelease.mjs @@ -9,7 +9,8 @@ // bun run prerelease:publish --iter 5 # pin the iteration number // bun run prerelease:publish --base 0.25.0 # override the in-development version // -// The base version is the lowest CHANGELOG.md `## [x.y.z]` section that is not released yet — +// The base version is the lowest CHANGELOG.md `## [x.y.z]` section on the released major line (or +// the next major) that is not released yet — // the repository's own declaration of what is being worked on — falling back to minor+1 when // every section is released. "Released" is read from public npm and the release tags, never // from package.json (release prep bumps that first). `--base` may override, but never to skip diff --git a/scripts/test-prerelease-version.mjs b/scripts/test-prerelease-version.mjs index e4b41383fc..0b07f458bd 100644 --- a/scripts/test-prerelease-version.mjs +++ b/scripts/test-prerelease-version.mjs @@ -7,10 +7,10 @@ // skips an unpublished CHANGELOG section (release prep bumped package.json to 1.1.0 and the // next rc went out as 1.2.0-rc.3). // P2 the iteration counter reads every page of the registry's listing. -// P4 only CHANGELOG sections on the released major line count; the old Maven-only [7.x] sections -// made a cut after 1.2.0 propose 7.20.12. // P3 a SIGTERM restores the version files, as exit and SIGINT already did, and stops a step that // is still running instead of letting the run publish the remaining registries first. +// P4 only CHANGELOG sections on the released major line or the next one count; the old Maven-only [7.x] sections +// made a cut after 1.2.0 propose 7.20.12. import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -48,6 +48,12 @@ await test("P4: a section from another major line (the old Maven-only [7.x]) is assert.equal(decideBase({ released: "1.2.0", changelog: changelogVersions(md), explicit: "1.2.1" }).base, "1.2.1"); }); +await test("P4: the NEXT major's section, being prepared, is still the base", () => { + const md = "## [Unreleased]\n\n## [2.0.0]\n\n## [1.2.0] — 2026-10-30\n\n## [7.20.12] — 2026-08-02\n"; + assert.deepEqual(decideBase({ released: "1.2.0", changelog: changelogVersions(md), explicit: null }), + { base: "2.0.0", source: "CHANGELOG.md" }); +}); + await test("P1: release prep's package.json bump does not make 1.1.0 'released'", () => { // package.json says 1.1.0 (the prep PR); npm and the tags say 1.0.13. const released = releasedVersion({ npmLatest: "1.0.13", tags: ["v1.0.13", "v1.1.0-rc.2"], major: 1 }); diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index 7f875c97bc..0320c1cc5d 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -13,7 +13,7 @@ import { buildKyselyFromUrl, inferDialect, redactUrl } from "../lib/kysely.js"; import { describeExprCanonPath, shadowSession } from "../lib/shadow.js"; import { log } from "../lib/log.js"; import { loadMemory, resolveCollection, resolveConfigDir, type Collection } from "@metaobjectsdev/sdk"; -import { loadMemoryOptionsFrom, loadMetaobjectsConfig, RemovedNamingConfigError, resolveGenConfigDir } from "../lib/load-metaobjects-config.js"; +import { configNotLoadedWarning, loadMemoryOptionsFrom, loadMetaobjectsConfig, RemovedNamingConfigError, resolveGenConfigDir } from "../lib/load-metaobjects-config.js"; import { collectionLoadOptions } from "../lib/collection-load-options.js"; import { exclusionNotes, importedOption, migrateScopeMismatch } from "../lib/migrate-scope.js"; import { @@ -759,6 +759,8 @@ export async function migrateCommand( log.error(e.message); return 2; } + const warning = configNotLoadedWarning(genRoot, e, "migrate"); + if (warning !== undefined) log.warn(warning); postgresLoadOptions = {}; } @@ -1199,6 +1201,8 @@ async function loadBaselineMetadata(metaRoot: string, genRoot: string) { } catch (e) { if (e instanceof RemovedNamingConfigError) throw e; // config absent — no custom providers, no libraries, default snake_case + const warning = configNotLoadedWarning(genRoot, e, "migrate"); + if (warning !== undefined) log.warn(warning); } const collection = await resolveCollection(metaRoot); return await loadMemory(collection.configDir, { @@ -1496,6 +1500,8 @@ export async function runOfflineGenerate( return 2; } // config absent — no custom providers, no libraries, default snake_case + const warning = configNotLoadedWarning(genRoot, e, "migrate"); + if (warning !== undefined) log.warn(warning); } let metadata; @@ -1792,6 +1798,8 @@ async function runD1Migrate( log.error(e.message); return 2; } + const warning = configNotLoadedWarning(genRoot, e, "migrate"); + if (warning !== undefined) log.warn(warning); d1LoadOptions = {}; } diff --git a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts index 8d399a0727..45f8190ee5 100644 --- a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts +++ b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts @@ -52,6 +52,13 @@ const CLI_PKG_PATHS: Record = { dist: "node_modules/@metaobjectsdev/metadata/dist/index.js", src: "node_modules/@metaobjectsdev/metadata/src/index.ts", }, + // A config that supplies its own schema conventions starts from a preset + // (`efcoreConventions`) — aliased like the other codegen specifiers so the project + // needn't declare migrate-ts directly, and a global CLI still resolves it. + "@metaobjectsdev/migrate-ts": { + dist: "node_modules/@metaobjectsdev/migrate-ts/dist/index.js", + src: "node_modules/@metaobjectsdev/migrate-ts/src/index.ts", + }, "@metaobjectsdev/codegen-ts/generators": { dist: "node_modules/@metaobjectsdev/codegen-ts/dist/generators/index.js", src: "node_modules/@metaobjectsdev/codegen-ts/src/generators/index.ts", @@ -203,6 +210,18 @@ function rewriteImportSpecifiers(source: string, aliasMap: Record { let out: string[] = []; let infoSpy: ReturnType; let errSpy: ReturnType; +let warnSpy: ReturnType; beforeEach(() => { out = []; infoSpy = spyOn(log, "info").mockImplementation((m: string) => { out.push(String(m)); }); errSpy = spyOn(log, "error").mockImplementation((m: string) => { out.push(String(m)); }); + warnSpy = spyOn(log, "warn").mockImplementation((m: string) => { out.push(String(m)); }); }); -afterEach(() => { infoSpy.mockRestore(); errSpy.mockRestore(); }); +afterEach(() => { infoSpy.mockRestore(); errSpy.mockRestore(); warnSpy.mockRestore(); }); const dryRun = (root: string) => migrateCommand(["--from-db", "--db", `file:${join(root, "t.db")}`, "--dialect", "sqlite", "--dry-run"], root); @@ -81,4 +83,27 @@ describe("meta migrate with migrate.conventions", () => { expect(text).toContain('migrate.conventions "hibernate" is not a schema-conventions preset: expected one of default, efcore'); expect(text).not.toContain("unexpected error"); }); + + test("a conventions object from metaobjects.config.ts applies, importing the preset from migrate-ts", async () => { + const root = await project(undefined); + await writeFile(join(root, "metaobjects.config.ts"), [ + 'import { efcoreConventions } from "@metaobjectsdev/migrate-ts";', + "export default { generators: [], schemaConventions: { ...efcoreConventions, id: \"acme\" } };", + "", + ].join("\n"), "utf8"); + + expect(await dryRun(root)).toBe(0); + expect(out.join("\n")).toContain('CREATE INDEX "IX_OrderLines_OrderId"'); + }); + + test("a metaobjects.config.ts that exists but does not load is warned about, not silently ignored", async () => { + const root = await project(undefined); + await writeFile(join(root, "metaobjects.config.ts"), 'throw new Error("config exploded");\n', "utf8"); + + expect(await dryRun(root)).toBe(0); + const text = out.join("\n"); + expect(text).toContain("metaobjects.config.ts exists but did not load"); + expect(text).toContain("config exploded"); + expect(text).toContain("schemaConventions"); + }); }); diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index 8f640cfa34..e9f37e08ef 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -1,3 +1,4 @@ +import { canBeUniqueConstraint } from "../schema-conventions.js"; import type { Change, EmitResult, ColumnDescriptor, IndexDescriptor, FkDescriptor, TableDescriptor, ViewDescriptor, ColumnDefault, FkAction, NameChange, DataHazard, @@ -566,7 +567,7 @@ function renderDefault(d: ColumnDefault): string { /** A unique key the schema conventions create as a constraint (only a plain column key can be one). */ function isUniqueConstraint(ix: IndexDescriptor): boolean { - return ix.constraint === "unique" && ix.unique && ix.where === undefined && ix.expr === undefined; + return ix.constraint === "unique" && canBeUniqueConstraint(ix); } function renderCreateIndex(table: string, schema: string | undefined, ix: IndexDescriptor): string { diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index dae730384a..ce1ca37afe 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -333,9 +333,19 @@ export class UnknownSchemaConventionsError extends Error { } } +/** A project-supplied schema-conventions object lacks members this version calls. */ +export class InvalidSchemaConventionsError extends Error { + override readonly name = "InvalidSchemaConventionsError"; + constructor(readonly id: string, readonly missing: readonly string[]) { + super(`the schema conventions "${id}" are missing ${missing.join(", ")} — start from a preset ` + + `({ ...efcoreConventions, id: "${id}", … }) so every member this version calls is present`); + } +} + /** Is `err` the {@link UnknownSchemaConventionsError}? */ -export function isUnknownSchemaConventionsError(err: unknown): err is UnknownSchemaConventionsError { - return err instanceof Error && err.name === "UnknownSchemaConventionsError"; +export function isUnknownSchemaConventionsError(err: unknown): err is UnknownSchemaConventionsError | InvalidSchemaConventionsError { + // Both are a project's conventions selection the tool cannot use: a config error. + return err instanceof Error && (err.name === "UnknownSchemaConventionsError" || err.name === "InvalidSchemaConventionsError"); } /** Is `err` the {@link FkTargetNotUniqueError} from FKs whose targets are not unique keys? */ diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 34ced0a6f3..7b77973bc8 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,5 +1,5 @@ import { DuplicateSqlNameError, FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; -import { resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; +import { canBeUniqueConstraint, resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, } from "@metaobjectsdev/metadata"; @@ -1159,35 +1159,40 @@ function collectFkTargetViolations( * `@constraintName` is known. The default conventions change nothing here. */ function applySchemaConventions(tables: TableDescriptor[], conventions: SchemaConventions): void { - const keyOf = (table: string, columns: readonly string[]) => `${table}|${[...columns].sort().join(",")}`; - const referenced = new Set(tables.flatMap((t) => t.foreignKeys.map((fk) => keyOf(fk.refTable, fk.refColumns)))); + // An FK references a table in its own schema (the emitter's assumption), so the key is schema-qualified. + const keyOf = (schema: string | undefined, table: string, columns: readonly string[]) => + `${schema ?? ""}.${table}|${[...columns].sort().join(",")}`; + const referenced = new Set(tables.flatMap((t) => t.foreignKeys.map((fk) => keyOf(t.schema, fk.refTable, fk.refColumns)))); for (const t of tables) { if (t.primaryKey.length > 0) { const pkName = conventions.primaryKeyName({ table: t.name, columns: t.primaryKey }); if (pkName !== `${t.name}_pkey`) t.primaryKeyName = pkName; } for (const ix of t.indexes) { - if (!ix.unique || ix.where !== undefined || ix.expr !== undefined) continue; - const kind = conventions.uniqueKeyKind({ table: t.name, columns: ix.columns, referencedByForeignKey: referenced.has(keyOf(t.name, ix.columns)) }); + // Only a plain key can be a UNIQUE constraint: one with a predicate, an expression, a DESC + // column or a non-btree method stays an index whatever the conventions prefer. + if (!canBeUniqueConstraint(ix)) continue; + const kind = conventions.uniqueKeyKind({ table: t.name, columns: ix.columns, referencedByForeignKey: referenced.has(keyOf(t.schema, t.name, ix.columns)) }); if (kind === "constraint") ix.constraint = "unique"; } - for (const fk of t.foreignKeys) { - const index = conventions.foreignKeyIndex( - { table: t.name, columns: fk.columns, refTable: fk.refTable, refColumns: fk.refColumns }, - { primaryKey: t.primaryKey, indexes: t.indexes }, - ); - if (index === undefined) continue; + const fkIndexes = conventions.foreignKeyIndexes({ + table: t.name, + primaryKey: t.primaryKey, + indexes: t.indexes, + foreignKeys: t.foreignKeys.map((fk) => ({ table: t.name, columns: fk.columns, refTable: fk.refTable, refColumns: fk.refColumns })), + }); + for (const index of fkIndexes) { if (t.indexes.some((ix) => ix.name === index.name)) { throw new DuplicateSqlNameError([{ name: index.name, owners: [ - `the ${conventions.id} conventions' index for foreign key "${fk.name}" on table "${t.name}"`, + `the ${conventions.id} conventions' foreign-key index on [${index.columns.join(", ")}] of table "${t.name}"`, `an index already named "${index.name}" on table "${t.name}"`, ], involvesIndex: true, }]); } - t.indexes.push({ name: index.name, columns: [...fk.columns], unique: false }); + t.indexes.push({ name: index.name, columns: [...index.columns], unique: false }); } } } diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index f46d86cb90..dcbb10485a 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -19,7 +19,7 @@ export { introspect, introspectPostgres, introspectSqlite } from "./introspect/i export { diff } from "./diff/index.js"; export { defaultConventions, efcoreConventions, resolveSchemaConventions, SCHEMA_CONVENTION_PRESETS, - type SchemaConventions, type KeyContext, type ForeignKeyContext, type ExistingKeys, + type SchemaConventions, type KeyContext, type ForeignKeyContext, type TableKeys, } from "./schema-conventions.js"; export { collectUnmanagedNames } from "./unmanaged.js"; // Per-command scope (`migrate.scope`) — see scope.ts for why the suppression is @@ -64,6 +64,7 @@ export { isFkTargetNotUniqueError, isUnknownSchemaConventionsError, UnknownSchemaConventionsError, + InvalidSchemaConventionsError, FkTargetNotUniqueError, type FkTargetViolation, } from "./errors.js"; diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index a2c174c297..0ff0c20d7d 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -743,6 +743,10 @@ async function readPgForeignKeys(k: RawKysely, schema: string, table: string): P WHERE con.contype = 'f' AND n.nspname = ${schema} AND t.relname = ${table} + -- Same-schema FKs only: FkDescriptor carries no referenced schema and the emitter + -- assumes the holder's, so a cross-schema FK would read as one to a same-named + -- table here. (The information_schema join this replaced excluded them too.) + AND rt.relnamespace = t.relnamespace ORDER BY con.conname, key.ord `.execute(k); } catch { diff --git a/server/typescript/packages/migrate-ts/src/schema-conventions.ts b/server/typescript/packages/migrate-ts/src/schema-conventions.ts index 151210fc83..c711f8597d 100644 --- a/server/typescript/packages/migrate-ts/src/schema-conventions.ts +++ b/server/typescript/packages/migrate-ts/src/schema-conventions.ts @@ -11,13 +11,14 @@ * `identity.reference`, and an index node's own name. * * Selected with `migrate.conventions` in `.metaobjects/config.json` (a preset name), or - * supplied as an object by the project (`migrate.conventions` in `metaobjects.config.ts`). + * supplied as an object by the project (`schemaConventions` in `metaobjects.config.ts`). * `default` is what migrate has always emitted, so a project that sets nothing sees no * change; `efcore` reproduces EF Core's conventions, for a database first built by EF * Core migrations. */ -import { UnknownSchemaConventionsError } from "./errors.js"; +import { InvalidSchemaConventionsError, UnknownSchemaConventionsError } from "./errors.js"; +import type { IndexDescriptor } from "./types.js"; /** A key on one table: the table's database name and the key's columns, in key order. */ export interface KeyContext { @@ -31,10 +32,13 @@ export interface ForeignKeyContext extends KeyContext { refColumns: readonly string[]; } -/** What a table already has that may already serve as a foreign key's index. */ -export interface ExistingKeys { +/** A table as the FK-index decision sees it: its keys, its declared indexes, its foreign keys. */ +export interface TableKeys { + table: string; primaryKey: readonly string[]; + /** The indexes the model declares (unique keys included); the conventions add to these. */ indexes: readonly { columns: readonly string[]; where?: string; expr?: string }[]; + foreignKeys: readonly ForeignKeyContext[]; } export interface SchemaConventions { @@ -43,8 +47,8 @@ export interface SchemaConventions { primaryKeyName(key: KeyContext): string; /** Used when the identity.reference declares no `@constraintName`. */ foreignKeyName(fk: ForeignKeyContext): string; - /** The index a foreign key gets, or undefined for none. */ - foreignKeyIndex(fk: ForeignKeyContext, existing: ExistingKeys): { name: string } | undefined; + /** The indexes the conventions add for a table's foreign keys (none, for most conventions). */ + foreignKeyIndexes(table: TableKeys): { name: string; columns: string[] }[]; /** How a unique key (`identity.secondary`) is created. A partial or expression key is always an index. */ uniqueKeyKind(key: KeyContext & { referencedByForeignKey: boolean }): "index" | "constraint"; } @@ -66,7 +70,7 @@ export const defaultConventions: SchemaConventions = { id: "default", primaryKeyName: ({ table }) => `${table}_pkey`, foreignKeyName: ({ table, columns }) => `${table}_${columns[0]}_fk`, - foreignKeyIndex: () => undefined, + foreignKeyIndexes: () => [], uniqueKeyKind: () => "index", }; @@ -74,11 +78,23 @@ export const efcoreConventions: SchemaConventions = { id: "efcore", primaryKeyName: ({ table }) => efTruncate(`PK_${table}`), foreignKeyName: ({ table, columns, refTable }) => efTruncate(`FK_${table}_${refTable}_${columns.join("_")}`), - // EF Core indexes every foreign key unless a key or index already starts with its columns. - foreignKeyIndex: (fk, existing) => { - if (startsWith(existing.primaryKey, fk.columns)) return undefined; - const covered = existing.indexes.some((ix) => ix.where === undefined && ix.expr === undefined && startsWith(ix.columns, fk.columns)); - return covered ? undefined : { name: efTruncate(`IX_${fk.table}_${fk.columns.join("_")}`) }; + // EF Core's ForeignKeyIndexConvention: every foreign key gets an index unless a key or + // another index already starts with its columns. Its AreIndexedBy compares property lists + // only — a filter is a relational annotation the convention never sees, so a partial index + // covers — and an index added later removes a convention index it covers, so the result + // does not depend on the order the foreign keys are declared in. + foreignKeyIndexes: (t) => { + const candidates: string[][] = []; + for (const fk of t.foreignKeys) { + const columns = [...fk.columns]; + if (startsWith(t.primaryKey, columns)) continue; + if (t.indexes.some((ix) => ix.expr === undefined && startsWith(ix.columns, columns))) continue; + if (candidates.some((c) => c.length === columns.length && startsWith(c, columns))) continue; + candidates.push(columns); + } + return candidates + .filter((c) => !candidates.some((o) => o.length > c.length && startsWith(o, c))) + .map((columns) => ({ name: efTruncate(`IX_${t.table}_${columns.join("_")}`), columns })); }, // An alternate key (one an FK references) is a UNIQUE constraint; any other unique key is an index. uniqueKeyKind: ({ referencedByForeignKey }) => (referencedByForeignKey ? "constraint" : "index"), @@ -95,8 +111,20 @@ export const SCHEMA_CONVENTION_PRESETS = Object.keys(PRESETS) as readonly string /** A preset by name, a project-supplied object as itself, and nothing as `default`. */ export function resolveSchemaConventions(selected: string | SchemaConventions | undefined): SchemaConventions { if (selected === undefined) return defaultConventions; - if (typeof selected !== "string") return selected; + if (typeof selected !== "string") { + const members = ["primaryKeyName", "foreignKeyName", "foreignKeyIndexes", "uniqueKeyKind"] as const; + const missing = members.filter((m) => typeof (selected as unknown as Record)[m] !== "function"); + if (missing.length > 0) throw new InvalidSchemaConventionsError(String((selected as { id?: unknown }).id ?? "(no id)"), missing); + return selected; + } const preset = PRESETS[selected]; if (preset === undefined) throw new UnknownSchemaConventionsError(selected, SCHEMA_CONVENTION_PRESETS); return preset; } + +/** A unique key a `UNIQUE` constraint can express: plain ascending btree columns, no predicate. */ +export function canBeUniqueConstraint(ix: IndexDescriptor): boolean { + return ix.unique && ix.where === undefined && ix.expr === undefined + && (ix.using === undefined || ix.using === "btree") + && (ix.orders === undefined || ix.orders.every((o) => o === "asc")); +} diff --git a/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts b/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts index bfd50c20a7..a62dbd27a0 100644 --- a/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/postgres-composite-fk-introspect.test.ts @@ -63,4 +63,25 @@ d("postgres composite FK introspection (real PG)", () => { await k.destroy(); } }); + + test("an FK into another schema is not read (FkDescriptor has no referenced schema; as before)", async () => { + const k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: PG_URL }) }) }); + const a = "xsa_" + Math.random().toString(36).slice(2, 8); + const b = "xsb_" + Math.random().toString(36).slice(2, 8); + try { + await sql.raw(`CREATE SCHEMA ${a}; CREATE SCHEMA ${b}`).execute(k); + await sql.raw(`CREATE TABLE ${b}.users ( id INTEGER PRIMARY KEY )`).execute(k); + await sql.raw(`CREATE TABLE ${a}.users ( id INTEGER PRIMARY KEY )`).execute(k); + await sql.raw(`CREATE TABLE ${a}.profiles ( id INTEGER PRIMARY KEY, user_id INTEGER REFERENCES ${b}.users (id), local_id INTEGER REFERENCES ${a}.users (id) )`).execute(k); + + const snap = await introspectPostgres(k); + const profiles = snap.tables.find((x) => x.name === "profiles" && x.schema === a)!; + + // Only the same-schema FK: the cross-schema one would read as an FK to a.users. + expect(profiles.foreignKeys.map((f) => f.columns)).toEqual([["local_id"]]); + } finally { + await sql.raw(`DROP SCHEMA IF EXISTS ${a} CASCADE; DROP SCHEMA IF EXISTS ${b} CASCADE`).execute(k); + await k.destroy(); + } + }); }); diff --git a/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts index e57bb29b94..077c76f863 100644 --- a/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/expected-schema-conventions.test.ts @@ -129,3 +129,46 @@ describe("the conventions the project-aware load put on the root", () => { expect(() => buildExpectedSchema(root)).toThrow(/migrate\.conventions "hibernate".*default, efcore/); }); }); + +describe("efcore unique keys that must stay indexes", () => { + const doc = (secondary: Record, extra: unknown[] = []) => ({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Region", children: [ + { "source.rdb": { "@table": "Regions", "@schema": "a" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.string": { name: "code", "@column": "Code" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "identity.secondary": { name: "AK_Regions_Code", "@fields": ["code"], ...secondary } }, + ] } }, + { "object.entity": { name: "Store", children: [ + { "source.rdb": { "@table": "Stores", "@schema": "a" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.string": { name: "regionCode", "@column": "RegionCode" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "identity.reference": { name: "region", "@fields": ["regionCode"], "@references": "Region.code" } }, + ] } }, + ...extra, + ] } }); + const kind = async (d: unknown, schema: string) => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(d))]); + expect(errors).toHaveLength(0); + const t = buildExpectedSchema(root, { conventions: efcoreConventions }).tables.find((x) => x.name === "Regions" && x.schema === schema)!; + return t.indexes.find((i) => i.name.startsWith("AK_"))!.constraint ?? "index"; + }; + + test("a DESC key or a non-btree method stays an index (a UNIQUE constraint carries neither)", async () => { + expect(await kind(doc({}), "a")).toBe("unique"); + expect(await kind(doc({ "@orders": ["desc"] }), "a")).toBe("index"); + expect(await kind(doc({ "@using": "hash" }), "a")).toBe("index"); + }); + + test("an FK in one schema does not make a same-named key in another schema a constraint", async () => { + const other = { "object.entity": { name: "OtherRegion", children: [ + { "source.rdb": { "@table": "Regions", "@schema": "b" } }, + { "field.long": { name: "id", "@column": "Id" } }, + { "field.string": { name: "code", "@column": "Code" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "identity.secondary": { name: "AK_OtherRegions_Code", "@fields": ["code"] } }, + ] } }; + expect(await kind(doc({}, [other]), "b")).toBe("index"); + }); +}); diff --git a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts index 06eb9a1aa4..8c40736d37 100644 --- a/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/schema-conventions.test.ts @@ -20,7 +20,8 @@ describe("efcore conventions", () => { expect(efcoreConventions.foreignKeyName(fk)).toBe("FK_OrderLines_Orders_OrderId"); expect(efcoreConventions.foreignKeyName({ ...fk, columns: ["OrderId", "Region"], refColumns: ["Id", "Region"] })) .toBe("FK_OrderLines_Orders_OrderId_Region"); - expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [] })).toEqual({ name: "IX_OrderLines_OrderId" }); + expect(efcoreConventions.foreignKeyIndexes({ table: "OrderLines", primaryKey: ["Id"], indexes: [], foreignKeys: [fk] })) + .toEqual([{ name: "IX_OrderLines_OrderId", columns: ["OrderId"] }]); }); test("a name over 63 characters is cut to 62 and marked with ~, as EF Core does", () => { @@ -33,14 +34,30 @@ describe("efcore conventions", () => { }); test("no FK index when the primary key or an existing index already starts with the FK's columns", () => { - expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["OrderId", "LineNo"], indexes: [] })).toBeUndefined(); - expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [{ columns: ["OrderId", "Sku"] }] })).toBeUndefined(); + const ix = (primaryKey: string[], indexes: { columns: string[]; where?: string; expr?: string }[]) => + efcoreConventions.foreignKeyIndexes({ table: "OrderLines", primaryKey, indexes, foreignKeys: [fk] }).map((i) => i.name); + + expect(ix(["OrderId", "LineNo"], [])).toEqual([]); + expect(ix(["Id"], [{ columns: ["OrderId", "Sku"] }])).toEqual([]); // an index that merely CONTAINS the columns later does not cover them - expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [{ columns: ["Sku", "OrderId"] }] })) - .toEqual({ name: "IX_OrderLines_OrderId" }); - // a partial or expression index does not cover them either - expect(efcoreConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [{ columns: ["OrderId"], where: "x" }] })) - .toEqual({ name: "IX_OrderLines_OrderId" }); + expect(ix(["Id"], [{ columns: ["Sku", "OrderId"] }])).toEqual(["IX_OrderLines_OrderId"]); + // a PARTIAL index covers them: EF Core's AreIndexedBy compares properties, and a filter is + // a relational annotation that convention never sees + expect(ix(["Id"], [{ columns: ["OrderId"], where: "x" }])).toEqual([]); + // an expression index has no columns to lead with + expect(ix(["Id"], [{ columns: [], expr: "lower(x)" }])).toEqual(["IX_OrderLines_OrderId"]); + }); + + test("FK indexes do not depend on FK order: one an FK index covers is dropped, as EF Core does", () => { + const a = { table: "hs", columns: ["a"], refTable: "x", refColumns: ["id"] }; + const ab = { table: "hs", columns: ["a", "b"], refTable: "y", refColumns: ["id", "k"] }; + const names = (foreignKeys: typeof a[]) => + efcoreConventions.foreignKeyIndexes({ table: "hs", primaryKey: ["id"], indexes: [], foreignKeys }).map((i) => i.name); + + expect(names([a, ab])).toEqual(["IX_hs_a_b"]); + expect(names([ab, a])).toEqual(["IX_hs_a_b"]); + // two FKs on the same columns get one index + expect(names([a, { ...a, refTable: "z" }])).toEqual(["IX_hs_a"]); }); test("a unique key an FK references is a constraint; any other is an index", () => { @@ -53,7 +70,7 @@ describe("default conventions (what migrate has always emitted)", () => { test("{table}_pkey, {table}_{firstColumn}_fk, no FK index, unique keys are indexes", () => { expect(defaultConventions.primaryKeyName({ table: "orders", columns: ["id"] })).toBe("orders_pkey"); expect(defaultConventions.foreignKeyName({ ...fk, table: "order_lines", columns: ["order_id", "region"] })).toBe("order_lines_order_id_fk"); - expect(defaultConventions.foreignKeyIndex(fk, { primaryKey: ["Id"], indexes: [] })).toBeUndefined(); + expect(defaultConventions.foreignKeyIndexes({ table: "OrderLines", primaryKey: ["Id"], indexes: [], foreignKeys: [fk] })).toEqual([]); expect(defaultConventions.uniqueKeyKind({ table: "orders", columns: ["code"], referencedByForeignKey: true })).toBe("index"); }); }); @@ -70,4 +87,10 @@ describe("resolveSchemaConventions", () => { expect(() => resolveSchemaConventions("hibernate")).toThrow(/migrate\.conventions "hibernate".*default, efcore/); expect(SCHEMA_CONVENTION_PRESETS).toEqual(["default", "efcore"]); }); + + test("a supplied object missing a member is refused by name (e.g. written for another version)", () => { + const partial = { id: "acme", primaryKeyName: () => "pk" } as unknown as Parameters[0]; + expect(() => resolveSchemaConventions(partial)) + .toThrow(/schema conventions "acme" are missing foreignKeyName, foreignKeyIndexes, uniqueKeyKind/); + }); }); From bdbebea52072235a83eb1e906d415d8d43662a67 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 20:04:14 -0500 Subject: [PATCH 010/267] feat(naming): a PascalCase column rule, in every port "naming": { "columns": "PascalCase" } upper-cases a field name's first letter and changes nothing else (createdAt -> CreatedAt, requestURL -> RequestURL): the column EF Core creates for a property. A camelCase model over an EF-built schema then needs @column only where the database spells a name differently. A column rule only, like kebab-case: literal tables already keep a PascalCase object name. The shared naming fixture gains the case and the table-rule refusal; C# and Python verify probe it last. Three tests used "PascalCase" as their example of an unknown rule and now use "camelCase". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ docs/features/field-types.md | 3 ++- docs/features/migrations/physical-naming.md | 8 +++++++- .../naming-conformance/physical-names/cases.json | 13 ++++++++++++- server/csharp/MetaObjects.Codegen/CSharpNaming.cs | 1 + server/csharp/MetaObjects.Codegen/CodegenCli.cs | 5 +++-- server/csharp/MetaObjects/Config/NeutralConfig.cs | 3 ++- server/csharp/MetaObjects/Meta/PhysicalNaming.cs | 10 ++++++++++ .../metaobjects/generator/kotlin/KotlinGenUtil.kt | 1 + .../com/metaobjects/database/ColumnNaming.java | 15 ++++++++++++++- .../com/metaobjects/database/PhysicalNaming.java | 13 +++++++------ .../metaobjects/database/ColumnNamingTest.java | 2 +- server/python/src/metaobjects/cli.py | 2 +- server/python/src/metaobjects/naming.py | 14 +++++++++++++- server/python/tests/codegen/test_m2m_codegen.py | 2 +- .../tests/unit/test_column_naming_strategy.py | 2 +- server/typescript/packages/metadata/src/index.ts | 2 +- server/typescript/packages/metadata/src/naming.ts | 15 +++++++++++++-- .../ADR-0058-one-physical-naming-setting.md | 4 +++- 19 files changed, 99 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 551cd3e917..1daa5c08bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,12 @@ here.** and the `wire` setting, and a project on any port runs them through the Node `meta` CLI. They are reference helpers: opt-in, listed by `meta gen --list`, ejectable and gated by `verify --codegen` (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. +- **A `PascalCase` column rule.** `"naming": { "columns": "PascalCase" }` in + `.metaobjects/config.json` upper-cases a field name's first letter and changes nothing else + (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`), in every port: the column names EF Core + creates, so a camelCase model over an EF-built schema needs `@column` only where the database + spells a name differently. A column rule only; `literal` tables keep a PascalCase object name. + See `docs/features/migrations/physical-naming.md`. - **Schema conventions for the database objects no code addresses.** `migrate.conventions` in `.metaobjects/config.json` picks how `meta migrate` names primary-key and foreign-key constraints, whether each foreign key gets an index, and whether a unique key an FK references diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 6623784a89..381b8104d8 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -111,7 +111,8 @@ A field has **two names**: the one your code calls it (`createdAt`, the metadata database calls it. `@column` sets the second. It never changes the first. With no `@column`, the physical name comes from the project's **column rule**: -`snake_case` (the default), `literal` (the field name verbatim) or `kebab-case`. That +`snake_case` (the default), `literal` (the field name verbatim), `kebab-case` or +`PascalCase` (the first letter upper-cased, the rest verbatim: EF Core's names). That is CONFIG, not metadata, on purpose: the same model has to be able to drive a snake_case Postgres schema and a literal-column one. It is ONE setting for the whole project, `naming` in `.metaobjects/config.json` (ADR-0058): diff --git a/docs/features/migrations/physical-naming.md b/docs/features/migrations/physical-naming.md index dbfbcd34ac..dbe05e5f17 100644 --- a/docs/features/migrations/physical-naming.md +++ b/docs/features/migrations/physical-naming.md @@ -25,11 +25,17 @@ every runtime `ObjectManager` and `verify` read it, so they always produce the s | Key | Values | Applies to | Default | |---|---|---|---| -| `columns` | `snake_case`, `literal`, `kebab-case` | a field with no `@column` | `snake_case` | +| `columns` | `snake_case`, `literal`, `kebab-case`, `PascalCase` | a field with no `@column` | `snake_case` | | `tables` | `snake_case`, `literal` | a source with no `@table`/`@view`/`@proc`/`@function`: its `name`, else the object's name made plural | `snake_case` | An unknown key or value fails when the file is read. Index and constraint names are unchanged. +`PascalCase` (added in 1.2.1) upper-cases the field name's first letter and changes nothing +else: `createdAt` becomes `CreatedAt` and `requestURL` becomes `RequestURL`. It is the column +EF Core creates for a property, so a camelCase model over an EF-built schema needs `@column` +only where the database spells a name differently (an acronym the field writes in lower case, +for example). It is a column rule only; `literal` tables already keep a PascalCase object name. + **Upgrade every port of an estate together.** A 1.0.x TypeScript tool refuses the new `naming` key, but a 1.0.x C#, Java or Python tool ignores an unknown top-level key silently and keeps the old column names, so a mixed estate disagrees about the schema without any error. diff --git a/fixtures/naming-conformance/physical-names/cases.json b/fixtures/naming-conformance/physical-names/cases.json index fbc0c77920..0899f839d0 100644 --- a/fixtures/naming-conformance/physical-names/cases.json +++ b/fixtures/naming-conformance/physical-names/cases.json @@ -1,5 +1,5 @@ { - "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read.", + "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `PascalCase` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`): the names EF Core and most C# schemas use.", "cases": [ { "name": "default", @@ -50,11 +50,22 @@ "Person.firstName": "first-name", "Person.lastName": "family_name", "AuditEntry.eventType": "event-type", "Category.displayName": "display-name", "HTTPRequest.requestURL": "request-url" } + }, + { + "name": "PascalCase columns, literal tables", + "naming": { "columns": "PascalCase", "tables": "literal" }, + "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests" }, + "columns": { + "OrderItem.id": "Id", "OrderItem.createdAt": "CreatedAt", "OrderItem.unitPriceCents": "UnitPriceCents", "OrderItem.sku": "SKU_CODE", + "Person.firstName": "FirstName", "Person.lastName": "family_name", + "AuditEntry.eventType": "EventType", "Category.displayName": "DisplayName", "HTTPRequest.requestURL": "RequestURL" + } } ], "invalid": [ { "name": "unknown column rule", "naming": { "columns": "camelCase" } }, { "name": "kebab-case is not a table rule", "naming": { "tables": "kebab-case" } }, + { "name": "PascalCase is not a table rule", "naming": { "tables": "PascalCase" } }, { "name": "unknown key", "naming": { "column": "literal" } }, { "name": "not an object", "naming": "snake_case" } ] diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 29e96e4ed4..67e384982e 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -442,6 +442,7 @@ public static string Column(MetaField field, ColumnNamingStrategy strategy = Col ColumnNamingStrategy.Literal => name, ColumnNamingStrategy.SnakeCase => ToSnakeCase(name), ColumnNamingStrategy.KebabCase => ToSnakeCase(name).Replace('_', '-'), + ColumnNamingStrategy.PascalCase => PhysicalNaming.ToPascalCaseColumn(name), _ => name, }; diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 8bb057b73a..89a3b9b1de 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -482,6 +482,7 @@ private static int Unknown(string cmd) { ColumnNamingStrategy.SnakeCase => "snake_case", ColumnNamingStrategy.KebabCase => "kebab-case", + ColumnNamingStrategy.PascalCase => "PascalCase", _ => "literal", }; @@ -809,12 +810,12 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) /// Every naming other than , in the order verify probes them (the /// Python port probes the same order): the used table rule first, so a different column /// rule alone is tried before a different table rule; within each, the used column rule - /// first, then snake_case, literal, kebab-case. + /// first, then snake_case, literal, kebab-case, PascalCase. /// private static IEnumerable NamingCandidates(PhysicalNaming used) { ColumnNamingStrategy[] columns = - [ColumnNamingStrategy.SnakeCase, ColumnNamingStrategy.Literal, ColumnNamingStrategy.KebabCase]; + [ColumnNamingStrategy.SnakeCase, ColumnNamingStrategy.Literal, ColumnNamingStrategy.KebabCase, ColumnNamingStrategy.PascalCase]; TableNamingRule[] tables = [TableNamingRule.SnakeCase, TableNamingRule.Literal]; foreach (var t in tables.OrderBy(t => t == used.Tables ? 0 : 1)) foreach (var c in columns.OrderBy(c => c == used.Columns ? 0 : 1)) diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index 4ec962d0e3..b776047458 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -251,7 +251,7 @@ private NeutralConfig( case "columns": if (p.Value.ValueKind != JsonValueKind.String || !TryParseColumnNaming(p.Value.GetString()!, out columns)) throw new MetaModelException( - $"{path}: \"naming.columns\" must be one of \"snake_case\", \"literal\", \"kebab-case\"", + $"{path}: \"naming.columns\" must be one of \"snake_case\", \"literal\", \"kebab-case\", \"PascalCase\"", ErrorCode.ERR_BAD_ATTR_VALUE); break; case "tables": @@ -389,6 +389,7 @@ private static bool TryParseColumnNaming(string raw, out ColumnNamingStrategy st case "literal": strategy = ColumnNamingStrategy.Literal; return true; case "snake_case": strategy = ColumnNamingStrategy.SnakeCase; return true; case "kebab-case": strategy = ColumnNamingStrategy.KebabCase; return true; + case "PascalCase": strategy = ColumnNamingStrategy.PascalCase; return true; default: strategy = ColumnNamingStrategy.Literal; return false; } } diff --git a/server/csharp/MetaObjects/Meta/PhysicalNaming.cs b/server/csharp/MetaObjects/Meta/PhysicalNaming.cs index 0844b9eb1a..edca9b870b 100644 --- a/server/csharp/MetaObjects/Meta/PhysicalNaming.cs +++ b/server/csharp/MetaObjects/Meta/PhysicalNaming.cs @@ -23,6 +23,10 @@ public enum ColumnNamingStrategy SnakeCase, /// camelCase / PascalCase → kebab-case. KebabCase, + /// The first letter upper-cased, nothing else changed (requestURL → + /// RequestURL): EF Core's column name for a property, so a camelCase model maps + /// onto an EF-built schema with no @column. + PascalCase, } /// @@ -71,10 +75,16 @@ public static string ResolveColumnName(MetaField field) { ColumnNamingStrategy.SnakeCase => SourceNaming.ToSnakeCase(field.Name), ColumnNamingStrategy.KebabCase => SourceNaming.ToSnakeCase(field.Name).Replace('_', '-'), + ColumnNamingStrategy.PascalCase => ToPascalCaseColumn(field.Name), _ => field.Name, }; } + /// The PascalCase column rule: the first letter upper-cased, the rest + /// verbatim. Not a word split — an acronym keeps the case it was written in. + public static string ToPascalCaseColumn(string name) => + name.Length == 0 ? name : char.ToUpperInvariant(name[0]) + name[1..]; + /// cased by the table rule — no pluralization (the /// caller decides whether to pluralize; see ). public static string ApplyTableNamingRule(string name, TableNamingRule rule) => diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt index 62b74b74fc..42bc4d6fd9 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt @@ -896,6 +896,7 @@ public object KotlinGenUtil { const val COLUMN_NAMING_SNAKE_CASE: String = ColumnNaming.SNAKE_CASE const val COLUMN_NAMING_LITERAL: String = ColumnNaming.LITERAL const val COLUMN_NAMING_KEBAB_CASE: String = ColumnNaming.KEBAB_CASE + const val COLUMN_NAMING_PASCAL_CASE: String = ColumnNaming.PASCAL_CASE const val DEFAULT_COLUMN_NAMING: String = COLUMN_NAMING_SNAKE_CASE /** diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/ColumnNaming.java b/server/java/metadata/src/main/java/com/metaobjects/database/ColumnNaming.java index 0726e5bc07..92c6d076bd 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/ColumnNaming.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/ColumnNaming.java @@ -45,6 +45,12 @@ private ColumnNaming() {} public static final String SNAKE_CASE = "snake_case"; /** camelCase / PascalCase to kebab-case. */ public static final String KEBAB_CASE = "kebab-case"; + /** + * The first letter upper-cased, nothing else changed ({@code requestURL} to + * {@code RequestURL}): EF Core's column name for a property, so a camelCase model maps onto + * an EF-built schema with no {@code @column}. Not a word split. + */ + public static final String PASCAL_CASE = "PascalCase"; /** The project default (ADR-0058) — what {@code meta migrate} has always created. */ public static final String DEFAULT = SNAKE_CASE; @@ -83,9 +89,16 @@ public static String apply(String name, String strategy) { if (LITERAL.equals(strategy)) return name; if (SNAKE_CASE.equals(strategy)) return toSnakeCase(name); if (KEBAB_CASE.equals(strategy)) return toSnakeCase(name).replace('_', '-'); + if (PASCAL_CASE.equals(strategy)) return toPascalCaseColumn(name); throw new IllegalArgumentException( "unknown column-naming strategy '" + strategy + "'; expected one of: " - + LITERAL + ", " + SNAKE_CASE + ", " + KEBAB_CASE); + + LITERAL + ", " + SNAKE_CASE + ", " + KEBAB_CASE + ", " + PASCAL_CASE); + } + + /** The {@link #PASCAL_CASE} rule: the first letter upper-cased, the rest verbatim. */ + public static String toPascalCaseColumn(String name) { + if (name == null || name.isEmpty()) return name; + return Character.toUpperCase(name.charAt(0)) + name.substring(1); } /** diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/PhysicalNaming.java b/server/java/metadata/src/main/java/com/metaobjects/database/PhysicalNaming.java index 87971a3180..6974386f52 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/PhysicalNaming.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/PhysicalNaming.java @@ -46,17 +46,18 @@ private PhysicalNaming(String columns, String tables) { * whole schema to the wrong names and report success. * * @throws MetaDataException on a {@code columns} value outside - * {@link ColumnNaming#SNAKE_CASE}/{@link ColumnNaming#LITERAL}/{@link ColumnNaming#KEBAB_CASE}, - * or a {@code tables} value outside {@link #TABLE_SNAKE_CASE}/{@link #TABLE_LITERAL} - * (kebab-case is a column rule only — not a table rule). + * {@link ColumnNaming#SNAKE_CASE}/{@link ColumnNaming#LITERAL}/{@link ColumnNaming#KEBAB_CASE}/ + * {@link ColumnNaming#PASCAL_CASE}, or a {@code tables} value outside + * {@link #TABLE_SNAKE_CASE}/{@link #TABLE_LITERAL} (kebab-case and PascalCase are column + * rules only — not table rules). */ public static PhysicalNaming of(String columns, String tables) { if (!ColumnNaming.SNAKE_CASE.equals(columns) && !ColumnNaming.LITERAL.equals(columns) - && !ColumnNaming.KEBAB_CASE.equals(columns)) { + && !ColumnNaming.KEBAB_CASE.equals(columns) && !ColumnNaming.PASCAL_CASE.equals(columns)) { throw new MetaDataException( "unknown \"naming.columns\" rule \"" + columns + "\" in .metaobjects/config.json; " + "expected one of: " + ColumnNaming.SNAKE_CASE + ", " + ColumnNaming.LITERAL - + ", " + ColumnNaming.KEBAB_CASE, + + ", " + ColumnNaming.KEBAB_CASE + ", " + ColumnNaming.PASCAL_CASE, ErrorCode.ERR_BAD_ATTR_VALUE); } if (!TABLE_SNAKE_CASE.equals(tables) && !TABLE_LITERAL.equals(tables)) { @@ -68,7 +69,7 @@ public static PhysicalNaming of(String columns, String tables) { return new PhysicalNaming(columns, tables); } - /** The {@code naming.columns} rule — snake_case / literal / kebab-case. */ + /** The {@code naming.columns} rule — snake_case / literal / kebab-case / PascalCase. */ public String columns() { return columns; } diff --git a/server/java/metadata/src/test/java/com/metaobjects/database/ColumnNamingTest.java b/server/java/metadata/src/test/java/com/metaobjects/database/ColumnNamingTest.java index 49807ae50d..395e1d9866 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/database/ColumnNamingTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/database/ColumnNamingTest.java @@ -68,7 +68,7 @@ public void snakeCaseMatchesTheCrossPortAlgorithm() { public void anUnknownStrategyIsRefusedNotSilentlyDefaulted() { // A typo would otherwise bind a whole schema to the wrong columns and succeed. IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, - () -> ColumnNaming.apply("createdAt", "PascalCase")); + () -> ColumnNaming.apply("createdAt", "camelCase")); org.junit.Assert.assertTrue(ex.getMessage(), ex.getMessage().contains("snake_case")); } } diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 06817f3b69..f28d2d9ea8 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -2277,7 +2277,7 @@ def naming_candidates(used: NamingRules) -> list[NamingRules]: """Every naming other than ``used``, in the order ``verify --codegen`` probes them (the C# port probes the same order): the used table rule first, so a different column rule alone is tried before a different table rule; within each, the used column rule first, then - snake_case, literal, kebab-case.""" + snake_case, literal, kebab-case, PascalCase.""" tables = sorted(TABLE_NAMING_RULES, key=lambda t: t != used.tables) columns = sorted(COLUMN_NAMING_STRATEGIES, key=lambda c: c != used.columns) return [ diff --git a/server/python/src/metaobjects/naming.py b/server/python/src/metaobjects/naming.py index 3ff359909b..e77683e636 100644 --- a/server/python/src/metaobjects/naming.py +++ b/server/python/src/metaobjects/naming.py @@ -37,18 +37,23 @@ COLUMN_NAMING_SNAKE_CASE = "snake_case" COLUMN_NAMING_LITERAL = "literal" COLUMN_NAMING_KEBAB_CASE = "kebab-case" +#: The first letter upper-cased, nothing else changed (``requestURL`` → ``RequestURL``): +#: EF Core's column name for a property, so a camelCase model maps onto an EF-built schema +#: with no ``@column``. Not a word split. +COLUMN_NAMING_PASCAL_CASE = "PascalCase" COLUMN_NAMING_STRATEGIES = ( COLUMN_NAMING_SNAKE_CASE, COLUMN_NAMING_LITERAL, COLUMN_NAMING_KEBAB_CASE, + COLUMN_NAMING_PASCAL_CASE, ) #: ADR-0058 — the project default, in every port: what ``meta migrate`` has always #: created. FLIPPED in 1.1.0 (was ``literal`` in this port only). DEFAULT_COLUMN_NAMING = COLUMN_NAMING_SNAKE_CASE -#: ADR-0058 — ``tables`` accepts only these two: no ``kebab-case`` table rule. +#: ADR-0058 — ``tables`` accepts only these two: no ``kebab-case`` or ``PascalCase`` table rule. TABLE_NAMING_SNAKE_CASE = "snake_case" TABLE_NAMING_LITERAL = "literal" @@ -132,6 +137,11 @@ def to_snake_case(name: str) -> str: return "".join(out) +def to_pascal_case_column(name: str) -> str: + """The ``PascalCase`` column rule: the first letter upper-cased, the rest verbatim.""" + return name[:1].upper() + name[1:] + + def apply_column_naming_strategy(name: str, strategy: str = DEFAULT_COLUMN_NAMING) -> str: """Apply a strategy to a bare name. @@ -144,6 +154,8 @@ def apply_column_naming_strategy(name: str, strategy: str = DEFAULT_COLUMN_NAMIN return to_snake_case(name) if strategy == COLUMN_NAMING_KEBAB_CASE: return to_snake_case(name).replace("_", "-") + if strategy == COLUMN_NAMING_PASCAL_CASE: + return to_pascal_case_column(name) raise ValueError( f"unknown column-naming strategy {strategy!r}; " f"expected one of: {', '.join(COLUMN_NAMING_STRATEGIES)}" diff --git a/server/python/tests/codegen/test_m2m_codegen.py b/server/python/tests/codegen/test_m2m_codegen.py index 946b9a4637..7082cc4da5 100644 --- a/server/python/tests/codegen/test_m2m_codegen.py +++ b/server/python/tests/codegen/test_m2m_codegen.py @@ -266,7 +266,7 @@ def test_an_unknown_strategy_is_refused_at_the_descriptor_too() -> None: # Fail loudly rather than fall back: a typo would otherwise bind junction SQL to # columns that do not exist and report success. with pytest.raises(ValueError, match="snake_case"): - resolve_m2m_descriptors(_ENTITIES["Post"], _INDEX, column_naming="PascalCase") + resolve_m2m_descriptors(_ENTITIES["Post"], _INDEX, column_naming="camelCase") # --------------------------------------------------------------------------- diff --git a/server/python/tests/unit/test_column_naming_strategy.py b/server/python/tests/unit/test_column_naming_strategy.py index 63bb83dafd..92d7acbb63 100644 --- a/server/python/tests/unit/test_column_naming_strategy.py +++ b/server/python/tests/unit/test_column_naming_strategy.py @@ -78,7 +78,7 @@ def test_an_unknown_strategy_is_refused_not_silently_defaulted() -> None: # A typo'd strategy would otherwise bind an entire schema to the wrong columns and # report success. with pytest.raises(ValueError, match="snake_case"): - apply_column_naming_strategy("createdAt", "PascalCase") + apply_column_naming_strategy("createdAt", "camelCase") # WHERE THE STRATEGY ACTUALLY REACHES, in this port. diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 6ddc3032ef..2a719f52c6 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -368,7 +368,7 @@ export { // Naming — hoisted from runtime-ts in v0.2.3 so multiple consumers (runtime-ts, migrate-ts, codegen-ts) // share identical name resolution. See spec §4.1. export { - toSnakeCase, toKebabCase, pluralize, pluralizeTableNameLegacy, + toSnakeCase, toKebabCase, toPascalCaseColumn, pluralize, pluralizeTableNameLegacy, applyColumnNamingStrategy, DEFAULT_COLUMN_NAMING_STRATEGY, COLUMN_NAMING_STRATEGIES, TABLE_NAMING_RULES, DEFAULT_PHYSICAL_NAMING, physicalNamingOf, applyTableNamingRule, PHYSICAL_NAMING_MIGRATION_GUIDE, PHYSICAL_NAMING_MIGRATION_GUIDE_PATH, physicalNamingRemovedMessage, diff --git a/server/typescript/packages/metadata/src/naming.ts b/server/typescript/packages/metadata/src/naming.ts index 794335465f..cb27a936b2 100644 --- a/server/typescript/packages/metadata/src/naming.ts +++ b/server/typescript/packages/metadata/src/naming.ts @@ -53,6 +53,16 @@ export function toKebabCase(s: string): string { return toSnakeCase(s).replace(/_/g, "-"); } +/** + * The `PascalCase` column rule: the first letter upper-cased, nothing else changed + * (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`). Not a word split: an + * acronym keeps the case it was written in, the way EF Core names a column after its + * property, so a camelCase model maps onto an EF-built schema with no `@column`. + */ +export function toPascalCaseColumn(s: string): string { + return s.charAt(0).toUpperCase() + s.slice(1); +} + /** * How a field with no `@column` becomes a column name. One project setting, * `naming.columns` in `.metaobjects/config.json`, read by every port (ADR-0058): the @@ -60,10 +70,10 @@ export function toKebabCase(s: string): string { * and verify resolve the same name. Not a metadata attr: `@column` is the per-field * override, this is the rule for the rest. */ -export type ColumnNamingStrategy = "snake_case" | "literal" | "kebab-case"; +export type ColumnNamingStrategy = "snake_case" | "literal" | "kebab-case" | "PascalCase"; /** Every column-naming rule, in the order the conformance corpus lists them. */ -export const COLUMN_NAMING_STRATEGIES: readonly ColumnNamingStrategy[] = ["snake_case", "literal", "kebab-case"]; +export const COLUMN_NAMING_STRATEGIES: readonly ColumnNamingStrategy[] = ["snake_case", "literal", "kebab-case", "PascalCase"]; /** The default in EVERY port: what `meta migrate` has always created. */ export const DEFAULT_COLUMN_NAMING_STRATEGY: ColumnNamingStrategy = "snake_case"; @@ -134,6 +144,7 @@ export function applyColumnNamingStrategy(name: string, strategy: ColumnNamingSt case "literal": return name; case "kebab-case": return toKebabCase(name); case "snake_case": return toSnakeCase(name); + case "PascalCase": return toPascalCaseColumn(name); } } diff --git a/spec/decisions/ADR-0058-one-physical-naming-setting.md b/spec/decisions/ADR-0058-one-physical-naming-setting.md index fdae02d7fc..afe4055db0 100644 --- a/spec/decisions/ADR-0058-one-physical-naming-setting.md +++ b/spec/decisions/ADR-0058-one-physical-naming-setting.md @@ -42,7 +42,9 @@ every port already reads for `sources`, `dependencies` and `libraries`: { "schema_version": 1, "naming": { "columns": "snake_case", "tables": "snake_case" } } ``` -- `columns`: `snake_case` | `literal` | `kebab-case`. Applies to a field with no `@column`. +- `columns`: `snake_case` | `literal` | `kebab-case` | `PascalCase`. Applies to a field with no + `@column`. (`PascalCase` was added in 1.2.1: the first letter upper-cased, the rest verbatim. + It is a column rule only, like `kebab-case`.) - `tables`: `snake_case` | `literal`. Applies to a source with no physical-name attribute: its structural `name` is cased by the rule; with no name either, the owning object's name is cased by the rule and then pluralized by the frozen legacy pluralizer, under every rule. From 55dcc71b0b2e88cc3e92c56a2274397c893ca84a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 20:54:46 -0500 Subject: [PATCH 011/267] chore(release): added vocabulary moves no metamodel version The metamodel-version gate demanded a minor metamodelVersion bump for any additive change: a new type, subtype, optional attribute or enum member. Every document that loaded still loads, identically, so nothing an adopter relies on changed. Additive changes now require no bump; the package's patch release carries them and the CHANGELOG names them. The number moves only for a breaking change, as before. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ docs/RELEASING.md | 2 +- scripts/check-metamodel-version.mjs | 8 ++++++-- scripts/test-metamodel-version.mjs | 10 ++++++---- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1daa5c08bd..0f64216da3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,11 @@ here.** ### Changed +- **Added vocabulary no longer moves `metamodelVersion`.** The metamodel spec version now moves + only when metadata that loaded may stop loading or change meaning. A new type, subtype, + optional attribute or enum member ships in the package's patch release, and its CHANGELOG + entry names it. `scripts/check-metamodel-version.mjs` and `docs/RELEASING.md` say so. + - **`meta migrate` refuses a foreign key that references columns the target does not hold unique.** Behaviour change: an `identity.reference` whose dotted `@references` names target fields that are not the target's primary key, a plain `identity.secondary` (no `@where`, no `@expr`) or a single diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 4a8f6df227..4f98446a93 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -304,7 +304,7 @@ requires. Same shape as `buf breaking --against '.git#tag=…'` / `oasdiff`. | Change | Required move | |---|---| | a type/subtype removed; an attr removed; an attr made required, retyped or re-arrayed; an enum member removed or an open attr closed; a child rule removed, its `min` raised or its `max` lowered; a default subtype changed | **major** (pre-1.0: minor — see below) | -| a type/subtype added; an optional attr added; an enum member added; a child rule added or relaxed; a default subtype added | **minor** | +| a type/subtype added; an optional attr added; an enum member added; a child rule added or relaxed; a default subtype added | **none** — every document that loaded still loads, identically. The package release carries it (a PATCH unless it is also a software-surface change), and the CHANGELOG names what was added | | prose only (`description` / `rules` / `whenToUse`) | none — but read the warning | **Pre-1.0 a breaking change moves the MINOR**, for the same reason the package line diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs index fb7844cdd8..8ec802fc90 100755 --- a/scripts/check-metamodel-version.mjs +++ b/scripts/check-metamodel-version.mjs @@ -117,7 +117,11 @@ const isPre1 = (v) => v.major === 0; */ export function requiredBump(severity, base, { correction = false } = {}) { if (severity === "none") return "none"; - if (severity === "additive") return "minor"; + // ADDITIVE moves no metamodel number. Every document that loaded still loads, and means + // the same, so nothing an adopter relies on changed: the package's patch release carries + // the new vocabulary and its CHANGELOG entry names it. The number moves only when + // existing metadata may stop loading or change meaning. + if (severity === "additive") return "none"; if (correction) return "minor"; // breaking, but a correction — never a metamodel major return isPre1(base) ? "minor" : "major"; // breaking } @@ -139,7 +143,7 @@ export function satisfies(bump, base, cur) { // Classification. // // BREAKING — metadata that used to load may now fail, or mean something else. -// ADDITIVE — every previously-valid document still loads, identically. +// ADDITIVE — every previously-valid document still loads, identically. Requires no bump. // PROSE — human-readable only; the classifier declines to guess (see the header). // --------------------------------------------------------------------------- diff --git a/scripts/test-metamodel-version.mjs b/scripts/test-metamodel-version.mjs index 19190074cd..064ab53105 100755 --- a/scripts/test-metamodel-version.mjs +++ b/scripts/test-metamodel-version.mjs @@ -275,8 +275,10 @@ const v = (s) => parseVersion(s, "test"); const bump = (sev, base) => requiredBump(sev, v(base)); if (bump("none", "1.0") !== "none") bad("no change requires no bump"); else ok("no change requires no bump"); -if (bump("additive", "1.0") !== "minor") bad("additive requires a minor"); -else ok("additive requires a minor"); +// Additive vocabulary moves no metamodel number: every document that loaded still loads, +// identically, so the package's patch release carries it and the CHANGELOG names it. +if (bump("additive", "1.0") !== "none") bad("additive requires no bump"); +else ok("additive requires no bump"); if (bump("breaking", "1.0") !== "major") bad("post-1.0 breaking requires a major"); else ok("post-1.0 breaking requires a major"); // Pre-1.0 the major carries no promise, so a break moves the minor — the same rule the @@ -305,8 +307,8 @@ else ok("pre-1.0 the correction flag changes nothing"); // It cannot upgrade a lesser severity into a bump it did not earn. if (corr("none", "1.0") !== "none") bad("a correction over `none` is still none"); else ok("a correction over `none` is still none"); -if (corr("additive", "1.0") !== "minor") bad("a correction over `additive` is still a minor"); -else ok("a correction over `additive` is still a minor"); +if (corr("additive", "1.0") !== "none") bad("a correction over `additive` is still none"); +else ok("a correction over `additive` is still none"); const sat = (b, base, cur) => satisfies(b, v(base), v(cur)); if (sat("minor", "1.0", "1.0")) bad("an unmoved version must NOT satisfy a minor"); From a1cb206970873e7e99704e18d19c21bacb5df6c0 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 21:42:09 -0500 Subject: [PATCH 012/267] feat(naming): @flattenedColumnPrefix, and flattened columns named in core A flattened value object's member columns were named by each consumer that needed them (meta migrate, the Prisma schema, the C# EF mapping, the Kotlin Exposed tables), each spelling "_" itself. Core naming now owns it in every port: TS resolveFlattenedColumnPrefix / resolveFlattenedColumnName C# PhysicalNaming.ResolveFlattenedColumnPrefix / ...ColumnName JVM ColumnNaming.resolveFlattenedPrefix / resolveFlattened Python resolve_flattened_column_prefix / resolve_flattened_column_name and every consumer calls it. Each takes an optional column rule, so verify's probe of an alternate rule names these columns as it names every other. @flattenedColumnPrefix on the embedding field.object replaces the default prefix verbatim ("" keeps the members' own columns). It is on the embedding field because one value object embedded twice needs two prefixes. Set on a field whose @storage is not "flattened", it is refused at load: ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE. The shared naming fixture embeds one value object four ways (default, @column, "" and "g_") under every column rule; two conformance fixtures pin the refusal (explicit jsonb, and no storage set). The Mustache corpus test skips the flattened keys: dbColumnName takes one field. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 9 +++ .../skills/metaobjects-authoring/SKILL.md | 4 +- .../references/physical-names.md | 8 ++- docs/CONFORMANCE.md | 6 +- docs/features/field-types.md | 24 +++++++- .../skills/metaobjects-authoring/SKILL.md | 4 +- .../references/physical-names.md | 8 ++- .../skills/metaobjects-authoring/SKILL.md | 4 +- .../references/physical-names.md | 8 ++- .../skills/metaobjects-authoring/SKILL.md | 4 +- .../references/physical-names.md | 8 ++- .../skills/metaobjects-authoring/SKILL.md | 4 +- .../references/physical-names.md | 8 ++- .../skills/metaobjects-authoring/SKILL.md | 4 +- .../references/physical-names.md | 8 ++- fixtures/conformance/ERROR-CODES.json | 1 + .../expected-errors.json | 15 +++++ .../input/meta.storage.json | 57 ++++++++++++++++++ .../providers.json | 1 + .../expected-errors.json | 15 +++++ .../input/meta.storage.json | 58 +++++++++++++++++++ .../providers.json | 1 + fixtures/metamodel-docs/expected/providers.md | 2 +- .../metamodel-docs/expected/types/field.md | 1 + .../physical-names/cases.json | 46 ++++++++++----- .../physical-names/meta.naming.json | 24 ++++++++ .../expected-registry.json | 7 +++ scripts/check-doc-examples.ts | 1 + .../NamingConformanceTests.cs | 19 +++++- .../ObjectFieldCodegenTests.cs | 36 ++++++++++++ .../Generators/DbContextGenerator.cs | 25 ++++---- server/csharp/MetaObjects/Errors.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 16 +++++ server/csharp/MetaObjects/Meta/MetaField.cs | 12 ++++ .../csharp/MetaObjects/Meta/PhysicalNaming.cs | 34 ++++++++++- .../MetaObjects/Persistence/Db/DbConstants.cs | 4 ++ .../MetaObjects/Persistence/Db/DbProvider.cs | 7 +++ .../MetaObjects/Persistence/Db/DbSchema.cs | 11 ++++ .../csharp/MetaObjects/SpecMetamodel/db.json | 1 + .../kotlin/KotlinExposedTableGenerator.kt | 11 ++-- .../kotlin/KotlinExposedTableGeneratorTest.kt | 34 +++++++++++ .../HelperRegistryPhysicalNamingTest.java | 5 ++ .../main/java/com/metaobjects/ErrorCode.java | 3 + .../metaobjects/database/ColumnNaming.java | 36 ++++++++++++ .../database/CoreDBMetaDataProvider.java | 7 +++ .../com/metaobjects/field/ObjectField.java | 7 +++ .../metaobjects/loader/ValidationPhase.java | 24 +++++++- .../util/ErrorMessageConstants.java | 9 +++ .../PhysicalNamingConformanceTest.java | 13 ++++- server/python/src/metaobjects/errors.py | 3 + .../metaobjects/loader/validation_passes.py | 22 +++++++ .../meta/core/field/field_constants.py | 4 ++ .../meta/persistence/db/db_provider.py | 15 +++++ server/python/src/metaobjects/naming.py | 27 +++++++++ .../src/metaobjects/spec_metamodel/db.json | 1 + .../conformance/test_naming_conformance.py | 19 ++++-- .../src/prisma/build-prisma-schema.ts | 4 +- .../test/prisma/prisma-schema.test.ts | 17 ++++++ .../packages/metadata/src/errors.ts | 1 + .../typescript/packages/metadata/src/index.ts | 3 +- .../metadata/src/loader/validation-passes.ts | 15 ++++- .../packages/metadata/src/naming.ts | 35 ++++++++++- .../src/persistence/db/db-constants.ts | 6 ++ .../persistence/db/db-definition.embedded.ts | 8 +++ .../field-definition-completeness.test.ts | 1 + .../migrate-ts/src/expected-schema.ts | 13 +++-- ...pected-schema-field-object-storage.test.ts | 25 ++++++++ .../test/physical-naming-conformance.test.ts | 16 ++++- site-reference/providers.html | 2 +- site-reference/types/field.html | 9 +++ spec/metamodel/db.json | 1 + 72 files changed, 814 insertions(+), 91 deletions(-) create mode 100644 fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/expected-errors.json create mode 100644 fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/input/meta.storage.json create mode 100644 fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/providers.json create mode 100644 fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/expected-errors.json create mode 100644 fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/input/meta.storage.json create mode 100644 fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/providers.json diff --git a/AGENTS.md b/AGENTS.md index 1ce9781050..31c4c7fa80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (421 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (423 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f64216da3..5fb8a9fac3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,15 @@ here.** and the `wire` setting, and a project on any port runs them through the Node `meta` CLI. They are reference helpers: opt-in, listed by `meta gen --list`, ejectable and gated by `verify --codegen` (ADR-0034 Amendment 10). Protobuf is not built. See `docs/features/contract-emitters.md`. +- **`@flattenedColumnPrefix`: name a flattened value object's columns.** On a `field.object` with + `@storage: "flattened"`, it replaces the default prefix (the field's column and `_`) verbatim; + `""` keeps the members' own column names. It sits on the embedding field because one value + object embedded twice needs two prefixes. Flattened column names now come from core naming in + every port (`resolveFlattenedColumnName` in TypeScript, `PhysicalNaming.ResolveFlattenedColumnName` + in C#, `ColumnNaming.resolveFlattened` on the JVM, `resolve_flattened_column_name` in Python), and + `meta migrate`, the Prisma schema, the C# EF mapping and the Kotlin Exposed tables all use it. Set + on any other storage, it is refused at load (`ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE`). + See `docs/features/field-types.md`, "Embedded value objects". - **A `PascalCase` column rule.** `"naming": { "columns": "PascalCase" }` in `.metaobjects/config.json` upper-cases a field name's first letter and changes nothing else (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`), in every port: the column names EF Core diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md index a1e709017f..5d363051a5 100644 --- a/agent-context/skills/metaobjects-authoring/SKILL.md +++ b/agent-context/skills/metaobjects-authoring/SKILL.md @@ -286,7 +286,9 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@storage` controls persistence: - `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. + Illegal on array fields. The prefix is the field's column and `_`; + `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' + own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. - `subdocument` (default, back-compat) — single jsonb column. diff --git a/agent-context/skills/metaobjects-codegen/references/physical-names.md b/agent-context/skills/metaobjects-codegen/references/physical-names.md index 83f8364241..d200bbf855 100644 --- a/agent-context/skills/metaobjects-codegen/references/physical-names.md +++ b/agent-context/skills/metaobjects-codegen/references/physical-names.md @@ -92,9 +92,11 @@ artifact exists *for your code*, which is the only place a physical name appears Two categories stay literal, deliberately, and the gate pins them as such rather than exempting them: -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; +- a **flattened value-object column** (`@storage: flattened`) is a composite — the + embedding field's prefix (its `@flattenedColumnPrefix`, else `_`) + followed by the member's column — belonging to no single field of either object, so there + is no one constant to reference. Compute it with core naming's + `resolveFlattenedColumnName` (or its port equivalent), never by concatenating; - a **write-through entity's replica view name**: the artifact holds the object's PRIMARY source's name (its table), and a write-through entity has two physical names. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 73b8182683..d7e9157567 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 421 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 423 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -285,7 +285,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (421) +### `fixtures/conformance/` — metamodel loader + canonical serializer (423) | Fixture prefix | Feature doc | |---|---| @@ -611,7 +611,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 421 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 423 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 381b8104d8..07eaa3f816 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -259,7 +259,7 @@ declaration. The `@storage` attr controls how the embedded shape persists. | `@storage` | Persistence shape | Use case | |---|---|---| -| `flattened` | One DB column per sub-field: `_` | EF Core `OwnsOne` / DDD value-objects | +| `flattened` | One DB column per sub-field: ``, the prefix `_` by default | EF Core `OwnsOne` / DDD value-objects | | `jsonb` | One `jsonb` column | Structured-but-evolvable user-defined shapes | | `subdocument` (default — back-compat) | Single jsonb column | Pre-`@storage` projects | @@ -276,6 +276,26 @@ Example: an `Author` with an embedded `Address` flattened to per-sub-field colum For `flattened`, the generated table gets `address_street`, `address_city`, `address_postal_code` columns instead of one `address` jsonb. +Each member's column is a **prefix** followed by the member's own column (its `@column`, else +its name under the project's column rule). The prefix defaults to the embedding field's column +and `_` (`address_`; with `@column: "bill"`, `bill_`; under the `PascalCase` rule, `Address_`, +EF Core's own default). **`@flattenedColumnPrefix`** on the embedding field replaces it, +verbatim: + +```json +{ "field.object": { "name": "homeAddress", "@objectRef": "Address", "@storage": "flattened", + "@flattenedColumnPrefix": "" } } +``` + +gives `street`, `city`, `postal_code`; `"@flattenedColumnPrefix": "home_"` gives `home_street`, and +so on. The prefix belongs to the embedding field, not the value object, because it is a fact +about the owning table: one `Address` embedded twice needs two prefixes. Every port names these +columns through the same core function (`resolveFlattenedColumnName` and its per-port +equivalents), so codegen, the runtime and `meta migrate` agree. On a field whose `@storage` is +not `flattened` the attribute is refused at load +(`ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE`): no other storage gives the members +columns of their own. + ## What each port generates ### TypeScript @@ -448,6 +468,8 @@ The following conformance fixtures gate this feature's behavior across ports: - [`fixtures/conformance/field-object-storage-jsonb-single/`](../../fixtures/conformance/field-object-storage-jsonb-single/) — `@storage=jsonb` single-record column - [`fixtures/conformance/field-object-storage-jsonb-array/`](../../fixtures/conformance/field-object-storage-jsonb-array/) — `@storage=jsonb` on array field - [`fixtures/conformance/error-field-object-storage-flattened-array/`](../../fixtures/conformance/error-field-object-storage-flattened-array/) — `@storage=flattened` on array field is illegal +- [`fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/`](../../fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/) and [`…-default-storage/`](../../fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/) — `@flattenedColumnPrefix` without `@storage=flattened` is illegal +- [`fixtures/naming-conformance/physical-names/`](../../fixtures/naming-conformance/physical-names/) — flattened member columns under every column rule, with and without `@flattenedColumnPrefix` - [`fixtures/conformance/error-field-object-storage-no-object-ref/`](../../fixtures/conformance/error-field-object-storage-no-object-ref/) — `field.object` without `@objectRef` rejected Cross-port runner coverage: TS / Java / Kotlin / C# / Python all execute these diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..5d363051a5 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -286,7 +286,9 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@storage` controls persistence: - `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. + Illegal on array fields. The prefix is the field's column and `_`; + `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' + own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. - `subdocument` (default, back-compat) — single jsonb column. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 83f8364241..d200bbf855 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -92,9 +92,11 @@ artifact exists *for your code*, which is the only place a physical name appears Two categories stay literal, deliberately, and the gate pins them as such rather than exempting them: -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; +- a **flattened value-object column** (`@storage: flattened`) is a composite — the + embedding field's prefix (its `@flattenedColumnPrefix`, else `_`) + followed by the member's column — belonging to no single field of either object, so there + is no one constant to reference. Compute it with core naming's + `resolveFlattenedColumnName` (or its port equivalent), never by concatenating; - a **write-through entity's replica view name**: the artifact holds the object's PRIMARY source's name (its table), and a write-through entity has two physical names. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..5d363051a5 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -286,7 +286,9 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@storage` controls persistence: - `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. + Illegal on array fields. The prefix is the field's column and `_`; + `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' + own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. - `subdocument` (default, back-compat) — single jsonb column. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 83f8364241..d200bbf855 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -92,9 +92,11 @@ artifact exists *for your code*, which is the only place a physical name appears Two categories stay literal, deliberately, and the gate pins them as such rather than exempting them: -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; +- a **flattened value-object column** (`@storage: flattened`) is a composite — the + embedding field's prefix (its `@flattenedColumnPrefix`, else `_`) + followed by the member's column — belonging to no single field of either object, so there + is no one constant to reference. Compute it with core naming's + `resolveFlattenedColumnName` (or its port equivalent), never by concatenating; - a **write-through entity's replica view name**: the artifact holds the object's PRIMARY source's name (its table), and a write-through entity has two physical names. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..5d363051a5 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -286,7 +286,9 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@storage` controls persistence: - `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. + Illegal on array fields. The prefix is the field's column and `_`; + `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' + own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. - `subdocument` (default, back-compat) — single jsonb column. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 83f8364241..d200bbf855 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -92,9 +92,11 @@ artifact exists *for your code*, which is the only place a physical name appears Two categories stay literal, deliberately, and the gate pins them as such rather than exempting them: -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; +- a **flattened value-object column** (`@storage: flattened`) is a composite — the + embedding field's prefix (its `@flattenedColumnPrefix`, else `_`) + followed by the member's column — belonging to no single field of either object, so there + is no one constant to reference. Compute it with core naming's + `resolveFlattenedColumnName` (or its port equivalent), never by concatenating; - a **write-through entity's replica view name**: the artifact holds the object's PRIMARY source's name (its table), and a write-through entity has two physical names. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..5d363051a5 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -286,7 +286,9 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@storage` controls persistence: - `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. + Illegal on array fields. The prefix is the field's column and `_`; + `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' + own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. - `subdocument` (default, back-compat) — single jsonb column. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 83f8364241..d200bbf855 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -92,9 +92,11 @@ artifact exists *for your code*, which is the only place a physical name appears Two categories stay literal, deliberately, and the gate pins them as such rather than exempting them: -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; +- a **flattened value-object column** (`@storage: flattened`) is a composite — the + embedding field's prefix (its `@flattenedColumnPrefix`, else `_`) + followed by the member's column — belonging to no single field of either object, so there + is no one constant to reference. Compute it with core naming's + `resolveFlattenedColumnName` (or its port equivalent), never by concatenating; - a **write-through entity's replica view name**: the artifact holds the object's PRIMARY source's name (its table), and a write-through entity has two physical names. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md index a1e709017f..5d363051a5 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -286,7 +286,9 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@storage` controls persistence: - `flattened` — one DB column per sub-field (`address_street`, `address_city`, …). - Illegal on array fields. + Illegal on array fields. The prefix is the field's column and `_`; + `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' + own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. - `subdocument` (default, back-compat) — single jsonb column. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 83f8364241..d200bbf855 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -92,9 +92,11 @@ artifact exists *for your code*, which is the only place a physical name appears Two categories stay literal, deliberately, and the gate pins them as such rather than exempting them: -- a **flattened value-object column** (`@storage: flattened`) is a composite — - `_` — belonging to no single field of either object, - so there is no one constant to reference; +- a **flattened value-object column** (`@storage: flattened`) is a composite — the + embedding field's prefix (its `@flattenedColumnPrefix`, else `_`) + followed by the member's column — belonging to no single field of either object, so there + is no one constant to reference. Compute it with core naming's + `resolveFlattenedColumnName` (or its port equivalent), never by concatenating; - a **write-through entity's replica view name**: the artifact holds the object's PRIMARY source's name (its table), and a write-through entity has two physical names. diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index d2c931bbad..019c46b02c 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -53,6 +53,7 @@ "ERR_TEMPLATE_ENGINE_UNSUPPORTED": "Build-time verify and render (ADR-0061): a template body is written for an engine this port does not ship — a Jinja body (.jinja / .j2 / .jinja2) in the Java, Kotlin or C# port, which render Mustache only. path = the template ref.", "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate or object.report (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", + "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", "ERR_UNRESOLVED_OBJECT_REF": "ADR-0042: a field.object / field.map @objectRef does not resolve to any object in the loaded tree (a dangling target). The ref resolves package-locally when bare (referrer's package, else root-level) and exactly when FQN — a bare cross-package ref no longer binds elsewhere. The error names same-short-name objects in other packages so the author can qualify it.", diff --git a/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/expected-errors.json b/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/expected-errors.json new file mode 100644 index 0000000000..9c0ece68e4 --- /dev/null +++ b/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE", + "source": { + "format": "json", + "files": [ + "meta.storage.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[1]['field.object']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/input/meta.storage.json b/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/input/meta.storage.json new file mode 100644 index 0000000000..098810c27b --- /dev/null +++ b/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/input/meta.storage.json @@ -0,0 +1,57 @@ +{ + "metadata.root": { + "package": "test", + "children": [ + { + "object.value": { + "name": "Address", + "children": [ + { + "field.string": { + "name": "street" + } + } + ] + } + }, + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.object": { + "name": "billTo", + "@objectRef": "test::Address", + "@flattenedColumnPrefix": "" + } + }, + { + "field.object": { + "name": "returnTo", + "@objectRef": "test::Address", + "@storage": "flattened", + "@flattenedColumnPrefix": "ret_" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/providers.json b/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-field-object-flattened-column-prefix-default-storage/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/expected-errors.json b/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/expected-errors.json new file mode 100644 index 0000000000..9c0ece68e4 --- /dev/null +++ b/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE", + "source": { + "format": "json", + "files": [ + "meta.storage.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[1]['field.object']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/input/meta.storage.json b/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/input/meta.storage.json new file mode 100644 index 0000000000..720dae57a1 --- /dev/null +++ b/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/input/meta.storage.json @@ -0,0 +1,58 @@ +{ + "metadata.root": { + "package": "test", + "children": [ + { + "object.value": { + "name": "Address", + "children": [ + { + "field.string": { + "name": "street" + } + } + ] + } + }, + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.object": { + "name": "shipTo", + "@objectRef": "test::Address", + "@storage": "jsonb", + "@flattenedColumnPrefix": "ship_" + } + }, + { + "field.object": { + "name": "returnTo", + "@objectRef": "test::Address", + "@storage": "flattened", + "@flattenedColumnPrefix": "ret_" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/providers.json b/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-field-object-flattened-column-prefix-without-flattened-storage/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index ee43c8bddc..3790f21eea 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -71,7 +71,7 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `field.int`: `@column`, `@db.indexed`, `@dbColumnType` - `field.long`: `@column`, `@db.indexed`, `@dbColumnType` - `field.map`: `@column`, `@db.indexed`, `@dbColumnType` -- `field.object`: `@column`, `@db.indexed`, `@dbColumnType`, `@storage` +- `field.object`: `@column`, `@db.indexed`, `@dbColumnType`, `@flattenedColumnPrefix`, `@storage` - `field.string`: `@column`, `@db.indexed`, `@dbColumnType` - `field.time`: `@autoSet`, `@column`, `@db.indexed`, `@dbColumnType` - `field.timestamp`: `@autoSet`, `@column`, `@db.indexed`, `@dbColumnType`, `@localTime` diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index f087e964f3..77a8d92433 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -444,6 +444,7 @@ A nested structured value (set @objectRef to the target object). Storage is gove | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | +| `@flattenedColumnPrefix` | string | no | | | metaobjects-db | On a field.object with @storage "flattened": the text put before each member's column, verbatim ("" allowed, so the members keep their own column names). Absent: this field's resolved column name and "_" (with @column "bill", the members are bill_). A fact about the owning table, so it lives on the embedding field, never on the value object. Refused on any other storage (ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE). | | `@formExclude` | boolean | no | | | metaobjects-ui | When true, the field is omitted from generated forms, and the generated create, PATCH and PUT routes ignore a value sent for it (reads of it are unchanged); inert on fields for which no form is generated (e.g. projection/derived fields). | | `@instruction` | string | no | | | metaobjects-prompt | FR-010: a short instruction for this field, shown in the generated output-format prompt fragment. | | `@mutability` | string | no | | `readWrite`, `writeOnce`, `readOnly` | metaobjects-core-types | FR-037 R1: who may write this field, and when. 'readWrite' (the default when absent) — the caller may set it on create and change it on update. 'writeOnce' — the caller sets it on create; it is excluded from the update shape thereafter, so a value presented on PATCH is ignored rather than rejected. 'readOnly' — nobody writes it: codegen emits no setter / writable property, the persistence layer skips the column on INSERT/UPDATE, and Zod/Pydantic/class-validator schemas omit it from input variants; the value is populated by the database (computed column, default expression, trigger), by replication, or by another external owner. The three are mutually exclusive modes of ONE axis — who may write, and when — so the illegal pair is unrepresentable and inheritance has a total order: a subtype may TIGHTEN an inherited mode (readWrite < writeOnce < readOnly) and never loosen it (ERR_MUTABILITY_DOWNGRADE). Pairing a non-readWrite mode with @autoSet is ERR_MUTABILITY_AUTOSET_CONFLICT: @autoSet already says the SERVER supplies the value, which is a different axis from who may write it. | diff --git a/fixtures/naming-conformance/physical-names/cases.json b/fixtures/naming-conformance/physical-names/cases.json index 0899f839d0..ecb76e49ca 100644 --- a/fixtures/naming-conformance/physical-names/cases.json +++ b/fixtures/naming-conformance/physical-names/cases.json @@ -1,64 +1,82 @@ { - "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `PascalCase` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`): the names EF Core and most C# schemas use.", + "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `PascalCase` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`): the names EF Core and most C# schemas use. A key `..` names a member of a `@storage: flattened` value object: its column is the flattened prefix (`@flattenedColumnPrefix` on the embedding field, verbatim, `\"\"` allowed; else that field's resolved column and `_`) followed by the member's resolved column.", "cases": [ { "name": "default", "naming": null, - "tables": { "OrderItem": "order_items", "Person": "people", "AuditEntry": "audit_log", "Category": "categories", "HTTPRequest": "http_requests" }, + "tables": { "OrderItem": "order_items", "Person": "people", "AuditEntry": "audit_log", "Category": "categories", "HTTPRequest": "http_requests", "Shipment": "shipments" }, "columns": { "OrderItem.id": "id", "OrderItem.createdAt": "created_at", "OrderItem.unitPriceCents": "unit_price_cents", "OrderItem.sku": "SKU_CODE", "Person.firstName": "first_name", "Person.lastName": "family_name", - "AuditEntry.eventType": "event_type", "Category.displayName": "display_name", "HTTPRequest.requestURL": "request_url" + "AuditEntry.eventType": "event_type", + "Category.displayName": "display_name", + "HTTPRequest.requestURL": "request_url", + "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY" } }, { "name": "empty block is the default", "naming": {}, - "tables": { "OrderItem": "order_items", "Person": "people", "AuditEntry": "audit_log", "Category": "categories", "HTTPRequest": "http_requests" }, + "tables": { "OrderItem": "order_items", "Person": "people", "AuditEntry": "audit_log", "Category": "categories", "HTTPRequest": "http_requests", "Shipment": "shipments" }, "columns": { "OrderItem.id": "id", "OrderItem.createdAt": "created_at", "OrderItem.unitPriceCents": "unit_price_cents", "OrderItem.sku": "SKU_CODE", "Person.firstName": "first_name", "Person.lastName": "family_name", - "AuditEntry.eventType": "event_type", "Category.displayName": "display_name", "HTTPRequest.requestURL": "request_url" + "AuditEntry.eventType": "event_type", + "Category.displayName": "display_name", + "HTTPRequest.requestURL": "request_url", + "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY" } }, { "name": "literal columns", "naming": { "columns": "literal" }, - "tables": { "OrderItem": "order_items", "Person": "people", "AuditEntry": "audit_log", "Category": "categories", "HTTPRequest": "http_requests" }, + "tables": { "OrderItem": "order_items", "Person": "people", "AuditEntry": "audit_log", "Category": "categories", "HTTPRequest": "http_requests", "Shipment": "shipments" }, "columns": { "OrderItem.id": "id", "OrderItem.createdAt": "createdAt", "OrderItem.unitPriceCents": "unitPriceCents", "OrderItem.sku": "SKU_CODE", "Person.firstName": "firstName", "Person.lastName": "family_name", - "AuditEntry.eventType": "eventType", "Category.displayName": "displayName", "HTTPRequest.requestURL": "requestURL" + "AuditEntry.eventType": "eventType", + "Category.displayName": "displayName", + "HTTPRequest.requestURL": "requestURL", + "Shipment.id": "id", "Shipment.shipTo.street": "shipTo_street", "Shipment.shipTo.postalCode": "shipTo_postalCode", "Shipment.shipTo.country": "shipTo_CTRY", "Shipment.billTo.postalCode": "bill_postalCode", "Shipment.returnTo.postalCode": "postalCode", "Shipment.giftTo.postalCode": "g_postalCode", "Shipment.giftTo.country": "g_CTRY" } }, { "name": "literal tables", "naming": { "tables": "literal" }, - "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests" }, + "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests", "Shipment": "Shipments" }, "columns": { "OrderItem.id": "id", "OrderItem.createdAt": "created_at", "OrderItem.unitPriceCents": "unit_price_cents", "OrderItem.sku": "SKU_CODE", "Person.firstName": "first_name", "Person.lastName": "family_name", - "AuditEntry.eventType": "event_type", "Category.displayName": "display_name", "HTTPRequest.requestURL": "request_url" + "AuditEntry.eventType": "event_type", + "Category.displayName": "display_name", + "HTTPRequest.requestURL": "request_url", + "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY" } }, { "name": "kebab-case columns, literal tables", "naming": { "columns": "kebab-case", "tables": "literal" }, - "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests" }, + "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests", "Shipment": "Shipments" }, "columns": { "OrderItem.id": "id", "OrderItem.createdAt": "created-at", "OrderItem.unitPriceCents": "unit-price-cents", "OrderItem.sku": "SKU_CODE", "Person.firstName": "first-name", "Person.lastName": "family_name", - "AuditEntry.eventType": "event-type", "Category.displayName": "display-name", "HTTPRequest.requestURL": "request-url" + "AuditEntry.eventType": "event-type", + "Category.displayName": "display-name", + "HTTPRequest.requestURL": "request-url", + "Shipment.id": "id", "Shipment.shipTo.street": "ship-to_street", "Shipment.shipTo.postalCode": "ship-to_postal-code", "Shipment.shipTo.country": "ship-to_CTRY", "Shipment.billTo.postalCode": "bill_postal-code", "Shipment.returnTo.postalCode": "postal-code", "Shipment.giftTo.postalCode": "g_postal-code", "Shipment.giftTo.country": "g_CTRY" } }, { "name": "PascalCase columns, literal tables", "naming": { "columns": "PascalCase", "tables": "literal" }, - "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests" }, + "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests", "Shipment": "Shipments" }, "columns": { "OrderItem.id": "Id", "OrderItem.createdAt": "CreatedAt", "OrderItem.unitPriceCents": "UnitPriceCents", "OrderItem.sku": "SKU_CODE", "Person.firstName": "FirstName", "Person.lastName": "family_name", - "AuditEntry.eventType": "EventType", "Category.displayName": "DisplayName", "HTTPRequest.requestURL": "RequestURL" + "AuditEntry.eventType": "EventType", + "Category.displayName": "DisplayName", + "HTTPRequest.requestURL": "RequestURL", + "Shipment.id": "Id", "Shipment.shipTo.street": "ShipTo_Street", "Shipment.shipTo.postalCode": "ShipTo_PostalCode", "Shipment.shipTo.country": "ShipTo_CTRY", "Shipment.billTo.postalCode": "bill_PostalCode", "Shipment.returnTo.postalCode": "PostalCode", "Shipment.giftTo.postalCode": "g_PostalCode", "Shipment.giftTo.country": "g_CTRY" } } ], @@ -67,6 +85,6 @@ { "name": "kebab-case is not a table rule", "naming": { "tables": "kebab-case" } }, { "name": "PascalCase is not a table rule", "naming": { "tables": "PascalCase" } }, { "name": "unknown key", "naming": { "column": "literal" } }, - { "name": "not an object", "naming": "snake_case" } + { "name": "not an object", "naming": "snake_case"} ] } diff --git a/fixtures/naming-conformance/physical-names/meta.naming.json b/fixtures/naming-conformance/physical-names/meta.naming.json index 45402809c7..eb351ec696 100644 --- a/fixtures/naming-conformance/physical-names/meta.naming.json +++ b/fixtures/naming-conformance/physical-names/meta.naming.json @@ -59,6 +59,30 @@ { "identity.primary": { "name": "id", "@fields": "id" } } ] } + }, + { + "object.value": { + "name": "Address", + "children": [ + { "field.string": { "name": "street" } }, + { "field.string": { "name": "postalCode" } }, + { "field.string": { "name": "country", "@column": "CTRY" } } + ] + } + }, + { + "object.entity": { + "name": "Shipment", + "children": [ + { "source.rdb": {} }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { "name": "billTo", "@objectRef": "Address", "@storage": "flattened", "@column": "bill" } }, + { "field.object": { "name": "returnTo", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "" } }, + { "field.object": { "name": "giftTo", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "g_" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } } ] } diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index e0fe66f7ef..826bc5a7a7 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -2005,6 +2005,13 @@ "required": false, "description": "When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer)." }, + { + "name": "flattenedColumnPrefix", + "valueType": "string", + "isArray": false, + "required": false, + "description": "On a field.object with @storage \"flattened\": the text put before each member's column, verbatim (\"\" allowed, so the members keep their own column names). Absent: this field's resolved column name and \"_\" (with @column \"bill\", the members are bill_). A fact about the owning table, so it lives on the embedding field, never on the value object. Refused on any other storage (ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE)." + }, { "name": "formExclude", "valueType": "boolean", diff --git a/scripts/check-doc-examples.ts b/scripts/check-doc-examples.ts index 37ad016a7d..c845a9c08f 100644 --- a/scripts/check-doc-examples.ts +++ b/scripts/check-doc-examples.ts @@ -154,6 +154,7 @@ const FAIL_CODES = new Set([ "ERR_MUTABILITY_DOWNGRADE", "ERR_READONLY_ASSIGNED_PRIMARY", "ERR_STORAGE_FLATTENED_ARRAY", + "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE", "ERR_PHYSICAL_NAME_KIND_MISMATCH", "ERR_PHYSICAL_NAME_MULTIPLE", "ERR_SQL_BODY_ON_WRITABLE_KIND", diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs index 304daf0902..d7c1e4e236 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs @@ -10,7 +10,9 @@ // and CSharpNaming.Column — never a reimplementation. Each `invalid` block must be refused // when the config is read. using System.Text.Json; +using MetaObjects; using MetaObjects.Config; +using MetaObjects.Core.Field; using MetaObjects.Loader; using MetaObjects.Meta; using Xunit; @@ -121,14 +123,25 @@ public void Resolves_every_table_and_column_name(string name) foreach (var (key, expectedColumn) in c.Columns) { - var parts = key.Split('.', 2); + var parts = key.Split('.', 3); var obj = root.FindObject(parts[0]); Assert.NotNull(obj); // ADR-0039: Fields() is the resolving accessor (an inherited field must resolve). var field = obj!.Fields().FirstOrDefault(f => f.Name == parts[1]); Assert.NotNull(field); - // CSharpNaming.Column is the exact door the entity/names generators call. - Assert.Equal(expectedColumn, CSharpNaming.Column(field!, naming.Columns)); + if (parts.Length == 2) + { + // CSharpNaming.Column is the exact door the entity/names generators call. + Assert.Equal(expectedColumn, CSharpNaming.Column(field!, naming.Columns)); + continue; + } + // `..`: a member of the flattened value object the field + // embeds, named by core naming, the door the DbContext generator calls. + var target = NamingRefs.RefTarget(field!, FieldConstants.FIELD_ATTR_OBJECT_REF) as MetaObject; + Assert.NotNull(target); + var member = target!.Fields().FirstOrDefault(f => f.Name == parts[2]); + Assert.NotNull(member); + Assert.Equal(expectedColumn, PhysicalNaming.ResolveFlattenedColumnName(field!, member!, naming.Columns)); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs index a704ee3c23..428f39609f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs @@ -96,6 +96,42 @@ public void Referenced_value_object_is_emitted_as_a_plain_poco() Assert.DoesNotContain("[Key]", address); } + // @flattenedColumnPrefix replaces the default `_` prefix, verbatim ("" keeps the members' + // own columns), and the default prefix follows the project's column rule: the names + // `meta migrate` creates for the same model (core naming's ResolveFlattenedColumnPrefix). + [Theory] + [InlineData(ColumnNamingStrategy.Literal, "street", "Officestreet", "homeAddress_street")] + [InlineData(ColumnNamingStrategy.PascalCase, "Street", "OfficeStreet", "HomeAddress_Street")] + public void DbContext_flattened_columns_follow_column_prefix_and_the_column_rule( + ColumnNamingStrategy strategy, string plain, string prefixed, string byDefault) + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Address", "children": [ { "field.string": { "name": "street" } } ]}}, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "mailing", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "" } }, + { "field.object": { "name": "work", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "Office" } }, + { "field.object": { "name": "homeAddress", "@objectRef": "Address", "@storage": "flattened" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "prefix.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = strategy }, + }; + var dbContext = new DbContextGenerator().Generate(ctx).Single().Content; + + Assert.Contains($"b.Property(p => p.Street).HasColumnName(\"{plain}\");", dbContext); + Assert.Contains($"b.Property(p => p.Street).HasColumnName(\"{prefixed}\");", dbContext); + Assert.Contains($"b.Property(p => p.Street).HasColumnName(\"{byDefault}\");", dbContext); + } + [Fact] public void DbContext_configures_owned_types_flattened_and_json() { diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index aa604b2b1f..2022ac03fb 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -1099,7 +1099,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s } // Owned-type config for an object-typed entity field. @storage flattened maps each - // nested scalar to "{parentCol}_{nestedCol}"; every other storage collapses to one + // nested scalar to "{prefix}{nestedCol}" (core naming's flattened prefix); every other storage collapses to one // json column (.ToJson) — matching the TS-owned schema DDL. null (with a warning) // when @objectRef can't be resolved. is the emitted CLR class // name (the write entity, or a write-through entity's View read model — #214). @@ -1118,7 +1118,6 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s } var strategy = ctx.Config.ColumnNamingStrategy; var nav = CSharpNaming.Pascal(field.Name); - var parentCol = CSharpNaming.Column(field, strategy); // A6 -- the field itself belongs to `entity` (the JSON column's own physical // name, not the nested value object's), so it hits entity's own names artifact // unconditionally in practice — a lookup, not an assumption, per ColumnRef. @@ -1164,14 +1163,14 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s ? $" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.ToJson({parentColRef}));" : OwnedJsonBlock("OwnsOne", owner, nav, parentColRef, jsonEnums); - // Flattened-column prefix for each nested member: `_`. This is - // migrate-ts's rule (expected-schema.ts flattenObjectField), and TS owns the schema - // (ADR-0015) — so it is the convention, NOT EF's, whose own owned-type default is - // `` + // A NESTED value object: migrate gives it ONE json column at `` // (subtypeToSqlType returns { kind: "json" } for field.object — a nested VO does // not flatten recursively). EF models it as a nested owned type, so it needs its // own ToJson pinned to that column, plus the enum conversions its own members @@ -1241,7 +1240,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s } // A `field.map` member: the migration flattens it to a jsonb column at - // `_`, so it takes the SAME converter/comparer pair a top-level map + // ``, so it takes the SAME converter/comparer pair a top-level map // takes, pinned to that name. Previously this fell to a warning whose stated // reason was that the port configured a top-level map nowhere either — that is // no longer true, and an unmapped dictionary here binds EF's ` + + + + + + + + + diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index 44c1048d73..50b3584845 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -21,6 +21,7 @@ "type": "field", "subType": "object", "children": [ + { "type": "attr", "subType": "string", "name": "flattenedColumnPrefix", "min": 0, "max": 1, "description": "On a field.object with @storage \"flattened\": the text put before each member's column, verbatim (\"\" allowed, so the members keep their own column names). Absent: this field's resolved column name and \"_\" (with @column \"bill\", the members are bill_). A fact about the owning table, so it lives on the embedding field, never on the value object. Refused on any other storage (ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE)." }, { "type": "attr", "subType": "string", "name": "storage", "min": 0, "max": 1, "allowedValues": ["flattened", "jsonb", "subdocument"], "description": "Storage strategy for an object-typed field (set with @objectRef). \"flattened\" expands the nested value into prefixed columns on the parent table. \"jsonb\" stores the structured value in a single jsonb column (supports isArray=true for arrays of values). \"subdocument\" is a hint for document-store codegen targets and emits no Postgres column." } ] }, From 4e961b9cb42b2764c7874359f0daa8765207cc3f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 1 Nov 2026 22:23:04 -0500 Subject: [PATCH 013/267] fix(naming): review fixes for PascalCase and @flattenedColumnPrefix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Java and Python checked @flattenedColumnPrefix on a root-level abstract field.object, so a prefix declared on a template and inherited through extends loaded in TS and C# but was refused in Java and Python. Every port now checks only fields an object owns. The naming fixture gains a field that inherits its prefix, in every case. - The C# DbContext built the member half of a flattened column itself; an empty member @column gave `bill_` where migrate creates `bill_street`. It now takes the whole name from PhysicalNaming.ResolveFlattenedColumnName. - PascalCase: JavaScript and Python upper-case `ß` to "SS"; C# and Java keep it. Every port now keeps a first character whose upper case is not one character. - Agent guidance said matching metamodelVersions mean ports are in sync. Added vocabulary no longer moves it, so the always-on context and the audit skill now say a match rules out breaking divergence only. - RELEASING, CHANGELOG and the gate comment speak for the metamodel version only; the package version follows the existing table. - Docs: no runtime uses these functions yet, so the docs name the consumers that do; no release number on PascalCase; absent @storage is one jsonb column, as the code does; an empty prefix and a non-empty one merge without ERR_MERGE_CONFLICT, so declare a prefix in one file. - A named constant for "flattened" in Java and Python; the new error's message names the object and field in every port; a stronger Prisma assertion; a stale Prisma comment. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++-- .../skills/metaobjects-audit/SKILL.md | 2 +- .../references/calibration.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 3 +- agent-context/templates/always-on.md.mustache | 4 +-- docs/RELEASING.md | 2 +- docs/features/field-types.md | 11 +++++-- docs/features/migrations/physical-naming.md | 2 +- examples/showcase/site-payload.json | 2 +- .../.claude/skills/metaobjects-audit/SKILL.md | 2 +- .../references/calibration.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 3 +- .../expected/.metaobjects/AGENTS.md | 4 +-- .../expected/.metaobjects/CLAUDE.md | 4 +-- .../.claude/skills/metaobjects-audit/SKILL.md | 2 +- .../references/calibration.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 3 +- .../expected/.metaobjects/AGENTS.md | 4 +-- .../expected/.metaobjects/CLAUDE.md | 4 +-- .../.claude/skills/metaobjects-audit/SKILL.md | 2 +- .../references/calibration.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 3 +- .../python/expected/.metaobjects/AGENTS.md | 4 +-- .../python/expected/.metaobjects/CLAUDE.md | 4 +-- .../.claude/skills/metaobjects-audit/SKILL.md | 2 +- .../references/calibration.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 3 +- .../expected/.metaobjects/AGENTS.md | 4 +-- .../expected/.metaobjects/CLAUDE.md | 4 +-- .../.claude/skills/metaobjects-audit/SKILL.md | 2 +- .../references/calibration.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 3 +- .../expected/.metaobjects/AGENTS.md | 4 +-- .../expected/.metaobjects/CLAUDE.md | 4 +-- .../physical-names/cases.json | 14 ++++---- .../physical-names/meta.naming.json | 2 ++ scripts/check-metamodel-version.mjs | 6 ++-- scripts/test-metamodel-version.mjs | 2 +- .../ObjectFieldCodegenTests.cs | 33 +++++++++++++++++++ .../Generators/DbContextGenerator.cs | 20 +++++------ .../csharp/MetaObjects/Meta/PhysicalNaming.cs | 2 +- .../metaobjects/database/ColumnNaming.java | 3 +- .../com/metaobjects/field/ObjectField.java | 2 ++ .../metaobjects/loader/ValidationPhase.java | 15 ++++++--- .../metaobjects/loader/validation_passes.py | 15 ++++++--- .../meta/core/field/field_constants.py | 4 ++- server/python/src/metaobjects/naming.py | 18 +++++++--- .../tests/unit/test_column_naming_strategy.py | 9 +++++ .../src/prisma/build-prisma-schema.ts | 5 +-- .../test/prisma/prisma-schema.test.ts | 2 +- .../packages/metadata/src/naming.ts | 12 +++++-- .../packages/metadata/test/naming.test.ts | 15 +++++++++ .../ADR-0058-one-physical-naming-setting.md | 2 +- 53 files changed, 199 insertions(+), 91 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fb8a9fac3..56dd587265 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -62,8 +62,10 @@ here.** - **Added vocabulary no longer moves `metamodelVersion`.** The metamodel spec version now moves only when metadata that loaded may stop loading or change meaning. A new type, subtype, - optional attribute or enum member ships in the package's patch release, and its CHANGELOG - entry names it. `scripts/check-metamodel-version.mjs` and `docs/RELEASING.md` say so. + optional attribute or enum member leaves it unchanged, and its CHANGELOG entry names it; the + package version follows the versioning table in `docs/RELEASING.md`, as before. Matching + `metamodelVersion`s therefore no longer prove two ports know the same vocabulary; compare + their releases. - **`meta migrate` refuses a foreign key that references columns the target does not hold unique.** Behaviour change: an `identity.reference` whose dotted `@references` names target fields that are diff --git a/agent-context/skills/metaobjects-audit/SKILL.md b/agent-context/skills/metaobjects-audit/SKILL.md index 21a2973750..d483666b1e 100644 --- a/agent-context/skills/metaobjects-audit/SKILL.md +++ b/agent-context/skills/metaobjects-audit/SKILL.md @@ -75,7 +75,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/agent-context/skills/metaobjects-audit/references/calibration.md b/agent-context/skills/metaobjects-audit/references/calibration.md index 4271e57eea..86f6e6bdbe 100644 --- a/agent-context/skills/metaobjects-audit/references/calibration.md +++ b/agent-context/skills/metaobjects-audit/references/calibration.md @@ -30,5 +30,5 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md index 5d363051a5..d3c3fdad9d 100644 --- a/agent-context/skills/metaobjects-authoring/SKILL.md +++ b/agent-context/skills/metaobjects-authoring/SKILL.md @@ -290,7 +290,8 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `subdocument` — single jsonb column (a hint for document-store targets). +- not set (the default) — one `jsonb` column, as `jsonb`. ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } diff --git a/agent-context/templates/always-on.md.mustache b/agent-context/templates/always-on.md.mustache index 260d02e3f6..21b59391c8 100644 --- a/agent-context/templates/always-on.md.mustache +++ b/agent-context/templates/always-on.md.mustache @@ -79,9 +79,9 @@ from. - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 4f98446a93..74aac3b2df 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -304,7 +304,7 @@ requires. Same shape as `buf breaking --against '.git#tag=…'` / `oasdiff`. | Change | Required move | |---|---| | a type/subtype removed; an attr removed; an attr made required, retyped or re-arrayed; an enum member removed or an open attr closed; a child rule removed, its `min` raised or its `max` lowered; a default subtype changed | **major** (pre-1.0: minor — see below) | -| a type/subtype added; an optional attr added; an enum member added; a child rule added or relaxed; a default subtype added | **none** — every document that loaded still loads, identically. The package release carries it (a PATCH unless it is also a software-surface change), and the CHANGELOG names what was added | +| a type/subtype added; an optional attr added; an enum member added; a child rule added or relaxed; a default subtype added | **none** — every document that loaded still loads, identically, so `metamodelVersion` stays put and the CHANGELOG names what was added. The package version follows the versioning table above | | prose only (`description` / `rules` / `whenToUse`) | none — but read the warning | **Pre-1.0 a breaking change moves the MINOR**, for the same reason the package line diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 07eaa3f816..2a46cfbf86 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -261,7 +261,8 @@ declaration. The `@storage` attr controls how the embedded shape persists. |---|---|---| | `flattened` | One DB column per sub-field: ``, the prefix `_` by default | EF Core `OwnsOne` / DDD value-objects | | `jsonb` | One `jsonb` column | Structured-but-evolvable user-defined shapes | -| `subdocument` (default — back-compat) | Single jsonb column | Pre-`@storage` projects | +| `subdocument` | Single jsonb column | A hint for document-store targets | +| not set (the default) | One `jsonb` column, as `jsonb` | Pre-`@storage` projects | Example: an `Author` with an embedded `Address` flattened to per-sub-field columns: @@ -291,11 +292,17 @@ gives `street`, `city`, `postal_code`; `"@flattenedColumnPrefix": "home_"` gives so on. The prefix belongs to the embedding field, not the value object, because it is a fact about the owning table: one `Address` embedded twice needs two prefixes. Every port names these columns through the same core function (`resolveFlattenedColumnName` and its per-port -equivalents), so codegen, the runtime and `meta migrate` agree. On a field whose `@storage` is +equivalents), so `meta migrate`, the Prisma schema, the C# EF mapping and the Kotlin Exposed +tables agree. On a field whose `@storage` is not `flattened` the attribute is refused at load (`ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE`): no other storage gives the members columns of their own. +Declare a field's prefix in one file. When two files both declare the same field (a merge, not +an `overlay`), the loader reports `ERR_MERGE_CONFLICT` for two different non-empty values, but +it treats `""` as unset when it compares them: one file's `"home_"` and another's `""` merge +without an error, and the last one loaded wins. + ## What each port generates ### TypeScript diff --git a/docs/features/migrations/physical-naming.md b/docs/features/migrations/physical-naming.md index dbe05e5f17..d8406c1cc8 100644 --- a/docs/features/migrations/physical-naming.md +++ b/docs/features/migrations/physical-naming.md @@ -30,7 +30,7 @@ every runtime `ObjectManager` and `verify` read it, so they always produce the s An unknown key or value fails when the file is read. Index and constraint names are unchanged. -`PascalCase` (added in 1.2.1) upper-cases the field name's first letter and changes nothing +`PascalCase` upper-cases the field name's first letter and changes nothing else: `createdAt` becomes `CreatedAt` and `requestURL` becomes `RequestURL`. It is the column EF Core creates for a property, so a camelCase model over an EF-built schema needs `@column` only where the database spells a name differently (an acronym the field writes in lower case, diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 82e51fcbdd..6e9ec3f63d 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 421, + "fixtures": 423, "corpora": 35, "baseTypes": 17 }, diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md index 21a2973750..d483666b1e 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -75,7 +75,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 4271e57eea..86f6e6bdbe 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -30,5 +30,5 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index 5d363051a5..d3c3fdad9d 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -290,7 +290,8 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `subdocument` — single jsonb column (a hint for document-store targets). +- not set (the default) — one `jsonb` column, as `jsonb`. ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md index d34c780c8f..37777f30c2 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/AGENTS.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/CLAUDE.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/CLAUDE.md index d34c780c8f..37777f30c2 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/CLAUDE.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.metaobjects/CLAUDE.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md index 21a2973750..d483666b1e 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -75,7 +75,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md index 4271e57eea..86f6e6bdbe 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -30,5 +30,5 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md index 5d363051a5..d3c3fdad9d 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -290,7 +290,8 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `subdocument` — single jsonb column (a hint for document-store targets). +- not set (the default) — one `jsonb` column, as `jsonb`. ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } diff --git a/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md index 60118bd559..aea562ab32 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/java-react/expected/.metaobjects/AGENTS.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/java-react/expected/.metaobjects/CLAUDE.md b/fixtures/agent-context-conformance/java-react/expected/.metaobjects/CLAUDE.md index 60118bd559..aea562ab32 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.metaobjects/CLAUDE.md +++ b/fixtures/agent-context-conformance/java-react/expected/.metaobjects/CLAUDE.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md index 21a2973750..d483666b1e 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -75,7 +75,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md index 4271e57eea..86f6e6bdbe 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -30,5 +30,5 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md index 5d363051a5..d3c3fdad9d 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -290,7 +290,8 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `subdocument` — single jsonb column (a hint for document-store targets). +- not set (the default) — one `jsonb` column, as `jsonb`. ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } diff --git a/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md index 49fe8148af..6ddb0cf71f 100644 --- a/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/python/expected/.metaobjects/AGENTS.md @@ -54,9 +54,9 @@ from. - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/python/expected/.metaobjects/CLAUDE.md b/fixtures/agent-context-conformance/python/expected/.metaobjects/CLAUDE.md index 49fe8148af..6ddb0cf71f 100644 --- a/fixtures/agent-context-conformance/python/expected/.metaobjects/CLAUDE.md +++ b/fixtures/agent-context-conformance/python/expected/.metaobjects/CLAUDE.md @@ -54,9 +54,9 @@ from. - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md index 21a2973750..d483666b1e 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -75,7 +75,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md index 4271e57eea..86f6e6bdbe 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -30,5 +30,5 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index 5d363051a5..d3c3fdad9d 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -290,7 +290,8 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `subdocument` — single jsonb column (a hint for document-store targets). +- not set (the default) — one `jsonb` column, as `jsonb`. ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md index a296481115..598d218cad 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/AGENTS.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/CLAUDE.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/CLAUDE.md index a296481115..598d218cad 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/CLAUDE.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.metaobjects/CLAUDE.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/SKILL.md index 21a2973750..d483666b1e 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/SKILL.md @@ -75,7 +75,7 @@ Actual cutovers run through the existing skills mapped per finding tier (§ Brid removed those four and 1.1 restored them: there it is an upgrade blocker, fixed by upgrading to 1.1 or by ejecting. Importing anything from that subpath is otherwise correct and is never a finding by itself. -- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) +- [ ] **Cross-language version consistency (silent-drift check).** If the project uses MetaObjects in more than one language (e.g. a TS web client + a Java/Python/C# backend), enumerate EVERY MetaObjects package across ALL ecosystems (npm `@metaobjectsdev/*`, Maven `com.metaobjects:*`, PyPI `metaobjects`, NuGet `MetaObjects.*`) and record each version. **The version-number LINES differ by ecosystem (npm/PyPI/NuGet `0.x`/`1.x` vs Maven `7.x`/`8.x`), so you CANNOT eyeball drift** — a `0.12` next to a `7.7` looks fine but can be badly out of sync. Compare the **`metamodelVersion`** each port reports (the shared spec version on the registry manifest): a mismatch is real cross-language drift and a **finding** — the ports disagree on vocabulary/wire behavior. A match is not enough on its own: added vocabulary does not move `metamodelVersion`, so also compare each port's release (each ecosystem's version for one CHANGELOG entry). A port on an older release is a **finding** when the model uses vocabulary that release lacks. Also flag any port not on the latest release for its ecosystem. (This is a known real-world failure mode: newest backend, stale client, invisible because the numbers differ.) - [ ] Classify: **Greenfield** (none/minimal) · **Partial** · **Deep** → choose path below. --- diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/calibration.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/calibration.md index 4271e57eea..86f6e6bdbe 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/calibration.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/calibration.md @@ -30,5 +30,5 @@ - **Cut subtypes** — `field.byte` / `field.short` / `field.class` are removed; never recommend them. - **TS/web-only** — `view.*` widget subtypes load in every port but are consumed only by TS/web; only `view.base` / `view.currency` are cross-port-gated. - **Planned, not shipped** — `api.*` / `operation.*` / `binding.*` (FR-024) and MCP exposure of declared prompts/tools are not yet in the registry; their absence is not an adopter defect. -- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). +- **Cross-port version-NUMBER skew is by design** — TS/C#/Python `0.x` vs Java/Kotlin `7.x` Maven is correct; never flag the *number lines* differing. But that is exactly why you can't eyeball cross-language drift: compare **`metamodelVersion`** (Phase 0 cross-language consistency item), not the package numbers. A `metamodelVersion` MISMATCH across ports *is* a finding; so is a port lagging its ecosystem's latest release. A MATCH does not prove parity: added vocabulary does not move `metamodelVersion`, so ports on one metamodel version can still disagree on which attributes they know. Also flag *intra-port* drift (mixed versions within one port, or a runtime package in `devDependencies`). - **Stale upstream prose** — "hand-write the Spring controller" (Java/Kotlin) is out of date; trust `meta gen --list`, not stale prose. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md index 5d363051a5..d3c3fdad9d 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -290,7 +290,8 @@ Reuse a constraint set across entities with an abstract `field.enum` + `extends` `@flattenedColumnPrefix` on the field replaces it verbatim (`""` keeps the members' own columns). Refused on any other storage. - `jsonb` — one `jsonb` column. -- `subdocument` (default, back-compat) — single jsonb column. +- `subdocument` — single jsonb column (a hint for document-store targets). +- not set (the default) — one `jsonb` column, as `jsonb`. ```json { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } } diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/AGENTS.md b/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/AGENTS.md index 29d77fc749..010c075141 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/AGENTS.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/AGENTS.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/CLAUDE.md b/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/CLAUDE.md index 29d77fc749..010c075141 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/CLAUDE.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.metaobjects/CLAUDE.md @@ -57,9 +57,9 @@ Not there? List the missing generator — and a `docs` target, if `targets` has - Package paths use `::` (`acme::common::id`). ## Keep all MetaObjects ports in sync -MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. Ports are only truly in sync when every one implements the same **Metamodel spec version** (`metamodelVersion`, on the registry manifest). Upgrade ALL ports together and confirm they land on the same Metamodel version; a lagging port silently disagrees on vocabulary + wire behavior. +MetaObjects ships as separate packages per language on DIFFERENT version lines (npm/PyPI/NuGet `0.x`/`1.x`, Maven Central `7.x`/`8.x`). Because the numbers differ by ecosystem, a stale port is INVISIBLE — an old TS client next to a new Java backend *looks* fine. A matching **Metamodel spec version** (`metamodelVersion`, on the registry manifest) means no port carries a BREAKING metamodel change the others lack. It does not move for added vocabulary, so ports on the same metamodel version can still differ in which attributes and subtypes they know: they are fully in sync only when every port is on the same release (each ecosystem's version for one CHANGELOG entry). Upgrade ALL ports together; a lagging port refuses vocabulary the others accept and can disagree on wire behavior. -`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work, separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. +`metamodelVersion` is also the number that tells you whether YOUR METADATA needs work (it moves only for a breaking metamodel change), separately from the package version, which tells you whether your BUILD does. A package major means imports/CLI/generated-code shape may need attention; a metamodel major means your model may. A release can move one without the other — so when you upgrade, read the changelog for a metamodel-version move, not just the package number. For a 1.0.x → 1.0.x upgrade, follow https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-within-1.0.md: it covers resyncing the generators you own (`meta eject --list`), which a plain `meta gen` does not do. **Upgrading from 1.0 to 1.1:** read https://github.com/metaobjectsdev/metaobjects/blob/main/docs/features/migrations/upgrading-1.0-to-1.1.md before you run `gen`, because the build can stay green while the result is wrong. It is the one page for every port and lists the steps in order. The changes that fail nothing when skipped: the default column and table names are now `snake_case` in every port, so a C#, Java, Kotlin or Python database whose columns are named like its fields needs `"naming": { "columns": "literal" }` in `.metaobjects/config.json`, or the regenerated code queries columns that do not exist; and a fractional validator `@min`/`@max` is refused. Upgrade to 1.1.2 or later: with no `wire` setting each port writes its language's standard JSON, and a project whose clients expect 1.1.0's canonical decimal strings declares `"wire": { "decimals": "string", "nullMembers": "omit" }` in `.metaobjects/config.json`. Documentation is a generator in the project's list, and the docs commands are removed. Then resync every generator you own (`meta eject --list` reports each copy that differs from the reference; `meta eject --force` takes the new one, and a plain `meta gen` does not): an owned copy keeps the logic it was copied with. diff --git a/fixtures/naming-conformance/physical-names/cases.json b/fixtures/naming-conformance/physical-names/cases.json index ecb76e49ca..9567aa4c9b 100644 --- a/fixtures/naming-conformance/physical-names/cases.json +++ b/fixtures/naming-conformance/physical-names/cases.json @@ -1,5 +1,5 @@ { - "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `PascalCase` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`): the names EF Core and most C# schemas use. A key `..` names a member of a `@storage: flattened` value object: its column is the flattened prefix (`@flattenedColumnPrefix` on the embedding field, verbatim, `\"\"` allowed; else that field's resolved column and `_`) followed by the member's resolved column.", + "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `PascalCase` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`): the names EF Core and most C# schemas use. A key `..` names a member of a `@storage: flattened` value object: its column is the flattened prefix (`@flattenedColumnPrefix` on the embedding field, verbatim, `\"\"` allowed; else that field's resolved column and `_`) followed by the member's resolved column; a prefix inherited through `extends` counts.", "cases": [ { "name": "default", @@ -11,7 +11,7 @@ "AuditEntry.eventType": "event_type", "Category.displayName": "display_name", "HTTPRequest.requestURL": "request_url", - "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY" + "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY", "Shipment.homeTo.postalCode": "addr_postal_code" } }, { @@ -24,7 +24,7 @@ "AuditEntry.eventType": "event_type", "Category.displayName": "display_name", "HTTPRequest.requestURL": "request_url", - "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY" + "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY", "Shipment.homeTo.postalCode": "addr_postal_code" } }, { @@ -37,7 +37,7 @@ "AuditEntry.eventType": "eventType", "Category.displayName": "displayName", "HTTPRequest.requestURL": "requestURL", - "Shipment.id": "id", "Shipment.shipTo.street": "shipTo_street", "Shipment.shipTo.postalCode": "shipTo_postalCode", "Shipment.shipTo.country": "shipTo_CTRY", "Shipment.billTo.postalCode": "bill_postalCode", "Shipment.returnTo.postalCode": "postalCode", "Shipment.giftTo.postalCode": "g_postalCode", "Shipment.giftTo.country": "g_CTRY" + "Shipment.id": "id", "Shipment.shipTo.street": "shipTo_street", "Shipment.shipTo.postalCode": "shipTo_postalCode", "Shipment.shipTo.country": "shipTo_CTRY", "Shipment.billTo.postalCode": "bill_postalCode", "Shipment.returnTo.postalCode": "postalCode", "Shipment.giftTo.postalCode": "g_postalCode", "Shipment.giftTo.country": "g_CTRY", "Shipment.homeTo.postalCode": "addr_postalCode" } }, { @@ -50,7 +50,7 @@ "AuditEntry.eventType": "event_type", "Category.displayName": "display_name", "HTTPRequest.requestURL": "request_url", - "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY" + "Shipment.id": "id", "Shipment.shipTo.street": "ship_to_street", "Shipment.shipTo.postalCode": "ship_to_postal_code", "Shipment.shipTo.country": "ship_to_CTRY", "Shipment.billTo.postalCode": "bill_postal_code", "Shipment.returnTo.postalCode": "postal_code", "Shipment.giftTo.postalCode": "g_postal_code", "Shipment.giftTo.country": "g_CTRY", "Shipment.homeTo.postalCode": "addr_postal_code" } }, { @@ -63,7 +63,7 @@ "AuditEntry.eventType": "event-type", "Category.displayName": "display-name", "HTTPRequest.requestURL": "request-url", - "Shipment.id": "id", "Shipment.shipTo.street": "ship-to_street", "Shipment.shipTo.postalCode": "ship-to_postal-code", "Shipment.shipTo.country": "ship-to_CTRY", "Shipment.billTo.postalCode": "bill_postal-code", "Shipment.returnTo.postalCode": "postal-code", "Shipment.giftTo.postalCode": "g_postal-code", "Shipment.giftTo.country": "g_CTRY" + "Shipment.id": "id", "Shipment.shipTo.street": "ship-to_street", "Shipment.shipTo.postalCode": "ship-to_postal-code", "Shipment.shipTo.country": "ship-to_CTRY", "Shipment.billTo.postalCode": "bill_postal-code", "Shipment.returnTo.postalCode": "postal-code", "Shipment.giftTo.postalCode": "g_postal-code", "Shipment.giftTo.country": "g_CTRY", "Shipment.homeTo.postalCode": "addr_postal-code" } }, { @@ -76,7 +76,7 @@ "AuditEntry.eventType": "EventType", "Category.displayName": "DisplayName", "HTTPRequest.requestURL": "RequestURL", - "Shipment.id": "Id", "Shipment.shipTo.street": "ShipTo_Street", "Shipment.shipTo.postalCode": "ShipTo_PostalCode", "Shipment.shipTo.country": "ShipTo_CTRY", "Shipment.billTo.postalCode": "bill_PostalCode", "Shipment.returnTo.postalCode": "PostalCode", "Shipment.giftTo.postalCode": "g_PostalCode", "Shipment.giftTo.country": "g_CTRY" + "Shipment.id": "Id", "Shipment.shipTo.street": "ShipTo_Street", "Shipment.shipTo.postalCode": "ShipTo_PostalCode", "Shipment.shipTo.country": "ShipTo_CTRY", "Shipment.billTo.postalCode": "bill_PostalCode", "Shipment.returnTo.postalCode": "PostalCode", "Shipment.giftTo.postalCode": "g_PostalCode", "Shipment.giftTo.country": "g_CTRY", "Shipment.homeTo.postalCode": "addr_PostalCode" } } ], diff --git a/fixtures/naming-conformance/physical-names/meta.naming.json b/fixtures/naming-conformance/physical-names/meta.naming.json index eb351ec696..f3e394ca94 100644 --- a/fixtures/naming-conformance/physical-names/meta.naming.json +++ b/fixtures/naming-conformance/physical-names/meta.naming.json @@ -60,6 +60,7 @@ ] } }, + { "field.object": { "name": "AddrCols", "abstract": true, "@objectRef": "acme::naming::Address", "@flattenedColumnPrefix": "addr_" } }, { "object.value": { "name": "Address", @@ -80,6 +81,7 @@ { "field.object": { "name": "billTo", "@objectRef": "Address", "@storage": "flattened", "@column": "bill" } }, { "field.object": { "name": "returnTo", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "" } }, { "field.object": { "name": "giftTo", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "g_" } }, + { "field.object": { "name": "homeTo", "extends": "acme::naming::AddrCols", "@storage": "flattened" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs index 8ec802fc90..890e397733 100755 --- a/scripts/check-metamodel-version.mjs +++ b/scripts/check-metamodel-version.mjs @@ -118,9 +118,9 @@ const isPre1 = (v) => v.major === 0; export function requiredBump(severity, base, { correction = false } = {}) { if (severity === "none") return "none"; // ADDITIVE moves no metamodel number. Every document that loaded still loads, and means - // the same, so nothing an adopter relies on changed: the package's patch release carries - // the new vocabulary and its CHANGELOG entry names it. The number moves only when - // existing metadata may stop loading or change meaning. + // the same, so nothing an adopter's metadata relies on changed: the CHANGELOG entry names + // the new vocabulary, and the package version follows docs/RELEASING.md. The number moves + // only when existing metadata may stop loading or change meaning. if (severity === "additive") return "none"; if (correction) return "minor"; // breaking, but a correction — never a metamodel major return isPre1(base) ? "minor" : "major"; // breaking diff --git a/scripts/test-metamodel-version.mjs b/scripts/test-metamodel-version.mjs index 064ab53105..31b0a33934 100755 --- a/scripts/test-metamodel-version.mjs +++ b/scripts/test-metamodel-version.mjs @@ -276,7 +276,7 @@ const bump = (sev, base) => requiredBump(sev, v(base)); if (bump("none", "1.0") !== "none") bad("no change requires no bump"); else ok("no change requires no bump"); // Additive vocabulary moves no metamodel number: every document that loaded still loads, -// identically, so the package's patch release carries it and the CHANGELOG names it. +// identically, so the CHANGELOG names it and the package version follows docs/RELEASING.md. if (bump("additive", "1.0") !== "none") bad("additive requires no bump"); else ok("additive requires no bump"); if (bump("breaking", "1.0") !== "major") bad("post-1.0 breaking requires a major"); diff --git a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs index 428f39609f..06405ce5f3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs @@ -132,6 +132,39 @@ public void DbContext_flattened_columns_follow_column_prefix_and_the_column_rule Assert.Contains($"b.Property(p => p.Street).HasColumnName(\"{byDefault}\");", dbContext); } + // Each flattened member's column is core naming's, whole: the generator does not build the + // member half itself. A member whose @column is "" is the case that told them apart: core + // treats an empty @column as absent, so the column is `bill_street`, not `bill_`. + [Fact] + public void DbContext_flattened_member_columns_are_core_namings() + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Address", "children": [ { "field.string": { "name": "street", "@column": "" } } ]}}, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "billing", "@objectRef": "Address", "@storage": "flattened", "@column": "bill" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "member.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.SnakeCase }, + }; + var dbContext = new DbContextGenerator().Generate(ctx).Single().Content; + + var billing = r.Root.FindObject("Customer")!.Fields().Single(f => f.Name == "billing"); + var street = r.Root.FindObject("Address")!.Fields().Single(f => f.Name == "street"); + var expected = PhysicalNaming.ResolveFlattenedColumnName(billing, street, ColumnNamingStrategy.SnakeCase); + Assert.Equal("bill_street", expected); + Assert.Contains($"b.Property(p => p.Street).HasColumnName(\"{expected}\");", dbContext); + } + [Fact] public void DbContext_configures_owned_types_flattened_and_json() { diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 2022ac03fb..de985e3ac1 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -1099,7 +1099,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s } // Owned-type config for an object-typed entity field. @storage flattened maps each - // nested scalar to "{prefix}{nestedCol}" (core naming's flattened prefix); every other storage collapses to one + // nested scalar to its core-naming flattened column (PhysicalNaming.ResolveFlattenedColumnName); every other storage collapses to one // json column (.ToJson) — matching the TS-owned schema DDL. null (with a warning) // when @objectRef can't be resolved. is the emitted CLR class // name (the write entity, or a write-through entity's View read model — #214). @@ -1163,14 +1163,14 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s ? $" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.ToJson({parentColRef}));" : OwnedJsonBlock("OwnsOne", owner, nav, parentColRef, jsonEnums); - // Flattened-column prefix for each nested member: core naming's rule - // (PhysicalNaming.ResolveFlattenedColumnPrefix) — the field's @flattenedColumnPrefix verbatim, - // else `_` — the same function migrate-ts names these columns - // with, and TS owns the schema (ADR-0015). It is NOT EF's own owned-type default, - // `` (migrate's @@ -287,7 +286,7 @@ public void DbContext_names_every_flattened_member_the_migration_creates() """ b.OwnsOne(p => p.Badge, nb => { - nb.ToJson("profile_badge"); + nb.ToJson(CustomerNames.ProfileBadgeColumn); nb.Property(p => p.Tier).HasConversion(); }); """, @@ -318,7 +317,7 @@ public void A_flattened_map_member_binds_its_prefixed_jsonb_column() // the shared helper. The VO value type is FULLY QUALIFIED — the DbContext's usings // cover entity namespaces only, and a value object is not an entity. Assert.Contains( - "b.Property(p => p.Prefs).HasColumnName(\"profile_prefs\").HasColumnType(\"jsonb\")" + "b.Property(p => p.Prefs).HasColumnName(CustomerNames.ProfilePrefsColumn).HasColumnType(\"jsonb\")" + ".HasConversion(MapJsonb.Converter()" + ", MapJsonb.Comparer());", dbContext); diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 67e384982e..5b9001497f 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -18,8 +18,16 @@ namespace MetaObjects.Codegen; -/// Physical name + logical field name for one field (§A2/§A3 names artifact). -public sealed record FieldNames(string Name, string Column); +/// +/// Physical name + logical field name for one field (§A2/§A3 names artifact). +/// A @storage: "flattened" value object has NO column of its own: is null and names one column per member of the +/// value object, keyed by the member's field name, through core naming +/// (, +/// the function meta migrate names them with). The field's own resolved column +/// (ship_to) does not exist in the database, so nothing here names it. +/// +public sealed record FieldNames(string Name, string? Column, IReadOnlyDictionary? Members = null); /// /// One source.rdb child, under the ROLE it plays. @@ -514,11 +522,11 @@ public static bool HasPrimarySource(MetaObject obj) => // ADR-0039: Fields() is the RESOLVING accessor — an inherited @column must // resolve here, or the constant disagrees with the column EF actually binds. foreach (var f in obj.Fields()) - fields[f.Name] = new FieldNames(f.Name, Column(f, strategy)); + fields[f.Name] = FieldNamesOf(f, strategy); // ADR-0039's sanctioned own-accessor use: what this artifact DECLARES. var ownFields = new Dictionary(StringComparer.Ordinal); foreach (var f in obj.OwnFields()) - ownFields[f.Name] = new FieldNames(f.Name, Column(f, strategy)); + ownFields[f.Name] = FieldNamesOf(f, strategy); var superObj = NamesArtifactSuperOf(obj); // Identity of the resolved source NODE, not equality of the resolved strings: a @@ -720,10 +728,10 @@ private static bool DeclaresNamesContent(MetaObject obj) => var fields = new Dictionary(StringComparer.Ordinal); foreach (var f in obj.Fields()) - fields[f.Name] = new FieldNames(f.Name, Column(f, strategy)); + fields[f.Name] = FieldNamesOf(f, strategy); var ownFields = new Dictionary(StringComparer.Ordinal); foreach (var f in own) - ownFields[f.Name] = new FieldNames(f.Name, Column(f, strategy)); + ownFields[f.Name] = FieldNamesOf(f, strategy); return new ObjectNames { @@ -813,6 +821,28 @@ public static string KeyMemberName(string type, string keyName, string member) = /// One field member: EmailField / EmailColumn. See /// for why this stays on . + /// + /// One field's names. The flattened test is migrate's own: a field.object whose + /// resolved @storage is flattened. A flattened field whose @objectRef + /// does not resolve has no members; the loader refuses that model before codegen runs. + /// + public static FieldNames FieldNamesOf(MetaField f, ColumnNamingStrategy strategy) + { + if (f.SubType != FIELD_SUBTYPE_OBJECT || f.Storage != STORAGE_FLATTENED) + return new FieldNames(f.Name, Column(f, strategy)); + var members = new Dictionary(StringComparer.Ordinal); + if (NamingRefs.RefTarget(f, FIELD_ATTR_OBJECT_REF) is MetaObject vo) + { + foreach (var m in vo.Fields()) + members[m.Name] = new FieldNames(m.Name, PhysicalNaming.ResolveFlattenedColumnName(f, m, strategy)); + } + return new FieldNames(f.Name, null, members); + } + + /// The constant member naming a flattened member's column: ShipToStreetColumn. + public static string FlattenedColumnMemberName(string fieldName, string memberName) => + FieldMemberName(fieldName + Pascal(memberName), MEMBER_COLUMN); + public static string FieldMemberName(string fieldName, string member) => Pascal(fieldName) + Pascal(member); @@ -856,11 +886,32 @@ public static string FieldMemberName(string fieldName, string member) => public static string ColumnRef(MetaObject owner, MetaField field, ColumnNamingStrategy strategy, bool includeNames) { var names = includeNames ? ResolveObjectNames(owner, strategy) : null; - return names is not null && names.Fields.ContainsKey(field.Name) + // A flattened field names no column (FieldNames.Column is null): the literal stands. + return names is not null && names.Fields.TryGetValue(field.Name, out var entry) && entry.Column is not null ? $"{NamesClassName(owner)}.{FieldMemberName(field.Name, MEMBER_COLUMN)}" : $"\"{Column(field, strategy)}\""; } + /// + /// §A6 for a flattened value object's member: the <Owner>Names.<Field><Member>Column + /// constant when the names generator is in this run and the owner's artifact names + /// that member, the core-naming literal (quoted) otherwise — the same presence rule as + /// . + /// + public static string FlattenedColumnRef( + MetaObject owner, + MetaField field, + MetaField member, + ColumnNamingStrategy strategy, + bool includeNames) + { + var names = includeNames ? ResolveObjectNames(owner, strategy) : null; + return names is not null && names.Fields.TryGetValue(field.Name, out var entry) + && entry.Members is { } members && members.ContainsKey(member.Name) + ? $"{NamesClassName(owner)}.{FlattenedColumnMemberName(field.Name, member.Name)}" + : $"\"{PhysicalNaming.ResolveFlattenedColumnName(field, member, strategy)}\""; + } + /// /// I1/§A6 — the <Owner>Names.Source<Role><Alias> constant reference for 's physical table/view/proc name, when BOTH C1 ( s var sb = new StringBuilder(); sb.AppendLine($" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b =>"); sb.AppendLine(" {"); - // A6 -- NOT converted, on two independent grounds. `vo` (object.value) never - // carries a source (FR-024 value purity), so it has no Names artifact at - // all — CSharpNaming.ColumnRef would miss on every nf, always. And even with - // one, nestedCol is a COMPOSITE string (prefix + column), not the bare physical - // name a names constant holds — there is no single constant this could reference. + // A6 -- each member's column is a constant of the OWNING entity's names artifact + // (`Names.Column`), never of the value object's: `vo` carries + // no source (FR-024 value purity), so it has no artifact, and the column belongs to + // the owner's table anyway. CSharpNaming.FlattenedColumnRef falls back to the + // core-naming literal when the names generator is not in the run. // // Every member the migration flattens must be named here, in the value object's // declaration order. migrate's `flattenObjectField` (expected-schema.ts) iterates @@ -1205,6 +1205,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s foreach (var nf in vo.Fields()) { var nestedColAny = PhysicalNaming.ResolveFlattenedColumnName(field, nf, strategy); + var nestedColRef = CSharpNaming.FlattenedColumnRef(entity, field, nf, strategy, ctx.Config.IncludeNames); // An ARRAY enum: migrate gives it a native array column (subtypeToSqlType derives // text[] from isArray), and EF Core 8 maps it as a primitive collection. Same @@ -1213,7 +1214,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s if (nf.SubType == FIELD_SUBTYPE_ENUM && nf.ResolvedIsArray()) { sb.AppendLine($" b.PrimitiveCollection(p => p.{CSharpNaming.Pascal(nf.Name)})" - + $".HasColumnName(\"{nestedColAny}\").ElementType()" + + $".HasColumnName({nestedColRef}).ElementType()" + $".{EnumConversionCall(ValueObjectNames.TypeName(vo, ctx.Root), vo, nf, ctx.Config)};"); continue; } @@ -1229,7 +1230,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var ownsCall = nf.ResolvedIsArray() ? "OwnsMany" : "OwnsOne"; sb.AppendLine($" b.{ownsCall}(p => p.{CSharpNaming.Pascal(nf.Name)}, nb =>"); sb.AppendLine(" {"); - sb.AppendLine($" nb.ToJson(\"{nestedColAny}\");"); + sb.AppendLine($" nb.ToJson({nestedColRef});"); // `nb`, not `b` — the nested builder shadows the outer one, and emitting `b.` // here would compile-fail the GENERATED file (the outer builder is out of the // nested lambda's intended scope and names the wrong entity type anyway). @@ -1248,7 +1249,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s if (nf.SubType == FIELD_SUBTYPE_MAP) { sb.AppendLine($" b.Property(p => p.{CSharpNaming.Pascal(nf.Name)})" - + $".HasColumnName(\"{nestedColAny}\")" + MapJsonbSuffix(vo, nf, ctx) + ";"); + + $".HasColumnName({nestedColRef})" + MapJsonbSuffix(vo, nf, ctx) + ";"); continue; } @@ -1263,11 +1264,10 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s + "mapping here, so EF will bind its own default name instead. See KNOWN_GAPS.md."); continue; } - var nestedCol = nestedColAny; // The enum type nests in the value object's class (EntityGenerator's // EmitValueObjectPoco), so the VO is the `owner` the conversion qualifies it by. var conversion = isEnum ? $".{EnumConversionCall(ValueObjectNames.TypeName(vo, ctx.Root), vo, nf, ctx.Config)}" : ""; - sb.AppendLine($" b.Property(p => p.{CSharpNaming.Pascal(nf.Name)}).HasColumnName(\"{nestedCol}\"){conversion};"); + sb.AppendLine($" b.Property(p => p.{CSharpNaming.Pascal(nf.Name)}).HasColumnName({nestedColRef}){conversion};"); } sb.Append(" });"); return sb.ToString(); diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index 74c9186a45..8e5d7d464a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -158,7 +158,11 @@ private static List> MemberGroups(ObjectNames n, bool ownOnly) { var path = $"field \"{f.Name}\""; fieldMembers.Add(Str(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_FIELD), f.Name, path)); - fieldMembers.Add(Str(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN), f.Column, path)); + if (f.Column is not null) + fieldMembers.Add(Str(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN), f.Column, path)); + // A flattened value object: one constant per member's column, none for the field. + foreach (var m in (f.Members ?? new Dictionary()).Values.OrderBy(v => v.Name, StringComparer.Ordinal)) + fieldMembers.Add(Str(CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name), m.Column!, $"field \"{f.Name}.{m.Name}\"")); } groups.Add(fieldMembers); @@ -293,7 +297,13 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra sb.AppendLine($" public static {hides}readonly Dictionary ColumnsByField = new(System.StringComparer.Ordinal)"); sb.AppendLine(" {"); foreach (var f in names.Fields.Values.OrderBy(v => v.Name, StringComparer.Ordinal)) - sb.AppendLine($" [\"{f.Name}\"] = {CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)},"); + { + if (f.Column is not null) + sb.AppendLine($" [\"{f.Name}\"] = {CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)},"); + // A flattened member is keyed `.`, the path the naming corpus uses. + foreach (var m in (f.Members ?? new Dictionary()).Values.OrderBy(v => v.Name, StringComparer.Ordinal)) + sb.AppendLine($" [\"{f.Name}.{m.Name}\"] = {CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name)},"); + } sb.AppendLine(" };"); sb.AppendLine("}"); diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 4fb21db319..7f03156170 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -1337,10 +1337,14 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBaseNames has no - // constant for it. Always literal; useNames() does not reach here. - val baseSpec = KotlinTypeMapper.exposedColumnSpec(subField, "\"$colName\"", api) + // A column of `entity`'s table, so `Names` carries it as + // `__COLUMN` (KotlinNamesGenerator, from the same + // ColumnNaming.resolveFlattened); the literal only without the names artifact. + val colExpr = if (bindsThroughNames(entity)) { + val (_, shortName) = PackageMapping.splitFqn(entity.name) + "${KotlinNaming.namesObjectName(shortName)}.${KotlinNaming.flattenedColumnMember(parentName, subField.name)}" + } else "\"$colName\"" + val baseSpec = KotlinTypeMapper.exposedColumnSpec(subField, colExpr, api) // Sub-column is nullable iff the parent is nullable OR the sub-field itself is. val nullable = parentNullable || !KotlinGenUtil.isRequiredField(subField) val full = if (nullable) "$baseSpec.nullable()" else baseSpec diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt index 42bc4d6fd9..a18e1b648a 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt @@ -214,8 +214,20 @@ public object KotlinGenUtil { .firstOrNull { MetaSource.ROLE_PRIMARY == it.role } } - /** §A2/§A3 — physical name + logical field name for one field. */ - data class KotlinFieldNames(val name: String, val column: String) + /** + * §A2/§A3 — physical name + logical field name for one field. + * + * A `@storage: "flattened"` value object has NO column of its own: [column] is null and + * [members] names one column per member of the value object, keyed by the member's field + * name, through core naming ([ColumnNaming.resolveFlattened], the rule `meta migrate` + * names them by). The field's own resolved column (`ship_to`) does not exist in the + * database, so nothing here names it. + */ + data class KotlinFieldNames( + val name: String, + val column: String?, + val members: Map? = null, + ) /** * One `source.rdb` child, under the ROLE it plays. @@ -448,7 +460,21 @@ public object KotlinGenUtil { } private fun fieldMap(fields: Collection>, strategy: String): Map = - fields.associate { f -> f.name to KotlinFieldNames(f.name, resolveColumnName(f, strategy)) } + fields.associate { f -> f.name to fieldNamesOf(f, strategy) } + + /** + * The flattened test is migrate's own: a `field.object` whose RESOLVED `@storage` is + * `flattened`. Members are the value object's resolving fields. + */ + private fun fieldNamesOf(f: MetaField<*>, strategy: String): KotlinFieldNames { + val flattened = f is ObjectField && f.hasMetaAttr(ObjectField.ATTR_STORAGE, true) && + ObjectField.STORAGE_FLATTENED == f.getMetaAttr(ObjectField.ATTR_STORAGE, true).valueAsString + if (!flattened) return KotlinFieldNames(f.name, resolveColumnName(f, strategy)) + val target = (f as ObjectField).objectRef + val members = target?.metaFields.orEmpty() + .associate { m -> m.name to KotlinFieldNames(m.name, ColumnNaming.resolveFlattened(f, m, strategy)) } + return KotlinFieldNames(f.name, null, members) + } /** * The names FRAGMENT for an object that a sourced object extends but which declares no diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt index 4e7a84d258..1613e13b8b 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt @@ -235,8 +235,13 @@ open class KotlinNamesGenerator : // lookup surface, and a miss on an inherited field is exactly the // fallback-to-literal this artifact removes. append("\n val COLUMNS_BY_FIELD: Map = mapOf(\n") - for (name in names.fields.keys.sorted()) { - append(" \"$name\" to ${KotlinNaming.namesMember(name)}_COLUMN,\n") + val rows = names.fields.values.flatMap { f -> + (if (f.column != null) listOf(f.name to "${KotlinNaming.namesMember(f.name)}_COLUMN") else emptyList()) + + // A flattened member is keyed `.`, the path the naming corpus uses. + f.members.orEmpty().values.map { m -> "${f.name}.${m.name}" to KotlinNaming.flattenedColumnMember(f.name, m.name) } + }.sortedBy { it.first } + for ((key, constant) in rows) { + append(" \"$key\" to $constant,\n") } append(" )\n") append("}\n") @@ -295,7 +300,11 @@ open class KotlinNamesGenerator : val member = KotlinNaming.namesMember(f.name) val path = "$self.fields.${f.name}" out += NameConst("${member}_FIELD", f.name, path, "fields") - out += NameConst("${member}_COLUMN", f.column, path, "fields") + f.column?.let { out += NameConst("${member}_COLUMN", it, path, "fields") } + // A flattened value object: one constant per member's column, none for the field. + for (m in f.members.orEmpty().values.sortedBy { it.name }) { + out += NameConst(KotlinNaming.flattenedColumnMember(f.name, m.name), m.column!!, "$path.${m.name}", "fields") + } } addKeys(out, self, "identities", if (all) names.identities else names.ownIdentities) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt index ba4ab410f1..3990c3b37f 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNaming.kt @@ -127,6 +127,10 @@ object KotlinNaming { */ fun namesMember(fieldName: String): String = KotlinGenUtil.camelToSnake(fieldName).uppercase() + /** The constant naming a flattened member's column: `SHIP_TO_STREET_COLUMN`. */ + fun flattenedColumnMember(fieldName: String, memberName: String): String = + "${namesMember(fieldName)}_${namesMember(memberName)}_COLUMN" + /** * [KotlinSpringControllerGenerator] / [KotlinM2mSupport]: the REST collection segment — * the ENTITY NAME snake_cased and then pluralized (`Author` -> `authors`, diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt index 4bce41ee12..cb55fef69a 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt @@ -3,6 +3,7 @@ package com.metaobjects.generator.kotlin import com.metaobjects.metadata.ktx.loadString import java.nio.file.Files import kotlin.test.Test +import kotlin.test.assertFalse import kotlin.test.assertTrue class KotlinExposedTableGeneratorTest { @@ -290,6 +291,35 @@ class KotlinExposedTableGeneratorTest { } } + @Test fun flattenedColumnsReferenceTheNamesConstants() { + val outDir = Files.createTempDirectory("ktbl-flat-names-") + try { + val model = """{ + "metadata.root": { "package": "acme::demo", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "street", "@required": true } } + ] } }, + { "object.entity": { "name": "User", "children": [ + { "field.long": { "name": "id" } }, + { "field.object": { "name": "work", "@objectRef": "Address", "@storage": "flattened", "@flattenedColumnPrefix": "office_" } }, + { "source.rdb": { "@table": "users" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + }""".trimIndent() + val gen = KotlinExposedTableGenerator() + gen.setArgs(mapOf("outputDir" to outDir.toString(), KotlinGenUtil.ARG_USE_NAMES to "true")) + gen.execute(loadString("flat-names", model)) + + val src = Files.readString(outDir.resolve("acme/demo/UserTable.kt")) + assertTrue("val workStreet = text(UserNames.WORK_STREET_COLUMN)" in src, + "expected the flattened column through its names constant; saw:\n$src") + assertFalse("\"office_street\"" in src, "the literal must not be spelled; saw:\n$src") + } finally { + outDir.toFile().deleteRecursively() + } + } + @Test fun storageJsonbEmitsJsonbColumn() { val outDir = Files.createTempDirectory("ktbl-jsonb-") try { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt index ebc1a0dc83..d3437659f9 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt @@ -525,4 +525,70 @@ class KotlinNamesGeneratorTest { assertTrue("CREATED_AT" in e.message!!, e.message!!) } + + // ------------------------------------------------------------------------- + // Flattened value objects: one constant per member's column, none for the field + // ------------------------------------------------------------------------- + + private val flattenedModel = """{ + "metadata.root": { "package": "acme::ship", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "street" } }, + { "field.string": { "name": "postalCode", "@column": "ZIP" } } + ] } }, + { "object.entity": { "name": "Shipment", "children": [ + { "source.rdb": { "@table": "shipments" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { "name": "payload", "@objectRef": "Address" } }, + { "identity.primary": { "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + }""".trimIndent() + + @Test fun `a flattened member gets a column constant and its field gets none`() { + val src = emit(flattenedModel).getValue("acme/ship/ShipmentNames.kt") + + assertTrue("const val SHIP_TO_FIELD: String = \"shipTo\"" in src, src) + assertTrue("const val SHIP_TO_STREET_COLUMN: String = \"ship_to_street\"" in src, src) + assertTrue("const val SHIP_TO_POSTAL_CODE_COLUMN: String = \"ship_to_ZIP\"" in src, src) + // The field's own resolved column, `ship_to`, is not a column of the table. + assertFalse("SHIP_TO_COLUMN" in src, src) + assertFalse("\"ship_to\"" in src, src) + // A jsonb object is one column, as before. + assertTrue("const val PAYLOAD_COLUMN: String = \"payload\"" in src, src) + assertTrue("\"shipTo.street\" to SHIP_TO_STREET_COLUMN" in src, src) + assertTrue("\"shipTo.postalCode\" to SHIP_TO_POSTAL_CODE_COLUMN" in src, src) + assertFalse("\"shipTo\" to" in src, src) + } + + @Test fun `a flattened member constant colliding with a field constant is refused`() { + val model = flattenedModel.replace( + "\"@storage\": \"flattened\" }", + "\"@storage\": \"flattened\", \"@flattenedColumnPrefix\": \"st_\" } },\n" + + " { \"field.string\": { \"name\": \"shipToStreet\" }") + val ex = assertFailsWith { emit(model) } + assertTrue("SHIP_TO_STREET_COLUMN" in ex.message.orEmpty(), ex.message) + } + + /** The cross-port naming corpus: every `..` key is a constant, under every rule. */ + @Test fun `every flattened column in the naming corpus is a constant`() { + var dir: Path? = Path.of("").toAbsolutePath() + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.parent + val corpus = requireNotNull(dir) { "could not locate fixtures/" }.resolve("fixtures/naming-conformance/physical-names") + val model = corpus.resolve("meta.naming.json").readText() + val cases = com.fasterxml.jackson.databind.ObjectMapper().readTree(corpus.resolve("cases.json").toFile()).get("cases") + for (c in cases) { + val naming = c.get("naming") + val rule = if (naming != null && naming.has("columns")) naming.get("columns").asText() else "snake_case" + val src = emit(model, columnsRule = rule).getValue("acme/naming/ShipmentNames.kt") + for ((key, value) in c.get("columns").fields()) { + val parts = key.split(".") + if (parts.size != 3 || parts[0] != "Shipment") continue + val member = "${KotlinNaming.namesMember(parts[1])}_${KotlinNaming.namesMember(parts[2])}_COLUMN" + val decl = "const val $member: String = \"${value.asText()}\"" + assertTrue(decl in src, "${c.get("name").asText()}: $decl\n$src") + } + } + } } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt index f80bdcc651..803726e84d 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt @@ -37,12 +37,10 @@ import kotlin.test.assertTrue * gate is only ever as wide as its fixture, so treat the model below as the load-bearing * part of this file and add to it whenever a generator grows a new path. * - * As of 0.25.0 this port has ZERO ESCAPE and ZERO KNOWN_LITERAL rows but one, and the one - * that remains is genuinely structural rather than undone: a FLATTENED `object.value`'s - * nested column is a composite the artifact has no single member for. The three rows that - * left — the replica view and the two index names — left because `Names` grew the - * members they were pinned as lacking, which is what a self-extinguishing ledger row is - * for. + * This port has ZERO ESCAPE and ZERO KNOWN_LITERAL rows. Every row that left — the replica + * view, the two index names, and last the FLATTENED `object.value`'s member column — left + * because `Names` grew the member it was pinned as lacking, which is what a + * self-extinguishing ledger row is for. * * Every token carries its REACH — see [Reach]. Every non-[Reach.CONSTANT] value is PINNED, * not exempted: the gate asserts the condition it names is still true, so the day a @@ -174,11 +172,12 @@ class NoMagicPhysicalNamesTest { Token(colFk, "OrderNames.CUSTOMER_ID_COLUMN"), Token(jsonbCol, "CustomerNames.PROFILE_COLUMN"), Token( - flatCol, "(no constant exists)", Reach.KNOWN_LITERAL, - "A flattened object.value's nested column is a COMPOSITE (owner field column + \"_\" + " + - "member column). The value object has no source (FR-024 value purity) and so no " + - "Names, and the owner's artifact carries one constant per FIELD, not per " + - "flattened member — there is no single constant to reference.", + flatCol, "CustomerNames.ADDRESS_ROAD_COLUMN", Reach.CONSTANT, + "Promoted from KNOWN_LITERAL. A flattened object.value's member column is a COMPOSITE " + + "(core naming: the field's prefix + the member's column), and the old reason it had " + + "no constant was true: the value object has no source and so no Names, and the " + + "owner's artifact carried one constant per FIELD. It now carries one per flattened " + + "MEMBER (__COLUMN), and the Exposed table references it.", ), Token(view, "CustomerSummaryNames.SOURCE_PRIMARY_VIEW"), // The write-through entity's TWO physical names, each under the member for the role diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java index fc13918616..6bc71092ce 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java @@ -10,6 +10,7 @@ import com.metaobjects.database.ColumnNaming; import com.metaobjects.database.IndexNaming; import com.metaobjects.field.MetaField; +import com.metaobjects.field.ObjectField; import com.metaobjects.generator.EmitsPhysicalNameConstants; import com.metaobjects.generator.GeneratorException; import com.metaobjects.generator.GeneratorIOWriter; @@ -164,7 +165,17 @@ public void execute(MetaDataLoader loader) { // ------------------------------------------------------------------------- /** Physical name + logical field name for one field. */ - private record FieldNames(String name, String column) {} + /** + * One field's names. A {@code @storage: "flattened"} value object has NO column of its own: + * {@code column} is null and {@code members} names one column per member of the value + * object, keyed by the member's field name, through core naming + * ({@link ColumnNaming#resolveFlattened(MetaField, MetaField, String)}, the rule + * {@code meta migrate} names them by). The field's own resolved column ({@code ship_to}) + * does not exist in the database, so nothing here names it. + */ + private record FieldNames(String name, String column, Map members) { + FieldNames(String name, String column) { this(name, column, null); } + } /** * One {@code source.rdb} child, under the ROLE it plays. @@ -344,10 +355,37 @@ private static Map keysOf(Collection nodes return out; } + /** + * The flattened test is migrate's own: a {@code field.object} whose RESOLVED + * {@code @storage} is {@code flattened}. Members are the value object's resolving fields. + */ + private static FieldNames fieldNamesOf(MetaField field, String strategy) { + if (!(field instanceof ObjectField) + || !field.hasMetaAttr(ObjectField.ATTR_STORAGE, true) + || !ObjectField.STORAGE_FLATTENED.equals( + field.getMetaAttr(ObjectField.ATTR_STORAGE, true).getValueAsString())) { + return new FieldNames(field.getName(), ColumnNaming.resolve(field, strategy)); + } + Map members = new LinkedHashMap<>(); + MetaObject target = ((ObjectField) field).getObjectRef(); + if (target != null) { + for (MetaField member : target.getMetaFields()) { + members.put(member.getName(), new FieldNames(member.getName(), + ColumnNaming.resolveFlattened(field, member, strategy))); + } + } + return new FieldNames(field.getName(), null, members); + } + + /** The constant naming a flattened member's column: {@code SHIP_TO_STREET_COLUMN}. */ + static String flattenedColumnMember(String fieldName, String memberName) { + return namesMember(fieldName) + "_" + namesMember(memberName) + "_COLUMN"; + } + private static Map fieldMap(Collection src, String strategy) { Map out = new LinkedHashMap<>(); for (MetaField field : src) { - out.put(field.getName(), new FieldNames(field.getName(), ColumnNaming.resolve(field, strategy))); + out.put(field.getName(), fieldNamesOf(field, strategy)); } return out; } @@ -533,13 +571,19 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean // field of the same name is what makes Names.COLUMNS_BY_FIELD the complete one. List allRows = new ArrayList<>(); for (FieldNames f : names.fields().values()) { - allRows.add(new String[] { namesMember(f.name()), f.name() }); + if (f.column() != null) allRows.add(new String[] { namesMember(f.name()) + "_COLUMN", f.name() }); + // A flattened member is keyed `.`, the path the naming corpus uses. + if (f.members() != null) { + for (FieldNames m : f.members().values()) { + allRows.add(new String[] { flattenedColumnMember(f.name(), m.name()), f.name() + "." + m.name() }); + } + } } allRows.sort((a, b) -> a[1].compareTo(b[1])); src.append("\n public static final Map COLUMNS_BY_FIELD = Map.ofEntries(\n"); for (int i = 0; i < allRows.size(); i++) { String[] row = allRows.get(i); - src.append(" Map.entry(\"").append(row[1]).append("\", ").append(row[0]).append("_COLUMN)"); + src.append(" Map.entry(\"").append(row[1]).append("\", ").append(row[0]).append(")"); src.append(i < allRows.size() - 1 ? ",\n" : "\n"); } src.append(" );\n"); @@ -606,7 +650,15 @@ private static List membersOf(ObjectNames names, boolean all) { String member = namesMember(f.name()); String path = self + ".fields." + f.name(); out.add(str(member + "_FIELD", f.name(), path, "fields")); - out.add(str(member + "_COLUMN", f.column(), path, "fields")); + if (f.column() != null) out.add(str(member + "_COLUMN", f.column(), path, "fields")); + // A flattened value object: one constant per member's column, none for the field. + if (f.members() != null) { + for (String m : sorted(f.members())) { + FieldNames mn = f.members().get(m); + out.add(str(flattenedColumnMember(f.name(), mn.name()), mn.column(), + path + "." + mn.name(), "fields")); + } + } } addKeys(out, self, "identities", all ? names.identities() : names.ownIdentities()); diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java index efde171a77..0cebf9298a 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java @@ -714,4 +714,87 @@ private void compileAll(Path root) throws Exception { fail(sb.toString()); } } + + // ------------------------------------------------------------------------- + // Flattened value objects: one constant per member's column, none for the field + // ------------------------------------------------------------------------- + + private static final String FLATTENED_FIXTURE = """ + { + "metadata.root": { "package": "acme::ship", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "street" } }, + { "field.string": { "name": "postalCode", "@column": "ZIP" } } + ] } }, + { "object.entity": { "name": "Shipment", "children": [ + { "source.rdb": { "@table": "shipments" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { "name": "payload", "@objectRef": "Address" } }, + { "identity.primary": { "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + }"""; + + @Test + public void aFlattenedMemberGetsAColumnConstantAndItsFieldGetsNone() throws IOException { + String src = emit(FLATTENED_FIXTURE, "acme/ship/ShipmentNames.java", Map.of()); + + assertTrue(src, src.contains("public static final String SHIP_TO_FIELD = \"shipTo\";")); + assertTrue(src, src.contains("public static final String SHIP_TO_STREET_COLUMN = \"ship_to_street\";")); + assertTrue(src, src.contains("public static final String SHIP_TO_POSTAL_CODE_COLUMN = \"ship_to_ZIP\";")); + // The field's own resolved column, `ship_to`, is not a column of the table. + assertFalse(src, src.contains("SHIP_TO_COLUMN")); + assertFalse(src, src.contains("\"ship_to\"")); + // A jsonb object is one column, as before. + assertTrue(src, src.contains("public static final String PAYLOAD_COLUMN = \"payload\";")); + assertTrue(src, src.contains("Map.entry(\"shipTo.street\", SHIP_TO_STREET_COLUMN)")); + assertTrue(src, src.contains("Map.entry(\"shipTo.postalCode\", SHIP_TO_POSTAL_CODE_COLUMN)")); + assertFalse(src, src.contains("Map.entry(\"shipTo\",")); + } + + @Test + public void aFlattenedMemberConstantCollidingWithAFieldConstantIsRefused() { + String model = FLATTENED_FIXTURE.replace( + "\"@storage\": \"flattened\" }", + "\"@storage\": \"flattened\", \"@flattenedColumnPrefix\": \"st_\" } },\n" + + " { \"field.string\": { \"name\": \"shipToStreet\" }"); + try { + emit(model, "acme/ship/ShipmentNames.java", Map.of()); + fail("expected the SHIP_TO_STREET_COLUMN collision to be refused"); + } catch (GeneratorException | IOException e) { + assertTrue(e.getMessage(), e.getMessage().contains("SHIP_TO_STREET_COLUMN")); + } + } + + /** + * The cross-port naming corpus: every {@code ..} key is a flattened + * column, and the names artifact must carry each one as {@code __COLUMN} + * holding exactly the column {@code meta migrate} creates, under every naming rule. + */ + @Test + public void everyFlattenedColumnInTheNamingCorpusIsAConstant() throws IOException { + Path dir = Path.of("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.getParent(); + assertNotNull("could not locate the repository fixtures/ directory", dir); + Path corpus = dir.resolve("fixtures/naming-conformance/physical-names"); + String model = Files.readString(corpus.resolve("meta.naming.json")); + com.fasterxml.jackson.databind.JsonNode cases = new com.fasterxml.jackson.databind.ObjectMapper() + .readTree(corpus.resolve("cases.json").toFile()).get("cases"); + for (com.fasterxml.jackson.databind.JsonNode c : cases) { + com.fasterxml.jackson.databind.JsonNode naming = c.get("naming"); + String columnsRule = naming != null && naming.has("columns") ? naming.get("columns").asText() : "snake_case"; + String src = emit(model, "acme/naming/ShipmentNames.java", Map.of(), columnsRule); + var it = c.get("columns").fields(); + while (it.hasNext()) { + var e = it.next(); + String[] parts = e.getKey().split("\\."); + if (parts.length != 3 || !parts[0].equals("Shipment")) continue; + String member = SpringNamesGenerator.namesMember(parts[1]) + "_" + + SpringNamesGenerator.namesMember(parts[2]) + "_COLUMN"; + String decl = "public static final String " + member + " = \"" + e.getValue().asText() + "\";"; + assertTrue(c.get("name").asText() + ": " + decl + "\n" + src, src.contains(decl)); + } + } + } } diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index 4e7f9999d5..b15f6549d3 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -90,13 +90,21 @@ from metaobjects.meta.persistence.source.source_constants import ( PHYSICAL_NAME_ATTR_BY_KIND, ) +from metaobjects.meta.core.field.field_constants import ( + FIELD_ATTR_OBJECT_REF, + FIELD_ATTR_STORAGE, + FIELD_SUBTYPE_OBJECT, + STORAGE_FLATTENED, +) from metaobjects.naming import ( resolve_column_name, + resolve_flattened_column_name, resolve_index_name, strip_package, to_snake_case, ) from metaobjects.shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_INDEX +from metaobjects.naming_refs import ref_target from metaobjects.source_resolution import primary_rdb_source #: The nodes whose DATABASE index name this module carries. @@ -238,6 +246,35 @@ def _field_consts(field: MetaData, column: str) -> list[_Const]: ] +def _flattened_members(field: MetaData, strategy: str) -> list[tuple[str, str]] | None: + """The ``(member name, column)`` pairs of a ``@storage: "flattened"`` value object, or + ``None`` for any other field. + + The flattened test is migrate's own: a ``field.object`` whose RESOLVED ``@storage`` is + ``flattened`` (ADR-0039 — it may be inherited). Each member's column is core naming's + :func:`metaobjects.naming.resolve_flattened_column_name`, the rule ``meta migrate`` names + it by. A flattened field whose ``@objectRef`` does not resolve has no members; the loader + refuses that model before codegen runs. + """ + if field.sub_type != FIELD_SUBTYPE_OBJECT or field.get_meta_attr(FIELD_ATTR_STORAGE) != STORAGE_FLATTENED: + return None + target = ref_target(field, FIELD_ATTR_OBJECT_REF) + if not isinstance(target, MetaObject): + return [] + return [(m.name, resolve_flattened_column_name(field, m, strategy)) for m in target.fields()] + + +def _flattened_consts(field: MetaData, members: list[tuple[str, str]]) -> list[_Const]: + """A flattened value object: the field's ``_FIELD`` name, one ``__COLUMN`` + per member, and NO ``_COLUMN`` for the field — its own resolved column (``ship_to``) is + not a column of the table.""" + member = _member(field.name) + out = [_Const(f"{member}_FIELD", _q(field.name), f"field {field.name!r}")] + for name, column in sorted(members): + out.append(_Const(f"{member}_{_member(name)}_COLUMN", _q(column), f"field {field.name}.{name!r}")) + return out + + #: The node types a names module carries. A frozenset of module-level constants rather #: than an inline tuple: an inline one is rebuilt on every element compared, because #: CPython cannot fold a tuple of globals. @@ -404,11 +441,19 @@ def carried_by_super(node: MetaData) -> bool: # ADR-0039: fields() RESOLVES — an inherited field and an inherited @column both # must appear here, or the constant disagrees with what the runtime actually binds. + # (COLUMNS_BY_FIELD key, constant member) — a flattened member is keyed + # `.`, the path the naming corpus uses. columns: list[tuple[str, str]] = [] for field in sorted(entity.fields(), key=lambda f: f.name): - column = resolve_column_name(field, strategy) - columns.append((field.name, column)) - groups.append(("fields", _field_consts(field, column), carried_by_super(field))) + members = _flattened_members(field, strategy) + if members is None: + column = resolve_column_name(field, strategy) + columns.append((field.name, f"{_member(field.name)}_COLUMN")) + groups.append(("fields", _field_consts(field, column), carried_by_super(field))) + continue + for name, _column in members: + columns.append((f"{field.name}.{name}", f"{_member(field.name)}_{_member(name)}_COLUMN")) + groups.append(("fields", _flattened_consts(field, members), carried_by_super(field))) for type_name in (TYPE_IDENTITY, TYPE_INDEX): keys = sorted( @@ -488,11 +533,11 @@ def carried_by_super(node: MetaData) -> bool: # module's re-exported reference to the base's own constant. Always emitted, even # when empty, so a consumer can read it unconditionally. lines.append(f"{upper}_COLUMNS_BY_FIELD: Final[dict[str, str]] = {{") - for name, _column in columns: + for key, member in sorted(columns): # _q, not a bare f-string: the KEY is an author-supplied field name, and every # other literal in this module goes through the escaper. Spliced raw, a name # holding a quote emitted a module that does not parse. - lines.append(f" {_q(name)}: {upper}_{_member(name)}_COLUMN,") + lines.append(f" {_q(key)}: {upper}_{member},") lines.append("}") lines.append("") return "\n".join(lines) diff --git a/server/python/tests/codegen/test_names_flattened.py b/server/python/tests/codegen/test_names_flattened.py new file mode 100644 index 0000000000..4b2e405a02 --- /dev/null +++ b/server/python/tests/codegen/test_names_flattened.py @@ -0,0 +1,95 @@ +"""A flattened value object has no column of its own: each member is a column of the +owning table, named by core naming (``resolve_flattened_column_name``). The names module +carries one ``___COLUMN`` constant per member and no ``_COLUMN`` for +the field itself, whose resolved column (``ship_to``) is not a column of the table. + +Mirrors the C# ``NamesGenerator``, the Java/Kotlin names generators and the TypeScript +``names.ts``; the corpus test runs the shared cross-port naming fixture. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +import metaobjects.core_types # noqa: F401 — side-effect: registers attr classes + +from metaobjects import FileSource, InMemoryStringSource, MetaDataFormat, MetaDataLoader +from metaobjects.codegen.generators.names_generator import render_names +from metaobjects.meta.core.object.meta_object import MetaObject +from metaobjects.naming import to_snake_case +from metaobjects.shared.base_types import TYPE_OBJECT + +REPO = Path(__file__).parents[4] +CORPUS = REPO / "fixtures" / "naming-conformance" / "physical-names" +_CASES: list[dict[str, object]] = json.loads((CORPUS / "cases.json").read_text())["cases"] + +_MODEL = { + "metadata.root": {"package": "acme::ship", "children": [ + {"object.value": {"name": "Address", "children": [ + {"field.string": {"name": "street"}}, + {"field.string": {"name": "postalCode", "@column": "ZIP"}}, + ]}}, + {"object.entity": {"name": "Shipment", "children": [ + {"source.rdb": {"@table": "shipments"}}, + {"field.long": {"name": "id"}}, + {"field.object": {"name": "shipTo", "@objectRef": "Address", "@storage": "flattened"}}, + {"field.object": {"name": "payload", "@objectRef": "Address"}}, + {"identity.primary": {"@fields": ["id"], "@generation": "increment"}}, + ]}}, + ]}, +} + + +def _object(root: MetaObject, name: str) -> MetaObject: + return next(c for c in root.children() if c.type == TYPE_OBJECT and c.name == name) + + +def _load(model: dict[str, object]) -> MetaObject: + result = MetaDataLoader().load( + [InMemoryStringSource(json.dumps(model), format=MetaDataFormat.JSON)] + ) + assert not result.errors, [e.message for e in result.errors] + return result.root + + +def test_a_flattened_member_gets_a_column_constant_and_its_field_gets_none() -> None: + src = render_names(_object(_load(_MODEL), "Shipment"), "snake_case") + + assert 'SHIPMENT_SHIP_TO_FIELD: Final[str] = "shipTo"' in src + assert 'SHIPMENT_SHIP_TO_STREET_COLUMN: Final[str] = "ship_to_street"' in src + assert 'SHIPMENT_SHIP_TO_POSTAL_CODE_COLUMN: Final[str] = "ship_to_ZIP"' in src + # The field's own resolved column, `ship_to`, is not a column of the table. + assert "SHIPMENT_SHIP_TO_COLUMN" not in src + assert '"ship_to"' not in src + # A jsonb object is one column, as before. + assert 'SHIPMENT_PAYLOAD_COLUMN: Final[str] = "payload"' in src + assert '"shipTo.street": SHIPMENT_SHIP_TO_STREET_COLUMN,' in src + assert '"shipTo.postalCode": SHIPMENT_SHIP_TO_POSTAL_CODE_COLUMN,' in src + assert '"shipTo":' not in src + + +def test_a_flattened_member_constant_colliding_with_a_field_constant_is_refused() -> None: + model = json.loads(json.dumps(_MODEL)) + shipment = model["metadata.root"]["children"][1]["object.entity"]["children"] + shipment[2]["field.object"]["@flattenedColumnPrefix"] = "st_" + shipment.insert(3, {"field.string": {"name": "shipToStreet"}}) + with pytest.raises(ValueError, match="SHIPMENT_SHIP_TO_STREET_COLUMN"): + render_names(_object(_load(model), "Shipment"), "snake_case") + + +@pytest.mark.parametrize("case", _CASES, ids=lambda c: c["name"]) +def test_every_flattened_column_in_the_naming_corpus_is_a_constant(case: dict[str, object]) -> None: + result = MetaDataLoader().load([FileSource(CORPUS / "meta.naming.json")]) + assert not result.errors, [e.message for e in result.errors] + naming = case["naming"] or {} + rule = naming.get("columns", "snake_case") # type: ignore[union-attr] + src = render_names(_object(result.root, "Shipment"), rule) + for key, column in case["columns"].items(): # type: ignore[union-attr] + parts = key.split(".") + if len(parts) != 3 or parts[0] != "Shipment": + continue + field, member = (to_snake_case(p).upper() for p in parts[1:]) + decl = f'SHIPMENT_{field}_{member}_COLUMN: Final[str] = "{column}"' + assert decl in src, f"{case['name']}: {decl}\n{src}" diff --git a/server/typescript/packages/codegen-ts/src/names.ts b/server/typescript/packages/codegen-ts/src/names.ts index 97aaebd97e..3f3b75d7cb 100644 --- a/server/typescript/packages/codegen-ts/src/names.ts +++ b/server/typescript/packages/codegen-ts/src/names.ts @@ -8,18 +8,25 @@ */ import { primaryRdbSource, + refTarget, resolveColumnName, + resolveFlattenedColumnName, resolveIndexName, resolveTableSchema, isMetaObject, isMetaSource, + FIELD_ATTR_OBJECT_REF, + FIELD_ATTR_STORAGE, + FIELD_SUBTYPE_OBJECT, PHYSICAL_NAME_ATTR_BY_KIND, SOURCE_ATTR_SCHEMA, SOURCE_ROLE_PRIMARY, + STORAGE_FLATTENED, TYPE_INDEX, TYPE_OBJECT, TYPE_SOURCE, type ColumnNamingStrategy, + type MetaField, type MetaObject, type MetaSource, } from "@metaobjectsdev/metadata"; @@ -28,7 +35,42 @@ import { crossEntitySpecifier } from "./import-path.js"; import type { RenderContext } from "./render-context.js"; import { effectivePackage } from "./docs-paths.js"; -export interface FieldNames { readonly name: string; readonly column: string; } +/** A field stored in one column. */ +export interface ColumnFieldNames { readonly name: string; readonly column: string; } + +/** + * A `@storage: "flattened"` value object: it has NO column of its own. Each member of the + * value object is a column of the owning table, named by core naming + * (`resolveFlattenedColumnName`, the function `meta migrate` names it with), keyed by the + * member's field name. There is deliberately no `column` here: the field's own resolved + * column (`ship_to`) does not exist in the database, so reading one is a compile error. + */ +export interface FlattenedFieldNames { + readonly name: string; + readonly members: Readonly>; +} + +export type FieldNames = ColumnFieldNames | FlattenedFieldNames; + +/** + * One field's names. The flattened test is migrate's own (`expected-schema.ts`): a + * `field.object` whose RESOLVED `@storage` is `flattened` (ADR-0039 — it may be inherited). + * A flattened field whose `@objectRef` does not resolve has no members; the loader refuses + * that model before codegen runs. + */ +function fieldNamesOf(f: MetaField, strategy: ColumnNamingStrategy | undefined): FieldNames { + if (f.subType === FIELD_SUBTYPE_OBJECT && f.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED) { + const target = refTarget(f, FIELD_ATTR_OBJECT_REF); + const members: Record = {}; + if (target !== undefined && isMetaObject(target)) { + for (const m of target.fields()) { + members[m.name] = { name: m.name, column: resolveFlattenedColumnName(f, m, strategy) }; + } + } + return { name: f.name, members }; + } + return { name: f.name, column: resolveColumnName(f, strategy) }; +} /** * One `source.rdb` child, under the ROLE it plays. @@ -325,12 +367,12 @@ export function resolveObjectNames( // ADR-0039: fields() is the RESOLVING accessor — inherited fields must appear, and an // inherited @column must resolve, or the constant disagrees with the DDL. for (const f of obj.fields()) { - fields[f.name] = { name: f.name, column: resolveColumnName(f, strategy) }; + fields[f.name] = fieldNamesOf(f, strategy); } // ADR-0039's sanctioned own-accessor use: what this artifact DECLARES. See ObjectNames. const ownFields: Record = {}; for (const f of ownFieldList) { - ownFields[f.name] = { name: f.name, column: resolveColumnName(f, strategy) }; + ownFields[f.name] = fieldNamesOf(f, strategy); } const superObj = namesArtifactSuperOf(obj); @@ -415,11 +457,11 @@ export function resolveSuperFragmentNames( const fields: Record = {}; for (const f of obj.fields()) { - fields[f.name] = { name: f.name, column: resolveColumnName(f, strategy) }; + fields[f.name] = fieldNamesOf(f, strategy); } const ownFields: Record = {}; for (const f of ownFieldList) { - ownFields[f.name] = { name: f.name, column: resolveColumnName(f, strategy) }; + ownFields[f.name] = fieldNamesOf(f, strategy); } const superObj = namesArtifactSuperOf(obj); return { @@ -624,7 +666,9 @@ export function columnExpr( literal: string, ): Code { const entry = names?.resolved.fields[fieldName]; - return names !== undefined && entry !== undefined + // A flattened field carries members, not a column (see FlattenedFieldNames): there is no + // constant to reference, so the caller's literal stands. + return names !== undefined && entry !== undefined && "column" in entry ? code`${names.symbol}.fields.${fieldName}.column` : code`${JSON.stringify(literal)}`; } diff --git a/server/typescript/packages/codegen-ts/src/templates/names-decl.ts b/server/typescript/packages/codegen-ts/src/templates/names-decl.ts index 97e192394a..8c3b5d05fd 100644 --- a/server/typescript/packages/codegen-ts/src/templates/names-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/names-decl.ts @@ -109,7 +109,12 @@ export function renderNamesDecl( }; const fieldsBlock = collection("fields", n.fields, n.ownFields, - (f: FieldNames) => `{ name: ${q(f.name)}, column: ${q(f.column)} }`); + (f: FieldNames) => "column" in f + ? `{ name: ${q(f.name)}, column: ${q(f.column)} }` + // A flattened value object: one column per member, and none of its own. + : `{ name: ${q(f.name)}, members: { ${Object.keys(f.members).sort() + .map((m) => `${key(m)}: { name: ${q(f.members[m]!.name)}, column: ${q(f.members[m]!.column)} }`) + .join(", ")} } }`); // `type` and `subType` on every entry, because the artifact mirrors the metadata tree // and because on these two collections the subType is the only thing that says whether diff --git a/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts b/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts index 8041c3f4dd..cbf50ada9d 100644 --- a/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts @@ -158,7 +158,7 @@ export function renderProjectionDecl( // normal, not a divergence — fall back to the literal, same as every other §A6 site. const namesEntry = names?.resolved.fields[f.name]; const dbColExpr: Code = - names !== undefined && namesEntry !== undefined + names !== undefined && namesEntry !== undefined && "column" in namesEntry ? code`${names.symbol}.fields.${f.name}.column` : code`${JSON.stringify(dbCol)}`; // #356 — a projection's descriptor is the same shape the entity descriptor emits, diff --git a/server/typescript/packages/codegen-ts/test/names-flattened.test.ts b/server/typescript/packages/codegen-ts/test/names-flattened.test.ts new file mode 100644 index 0000000000..a179f9f7ac --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/names-flattened.test.ts @@ -0,0 +1,110 @@ +// A flattened value object has no column of its own: each member is a column of the owning +// table, named by core naming (`resolveFlattenedColumnName`). The names artifact carries +// those columns under the field, and no `column` for the field itself, so code that needs a +// flattened column reads a constant instead of spelling it, and a lookup of the phantom +// `ship_to` column is a compile error rather than a query against a column that is not there. +// +// The corpus is the cross-port naming fixture: every `..` key in it is +// a flattened column, and the artifact must name each one exactly as `meta migrate` does, +// under every naming rule. + +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { + MetaDataLoader, + InMemoryStringSource, + isMetaRoot, + type ColumnNamingStrategy, + type MetaObject, + type MetaRoot, + type TableNamingRule, +} from "@metaobjectsdev/metadata"; +import { resolveObjectNames, type FieldNames } from "../src/names.js"; +import { renderNamesDecl } from "../src/templates/names-decl.js"; + +const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/naming-conformance/physical-names"); + +interface NamingCase { + name: string; + naming: { columns?: ColumnNamingStrategy; tables?: TableNamingRule } | null; + columns: Record; +} +const corpus = JSON.parse(readFileSync(join(CORPUS, "cases.json"), "utf8")) as { cases: NamingCase[] }; + +async function loadCorpusModel(c: NamingCase): Promise { + const result = await new MetaDataLoader().load([new FileSource(join(CORPUS, "meta.naming.json"))]); + expect(result.errors).toEqual([]); + if (!isMetaRoot(result.root)) throw new Error("not a root"); + result.root.physicalNaming = { + columns: c.naming?.columns ?? "snake_case", + tables: c.naming?.tables ?? "snake_case", + }; + return result.root; +} + +/** The column the artifact names for a corpus key, or undefined when it names none. */ +function artifactColumn(root: MetaRoot, key: string): string | undefined { + const [objectName, fieldName, memberName] = key.split(".") as [string, string, string | undefined]; + const names = resolveObjectNames(root.findObject(objectName) as MetaObject); + const entry: FieldNames | undefined = names?.fields[fieldName]; + if (entry === undefined) return undefined; + if (memberName === undefined) return "column" in entry ? entry.column : undefined; + return "members" in entry ? entry.members[memberName]?.column : undefined; +} + +describe("names artifact — flattened columns (cross-port naming corpus)", () => { + for (const c of corpus.cases) { + test(`${c.name}: every column in the corpus, flattened members included`, async () => { + const root = await loadCorpusModel(c); + const actual: Record = {}; + for (const key of Object.keys(c.columns)) actual[key] = artifactColumn(root, key); + expect(actual).toEqual(c.columns); + }); + } + + test("a flattened field names no column of its own", async () => { + const root = await loadCorpusModel(corpus.cases[0]!); + const names = resolveObjectNames(root.findObject("Shipment") as MetaObject); + for (const field of ["shipTo", "billTo", "returnTo", "giftTo", "homeTo"]) { + const entry = names?.fields[field]; + expect(entry).toBeDefined(); + expect("column" in entry!).toBe(false); + } + }); +}); + +describe("names artifact — rendered flattened members", () => { + const DOC = { + "metadata.root": { + package: "acme", + children: [ + { "object.value": { name: "Address", children: [ + { "field.string": { name: "street" } }, + { "field.string": { name: "postalCode", "@column": "ZIP" } }, + ] } }, + { "object.entity": { name: "Shipment", children: [ + { "source.rdb": { "@table": "shipments" } }, + { "field.long": { name: "id" } }, + { "field.object": { name: "shipTo", "@objectRef": "Address", "@storage": "flattened" } }, + { "field.object": { name: "payload", "@objectRef": "Address" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }, + ], + }, + }; + + test("members under the field, each with its column; a jsonb object keeps its one column", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(DOC))]); + expect(errors).toEqual([]); + const out = renderNamesDecl(root.findObject("Shipment") as MetaObject, { strategy: "snake_case" }); + + expect(out).toContain( + 'shipTo: { name: "shipTo", members: { postalCode: { name: "postalCode", column: "ship_to_ZIP" }, ' + + 'street: { name: "street", column: "ship_to_street" } } }', + ); + expect(out).toContain('payload: { name: "payload", column: "payload" }'); + expect(out).not.toContain('column: "ship_to"'); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/names.test.ts b/server/typescript/packages/codegen-ts/test/names.test.ts index 439513a281..384162de51 100644 --- a/server/typescript/packages/codegen-ts/test/names.test.ts +++ b/server/typescript/packages/codegen-ts/test/names.test.ts @@ -106,7 +106,7 @@ describe("resolveObjectNames", () => { }, ]); const n = resolveObjectNames(obj(root, "Thing"), "snake_case"); - expect(n?.fields.firstName?.column).toBe("given_name"); + expect(n?.fields.firstName).toEqual({ name: "firstName", column: "given_name" }); }); // A single role==="primary" source that happens to be READ-ONLY, beside a non-primary diff --git a/server/typescript/packages/test-generators/src/templates/projection-decl.ts b/server/typescript/packages/test-generators/src/templates/projection-decl.ts index e9ab1e45d2..ac90598b31 100644 --- a/server/typescript/packages/test-generators/src/templates/projection-decl.ts +++ b/server/typescript/packages/test-generators/src/templates/projection-decl.ts @@ -158,7 +158,7 @@ export function renderProjectionDecl( // normal, not a divergence — fall back to the literal, same as every other §A6 site. const namesEntry = names?.resolved.fields[f.name]; const dbColExpr: Code = - names !== undefined && namesEntry !== undefined + names !== undefined && namesEntry !== undefined && "column" in namesEntry ? code`${names.symbol}.fields.${f.name}.column` : code`${JSON.stringify(dbCol)}`; // #356 — a projection's descriptor is the same shape the entity descriptor emits, From d3b26b58f1141ba8e57c6f51f2b830cdd123d5f0 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 06:40:41 -0500 Subject: [PATCH 015/267] fix(names): flattened member constants are additive, and nothing breaks for owned copies Review fixes for the flattened-column constants: - The engine types keep their shape. A field's entry keeps its column (FieldNames / KotlinFieldNames.column stays non-null, the TS FieldNames is an interface again); flattened member columns are an optional `members` beside it. An owned copy of an older names generator therefore compiles and emits what it did. - The field's own column constants are emitted as before; the member constants are added beside them. - The C# EF mapping and the Kotlin Exposed table spell flattened columns as literals again: an owned older names generator does not emit the member constants, so referencing them would break that project's build. Both no-magic ledgers keep the flattened rows as known literals. - A member constant that would share its name with another constant is left out with a warning instead of refusing the model (C#, Java, Kotlin, Python), so every model that generated before still generates. - C# and Java: a names class no longer extends its base's when that would make a base constant that is not a column of its own table reachable through it (a flattened field redeclared as jsonb); it is emitted complete instead. - Docs: the audit drift signature no longer exempts flattened columns, the physical-names reference and field-types describe the additive shape, and the CHANGELOG entry is rewritten. Doc-comment order in CSharpNaming and the Python collision path fixed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 ++--- .../references/drift-signatures.md | 2 +- .../references/physical-names.md | 11 ++- docs/features/field-types.md | 3 +- .../codegen/templates/projection-decl.ts | 2 +- .../codegen/templates/projection-decl.ts | 2 +- .../references/drift-signatures.md | 2 +- .../references/physical-names.md | 11 ++- .../references/drift-signatures.md | 2 +- .../references/physical-names.md | 11 ++- .../references/drift-signatures.md | 2 +- .../references/physical-names.md | 11 ++- .../references/drift-signatures.md | 2 +- .../references/physical-names.md | 11 ++- .../references/drift-signatures.md | 2 +- .../references/physical-names.md | 11 ++- .../NamesGeneratorTests.cs | 84 ++++++++++++----- .../NamingConformanceTests.cs | 4 +- .../NoMagicPhysicalNamesTests.cs | 23 ++--- .../ObjectFieldCodegenTests.cs | 23 ++--- .../MetaObjects.Codegen/CSharpNaming.cs | 54 ++++------- .../Generators/DbContextGenerator.cs | 20 ++-- .../Generators/NamesGenerator.cs | 92 +++++++++++++++++-- .../kotlin/KotlinExposedTableGenerator.kt | 12 +-- .../generator/kotlin/KotlinGenUtil.kt | 19 ++-- .../generator/kotlin/KotlinNamesGenerator.kt | 43 ++++++++- .../kotlin/KotlinExposedTableGeneratorTest.kt | 10 +- .../kotlin/KotlinNamesGeneratorTest.kt | 22 +++-- .../kotlin/NoMagicPhysicalNamesTest.kt | 21 +++-- .../spring/SpringNamesGenerator.java | 92 ++++++++++++++++--- .../spring/SpringNamesGeneratorTest.java | 54 ++++++++--- .../codegen/generators/names_generator.py | 70 ++++++++++---- .../tests/codegen/test_names_flattened.py | 28 +++--- .../packages/codegen-ts/src/names.ts | 53 ++++++----- .../codegen-ts/src/templates/names-decl.ts | 8 +- .../src/templates/projection-decl.ts | 2 +- .../codegen-ts/test/names-flattened.test.ts | 25 +++-- .../packages/codegen-ts/test/names.test.ts | 2 +- .../src/templates/projection-decl.ts | 2 +- 39 files changed, 580 insertions(+), 292 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0fc3c83778..34406ebf68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,19 @@ here.** `meta migrate`, the Prisma schema, the C# EF mapping and the Kotlin Exposed tables all use it. Set on any other storage, it is refused at load (`ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE`). See `docs/features/field-types.md`, "Embedded value objects". +- **Names artifacts carry a flattened value object's member columns.** Each member of a + `@storage: "flattened"` value object is a column of the owning table, and the owner's names + artifact now has a constant for each, named by core naming: `fields.shipTo.members.street.column` + in TypeScript, `ShipToStreetColumn` in C#, `SHIP_TO_STREET_COLUMN` in Java and Kotlin, + `SHIPMENT_SHIP_TO_STREET_COLUMN` in Python, keyed `shipTo.street` in the column-by-field maps. + Additive: the field's own constants are unchanged (its column constant names no column of the + table, as before), the engine types gain only an optional member collection, and an owned + copy of an older names generator keeps compiling and emitting what it did. For that reason the + generated EF Core and Exposed bindings still spell these columns as literals. A member constant + that would share its name with another constant is left out with a warning, so every model + that generated before still generates. In C# and Java, a names class no longer extends its + base's when that would make a base constant that is not a column of its own table reachable + through it (a flattened field redeclared as jsonb, say); it is emitted complete instead. - **A `PascalCase` column rule.** `"naming": { "columns": "PascalCase" }` in `.metaobjects/config.json` upper-cases a field name's first letter and changes nothing else (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`), in every port: the column names EF Core @@ -60,17 +73,6 @@ here.** ### Changed -- **Names artifacts carry a flattened value object's columns, and no column for the field.** - Each member of a `@storage: "flattened"` value object is a column of the owning table, and the - owner's names artifact now has a constant for each: `fields.shipTo.members.street.column` in - TypeScript, `ShipToStreetColumn` in C#, `SHIP_TO_STREET_COLUMN` in Java and Kotlin, - `SHIPMENT_SHIP_TO_STREET_COLUMN` in Python, keyed `shipTo.street` in the column-by-field maps. - The C# EF mapping and the Kotlin Exposed tables reference them instead of spelling the column. - The field's own column constant is gone (`ShipToColumn`, `SHIP_TO_COLUMN`, `fields.shipTo.column`): - it named a column that does not exist, so code that read it now fails to compile instead of - querying a missing column. In TypeScript `FieldNames` is now a union, so code that reads - `.column` from an untyped entry narrows it first (`"column" in entry`). - - **Added vocabulary no longer moves `metamodelVersion`.** The metamodel spec version now moves only when metadata that loaded may stop loading or change meaning. A new type, subtype, optional attribute or enum member leaves it unchanged, and its CHANGELOG entry names it; the diff --git a/agent-context/skills/metaobjects-audit/references/drift-signatures.md b/agent-context/skills/metaobjects-audit/references/drift-signatures.md index 351893deb6..5148b26db4 100644 --- a/agent-context/skills/metaobjects-audit/references/drift-signatures.md +++ b/agent-context/skills/metaobjects-audit/references/drift-signatures.md @@ -35,7 +35,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. diff --git a/agent-context/skills/metaobjects-codegen/references/physical-names.md b/agent-context/skills/metaobjects-codegen/references/physical-names.md index d89ea51d9c..8cb815149b 100644 --- a/agent-context/skills/metaobjects-codegen/references/physical-names.md +++ b/agent-context/skills/metaobjects-codegen/references/physical-names.md @@ -93,7 +93,8 @@ artifact exists *for your code*, which is the only place a physical name appears `@storage: flattened` field has no column of its own: each member of the value object is a column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, else `_`, then the member's column). The artifact carries one constant per -member and none for the field, because the field's own resolved column does not exist: +member. The field's own column constant is still emitted, unchanged, but on a flattened +field it names no column of the table; read the member constants: | Port | Reads as | |---|---| @@ -103,8 +104,12 @@ member and none for the field, because the field's own resolved column does not | Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. -Without the artifact, compute the name with core naming's `resolveFlattenedColumnName` (or -its port equivalent), never by concatenating. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/docs/features/field-types.md b/docs/features/field-types.md index f1f574f7fd..3a17110090 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -295,7 +295,8 @@ columns through the same core function (`resolveFlattenedColumnName` and its per equivalents), so `meta migrate`, the Prisma schema, the C# EF mapping and the Kotlin Exposed tables agree, and the owning object's names artifact carries each one as a constant (`ShipmentNames.ShipToStreetColumn` in C#; see the codegen skill's physical-names reference -for every port). The field itself gets no column constant, because it has no column. On a +for every port). The field's own column constant is still emitted but names no column of the +table, so use the member constants. On a field whose `@storage` is not `flattened` the attribute is refused at load (`ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE`): no other storage gives the members columns of their own. diff --git a/examples/advanced-modeling/codegen/templates/projection-decl.ts b/examples/advanced-modeling/codegen/templates/projection-decl.ts index ac90598b31..e9ab1e45d2 100644 --- a/examples/advanced-modeling/codegen/templates/projection-decl.ts +++ b/examples/advanced-modeling/codegen/templates/projection-decl.ts @@ -158,7 +158,7 @@ export function renderProjectionDecl( // normal, not a divergence — fall back to the literal, same as every other §A6 site. const namesEntry = names?.resolved.fields[f.name]; const dbColExpr: Code = - names !== undefined && namesEntry !== undefined && "column" in namesEntry + names !== undefined && namesEntry !== undefined ? code`${names.symbol}.fields.${f.name}.column` : code`${JSON.stringify(dbCol)}`; // #356 — a projection's descriptor is the same shape the entity descriptor emits, diff --git a/examples/showcase/codegen/templates/projection-decl.ts b/examples/showcase/codegen/templates/projection-decl.ts index ac90598b31..e9ab1e45d2 100644 --- a/examples/showcase/codegen/templates/projection-decl.ts +++ b/examples/showcase/codegen/templates/projection-decl.ts @@ -158,7 +158,7 @@ export function renderProjectionDecl( // normal, not a divergence — fall back to the literal, same as every other §A6 site. const namesEntry = names?.resolved.fields[f.name]; const dbColExpr: Code = - names !== undefined && namesEntry !== undefined && "column" in namesEntry + names !== undefined && namesEntry !== undefined ? code`${names.symbol}.fields.${f.name}.column` : code`${JSON.stringify(dbCol)}`; // #356 — a projection's descriptor is the same shape the entity descriptor emits, diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md index 351893deb6..5148b26db4 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md @@ -35,7 +35,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index d89ea51d9c..8cb815149b 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -93,7 +93,8 @@ artifact exists *for your code*, which is the only place a physical name appears `@storage: flattened` field has no column of its own: each member of the value object is a column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, else `_`, then the member's column). The artifact carries one constant per -member and none for the field, because the field's own resolved column does not exist: +member. The field's own column constant is still emitted, unchanged, but on a flattened +field it names no column of the table; read the member constants: | Port | Reads as | |---|---| @@ -103,8 +104,12 @@ member and none for the field, because the field's own resolved column does not | Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. -Without the artifact, compute the name with core naming's `resolveFlattenedColumnName` (or -its port equivalent), never by concatenating. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md index 351893deb6..5148b26db4 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md @@ -35,7 +35,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index d89ea51d9c..8cb815149b 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -93,7 +93,8 @@ artifact exists *for your code*, which is the only place a physical name appears `@storage: flattened` field has no column of its own: each member of the value object is a column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, else `_`, then the member's column). The artifact carries one constant per -member and none for the field, because the field's own resolved column does not exist: +member. The field's own column constant is still emitted, unchanged, but on a flattened +field it names no column of the table; read the member constants: | Port | Reads as | |---|---| @@ -103,8 +104,12 @@ member and none for the field, because the field's own resolved column does not | Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. -Without the artifact, compute the name with core naming's `resolveFlattenedColumnName` (or -its port equivalent), never by concatenating. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md index 351893deb6..5148b26db4 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md @@ -35,7 +35,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index d89ea51d9c..8cb815149b 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -93,7 +93,8 @@ artifact exists *for your code*, which is the only place a physical name appears `@storage: flattened` field has no column of its own: each member of the value object is a column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, else `_`, then the member's column). The artifact carries one constant per -member and none for the field, because the field's own resolved column does not exist: +member. The field's own column constant is still emitted, unchanged, but on a flattened +field it names no column of the table; read the member constants: | Port | Reads as | |---|---| @@ -103,8 +104,12 @@ member and none for the field, because the field's own resolved column does not | Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. -Without the artifact, compute the name with core naming's `resolveFlattenedColumnName` (or -its port equivalent), never by concatenating. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md index 351893deb6..5148b26db4 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md @@ -35,7 +35,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index d89ea51d9c..8cb815149b 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -93,7 +93,8 @@ artifact exists *for your code*, which is the only place a physical name appears `@storage: flattened` field has no column of its own: each member of the value object is a column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, else `_`, then the member's column). The artifact carries one constant per -member and none for the field, because the field's own resolved column does not exist: +member. The field's own column constant is still emitted, unchanged, but on a flattened +field it names no column of the table; read the member constants: | Port | Reads as | |---|---| @@ -103,8 +104,12 @@ member and none for the field, because the field's own resolved column does not | Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. -Without the artifact, compute the name with core naming's `resolveFlattenedColumnName` (or -its port equivalent), never by concatenating. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md index 351893deb6..5148b26db4 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/drift-signatures.md @@ -35,7 +35,7 @@ Per finding: `file:line` → what → generated-equivalent exists? → recommend **Hunt from the declaration outward, never from code shapes inward.** (1) Build the value list from the generated artifacts, because they already carry every derived value after every transform — naming strategy, pluralized path, humanized label: read `Names` and, on TypeScript, the `.meta.ts` twin. Where the port emits no names artifact yet, derive the list from the metadata directly (`@table` / `@schema` / `@column`, else the naming strategy applied to the field name; `@values`; `@title`) and record the un-wired generator as the first finding (below). (2) Grep the non-generated tree once — code AND checked-in config, fixtures, YAML, JSON, `.env`, OpenAPI fragments — with an alternation of those VALUES as literals; distinctive values (`"email_address"`, `"/subscribers"`, `"edited_approved"`) score on the hit, generic ones (`"id"`, `"name"`, `255`) only by reading the consumer, never by count. This step is what finds the topic name, the index field, the `COPY` header and the flag key without knowing they exist. (3) Trace each hit to its CONSUMER and ask what that consumer matches it against. Matched against the schema, the generated route table, a generated wire shape or a generated label → the metadata owns it, apply the discriminator. Matched against something the app chose — its own page-route table, its own copy deck — → not owned, not this finding. (4) Only then run the shape greps — raw SQL, `fetch(` / `app.get(` / a `queryKey`, a hand validator — as the second pass, for what a value grep cannot see: a literal that has ALREADY drifted from the declared value, a concatenated or interpolated name, a case-transformed one. - **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a flattened value-object composite column belongs to no single field of either object; a relationship-synthesized FK column is derived, never declared; a write-through entity's replica view name is not in the artifact, which holds the PRIMARY source's. A hand-written repository that imports `Names` is the gold standard — call it out as good. + **Do not flag — one rule, and its consequences.** A literal is exempt when (a) it is resolved, not compared: a typed ORM handle (a Drizzle column object, an Exposed `Column`, an EF property, a Pydantic attribute), a typed property access (`row.email`, `form.input.email`), a typed filter object, an enum member narrowed by the generated union — rewriting any of these to `Subscriber.email.name` or a string lookup swaps a checked reference for an unchecked one and is a regression (the emitted `options: [...] as const` populates a dropdown; it does not replace checked literals); (b) the metadata does not OWN it — the value coincides with a derived one but the app may change it without the metadata being wrong: a client-side page route or link (``, ``) is a navigation URL the app chose, measured on an estate where all 11 apparent `$path` hits were exactly this and the true count was 0, and converting one couples the site's URL structure to the API's; likewise the deployment prefix of a fetch URL, which the constants surface deliberately does not carry — `/api` is supplied at runtime through the client provider's `baseUrl`, never frozen at `meta gen` — so `fetch("/api/subscribers")` decomposes into a prefix with no constant by design and a `/subscribers` that is `$path`; (c) no generated constant exists for it — next paragraph; (d) it sits where a constant cannot be imported or names something no single declaration owns: a `source.rdb` `@sql` body is metadata, fingerprinted precisely because it can reference nothing; a relationship-synthesized FK column is derived, never declared. (A flattened value object's member column and a write-through entity's replica view name are NOT exempt: the artifact carries both, as the field's member column constant and the source in role `replica`.) A hand-written repository that imports `Names` is the gold standard — call it out as good. **Score only where a constant actually exists.** A fact declared in the project's CODEGEN CONFIG rather than in metadata — a bespoke route mount path, a hand-chosen JSON envelope key — is genuinely spelled twice when a client re-types it, but no generated constant holds it. That is a GENERATOR GAP, reported as one, never a literal-site finding: never invent a constant that the emitters do not emit. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index d89ea51d9c..8cb815149b 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -93,7 +93,8 @@ artifact exists *for your code*, which is the only place a physical name appears `@storage: flattened` field has no column of its own: each member of the value object is a column of the owner's table, named by core naming (the field's `@flattenedColumnPrefix`, else `_`, then the member's column). The artifact carries one constant per -member and none for the field, because the field's own resolved column does not exist: +member. The field's own column constant is still emitted, unchanged, but on a flattened +field it names no column of the table; read the member constants: | Port | Reads as | |---|---| @@ -103,8 +104,12 @@ member and none for the field, because the field's own resolved column does not | Python | `SHIPMENT_SHIP_TO_STREET_COLUMN` | The column-by-field maps (`ColumnsByField`, `COLUMNS_BY_FIELD`) key these `shipTo.street`. -Without the artifact, compute the name with core naming's `resolveFlattenedColumnName` (or -its port equivalent), never by concatenating. +A member constant that would share its name with another constant (a field `shipToStreet` +beside a flattened `shipTo.street` with a custom prefix) is left out with a warning; rename +one to get it. The generated EF Core and Exposed bindings still spell these columns as +literals, because an owned copy of an older names generator does not emit the member +constants. Without the artifact, compute the name with core naming's +`resolveFlattenedColumnName` (or its port equivalent), never by concatenating. **But prefer a typed handle where one exists — this rule has a real limit.** If the ORM gives you a type-checked object for the same thing, use that. Replacing a Drizzle column diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs index fcd015c33f..15b9706ab2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs @@ -567,12 +567,15 @@ public void DbContext_ToView_and_ToJson_reference_the_name_constants() } [Fact] - public void Flattened_value_object_member_columns_are_the_owners_constants() + public void Flattened_value_object_nested_columns_keep_the_literal_a_genuine_lookup_miss() { // Address (object.value) has NO primary source (FR-024 value purity forbids - // one) and therefore NO
Names artifact at all. The flattened column is a - // column of the OWNER's table, so the owner's artifact carries it - // (CustomerNames.HomeAddressStreetColumn), and the DbContext references that. + // one) and therefore NO
Names artifact at all — CSharpNaming.ColumnRef + // misses unconditionally here, and the value it would need ("homeAddress_street", + // a PREFIXED composite) isn't even a bare physical name a names constant holds. + // This is the "a lookup miss is normal and keeps the literal" case, distinct from + // the divergence case below — ResolveObjectNames(Address) is never called (there + // is no primary source to resolve), so there is nothing to disagree with. const string model = """ { "metadata.root": { "package": "acme", "children": [ { "object.value": { "name": "Address", "children": [ @@ -589,9 +592,8 @@ public void Flattened_value_object_member_columns_are_the_owners_constants() var ctx = Ctx(Load(model), ColumnNamingStrategy.Literal); var dbContext = new DbContextGenerator().Generate(ctx).Single().Content; - Assert.Contains("HasColumnName(CustomerNames.HomeAddressStreetColumn);", dbContext); - Assert.DoesNotContain("HasColumnName(\"homeAddress_street\")", dbContext); - Assert.DoesNotContain(" AddressNames", dbContext); + Assert.Contains("HasColumnName(\"homeAddress_street\");", dbContext); + Assert.DoesNotContain("AddressNames", dbContext); } [Fact] @@ -902,40 +904,78 @@ public void GenConfig_IncludeNames_defaults_to_false_so_a_bare_config_falls_back """; [Fact] - public void A_flattened_member_gets_a_column_constant_and_its_field_gets_none() + public void A_flattened_member_gets_a_column_constant_beside_its_field_constants() { var content = new NamesGenerator().Generate(Ctx(Load(FlattenedModel))).Single(f => f.Path == "ShipmentNames.g.cs").Content; - Assert.Contains("public const string ShipToField = \"shipTo\";", content); Assert.Contains("public const string ShipToStreetColumn = \"ship_to_street\";", content); Assert.Contains("public const string ShipToPostalCodeColumn = \"ship_to_ZIP\";", content); - // The field's own resolved column, `ship_to`, is not a column of the table. - Assert.DoesNotContain("ShipToColumn", content); - Assert.DoesNotContain("\"ship_to\"", content); - // A jsonb object is one column, as before. + // The field's own constants are kept as they were, so nothing that reads them changes. + Assert.Contains("public const string ShipToField = \"shipTo\";", content); + Assert.Contains("public const string ShipToColumn = \"ship_to\";", content); Assert.Contains("public const string PayloadColumn = \"payload\";", content); + Assert.Contains("[\"shipTo\"] = ShipToColumn,", content); Assert.Contains("[\"shipTo.street\"] = ShipToStreetColumn,", content); Assert.Contains("[\"shipTo.postalCode\"] = ShipToPostalCodeColumn,", content); - Assert.DoesNotContain("[\"shipTo\"]", content); } [Fact] - public void A_flattened_member_constant_that_collides_with_a_field_constant_is_refused() + public void A_flattened_member_constant_that_collides_with_a_field_constant_is_left_out_with_a_warning() { var model = FlattenedModel.Replace( "\"@storage\": \"flattened\" }", "\"@storage\": \"flattened\", \"@flattenedColumnPrefix\": \"st_\" } },\n { \"field.string\": { \"name\": \"shipToStreet\" }"); - var ex = Assert.Throws(() => new NamesGenerator().Generate(Ctx(Load(model))).ToList()); - Assert.Contains("ShipToStreetColumn", ex.Message); + var warnings = new List(); + var root = Load(model); + var ctx = new GenContext + { + Entities = root.Objects(), Root = root, Warn = warnings.Add, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.SnakeCase, IncludeNames = true }, + }; + var content = new NamesGenerator().Generate(ctx).Single(f => f.Path == "ShipmentNames.g.cs").Content; + + // The field's constant wins; the model generates, as it did before member constants. + Assert.Contains("public const string ShipToStreetColumn = \"ship_to_street\";", content); + Assert.DoesNotContain("\"st_street\"", content); + Assert.Contains("public const string ShipToPostalCodeColumn = \"st_ZIP\";", content); + Assert.Contains(warnings, w => w.Contains("ShipToStreetColumn")); } [Fact] - public void DbContext_names_flattened_columns_through_the_constants() + public void DbContext_keeps_the_literal_flattened_columns() { - var root = Load(FlattenedModel); - var dbContext = new DbContextGenerator().Generate(Ctx(root)).Single().Content; + // An owned (ejected) names generator from before member constants does not emit them, + // so the EF mapping must not reference them. + var dbContext = new DbContextGenerator().Generate(Ctx(Load(FlattenedModel))).Single().Content; + + Assert.Contains("b.Property(p => p.Street).HasColumnName(\"ship_to_street\");", dbContext); + Assert.DoesNotContain("ShipToStreetColumn", dbContext); + } - Assert.Contains("b.Property(p => p.Street).HasColumnName(ShipmentNames.ShipToStreetColumn);", dbContext); - Assert.Contains("b.Property(p => p.PostalCode).HasColumnName(ShipmentNames.ShipToPostalCodeColumn);", dbContext); + [Fact] + public void A_child_that_redeclares_a_flattened_field_as_jsonb_does_not_inherit_its_member_constants() + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.value": { "name": "Address", "children": [ { "field.string": { "name": "street" } } ]}}, + { "object.entity": { "name": "Base", "abstract": true, "children": [ + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "flattened" } } + ]}}, + { "object.entity": { "name": "Order", "extends": "Base", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "jsonb" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + var files = new NamesGenerator().Generate(Ctx(Load(model))).ToList(); + var order = files.Single(f => f.Path == "OrderNames.g.cs").Content; + + // Extending BaseNames would make BaseNames.ShipToStreetColumn a member of OrderNames, + // naming a column `orders` does not have; the artifact is emitted complete instead. + Assert.Contains("public abstract class OrderNames\n", order.Replace("\r\n", "\n")); + Assert.DoesNotContain("ShipToStreetColumn", order); + Assert.Contains("public const string ShipToColumn = \"ship_to\";", order); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs index b97776a810..3755e1179f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamingConformanceTests.cs @@ -148,8 +148,7 @@ public void Resolves_every_table_and_column_name(string name) /// /// The names artifact names every column in the corpus the way the resolvers above do: a /// scalar field's Column, and each member of a flattened value object under its - /// field's Members. A flattened field itself has no column (Column is null), - /// because none exists in the database. + /// field's Members. /// [Theory] [MemberData(nameof(ValidCaseNames))] @@ -170,7 +169,6 @@ public void Names_artifact_carries_every_column(string name) Assert.Equal(expectedColumn, field.Column); continue; } - Assert.Null(field.Column); Assert.NotNull(field.Members); Assert.Equal(expectedColumn, field.Members![parts[2]].Column); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs index 5ab30a6050..4f68b80fdb 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NoMagicPhysicalNamesTests.cs @@ -106,7 +106,7 @@ private enum Reach // The two categories C# documents as literal-only, each reachable by this fixture. // FlatPrefix is deliberately NOT tracked on its own: under @storage: flattened the // field's "column" is not a column at all, only the prefix each member column is built - // from, so the names artifact names no column for the field and nothing references it. + // from, so there is nothing for a generator to reference it AS. private const string FlatPrefix = "zz_phys_col_pfx"; private const string VoMemberCol = "zz_phys_col_road"; // a member of the value object private const string FlatCol = FlatPrefix + "_" + VoMemberCol; // what EF is actually told @@ -178,14 +178,11 @@ private static readonly (string Literal, string ShouldUse, Reach Reach, string W (WtTable, "AccountNames.SourcePrimaryTable", Reach.Constant, ""), (WtId, "AccountNames.IdColumn", Reach.Constant, ""), - (FlatCol, "CustomerNames.AddressRoadColumn", Reach.Constant, - "Promoted from KnownLiteral. A flattened object.value's member column is a COMPOSITE " + - "(core naming: the field's prefix + the member's column), and the old reason it had no " + - "constant was true: the value object has no source and so no Names, and the owner's " + - "artifact carried one constant per FIELD. The owner's artifact now carries one constant " + - "per flattened MEMBER (Column), and the field itself carries none, since " + - "its own resolved column is not a column of the table. DbContextGenerator.OwnedTypeConfig " + - "references it."), + (FlatCol, "(no constant exists)", Reach.KnownLiteral, + "A flattened object.value's nested column is a COMPOSITE (owner field column + \"_\" + " + + "member column). The value object has no source and so no Names, and the owner's " + + "artifact carries one constant per FIELD, not per flattened member — there is no single " + + "constant to reference. DbContextGenerator.OwnedTypeConfig."), (WtView, "AccountNames.SourceReplicaView", Reach.Constant, "Promoted from KnownLiteral by the 0.25.0 restructure, and the row is kept with its history " + "because the OLD reason was true and specific: a write-through entity has TWO physical " + @@ -251,8 +248,12 @@ private static readonly (string Literal, string ShouldUse, Reach Reach, string W // scalar arm — so the bare literal must appear nowhere, and the exhaustive test convicts // it if the attribute ever comes back. Under @storage: flattened its physical column is // the composite below. - (FlatEnumCol, "CustomerNames.AddressMoodColumn", Reach.Constant, - "As FlatCol — the flattened value object's enum member. Promoted with it."), + (FlatEnumCol, "(no constant exists)", Reach.KnownLiteral, + "As FlatCol — the flattened value object's enum member, `_`, which DbContextGenerator.OwnedTypeConfig now names the way the scalar members " + + "are named (and migrate-ts's flattenObjectField names it), so the column EF binds is the " + + "one the migration creates. A composite of two names, one of which (the value object's " + + "member) has no constant anywhere — the same structural impossibility as FlatCol."), // --- an @isArray value-object column: the routes tier's raw-SQL null clear --------- // Composed against TaggerNames inside a compile-time-constant string (the identifiers diff --git a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs index 8d6799316c..06405ce5f3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs @@ -171,21 +171,22 @@ public void DbContext_configures_owned_types_flattened_and_json() var ctx = Ctx(Load()); var dbContext = new DbContextGenerator().Generate(ctx).Single().Content; - // Flattened: each member's column, named by core naming (prefix + member column), is a - // constant of the OWNING entity's names artifact — never of Address, which as an - // object.value has no source and no artifact. + // Flattened: per-property column names prefixed by the parent column. §A6 — + // NOT converted: Address (object.value) has no primary source and so no + // AddressNames artifact, and the prefixed name is a composite no single + // constant could hold anyway (a genuine lookup miss). Assert.Contains("modelBuilder.Entity().OwnsOne(x => x.HomeAddress, b =>", dbContext); - Assert.Contains("b.Property(p => p.Street).HasColumnName(CustomerNames.HomeAddressStreetColumn);", dbContext); - Assert.Contains("b.Property(p => p.City).HasColumnName(CustomerNames.HomeAddressCityColumn);", dbContext); + Assert.Contains("b.Property(p => p.Street).HasColumnName(\"homeAddress_street\");", dbContext); + Assert.Contains("b.Property(p => p.City).HasColumnName(\"homeAddress_city\");", dbContext); // The value object's ENUM members are flattened the same way — migrate-ts's // flattenObjectField prefixes EVERY nested member, and TS owns the schema — and carry // the same conversion an entity-level enum gets: string-backed → the member symbol in a // text column; @intValueMap → the declared integers. Before this, an enum member fell // through to EF's own defaults (`HomeAddress_Kind`, integer) and bound a column the // migration never created — measured against a real Postgres, not inferred. - Assert.Contains("b.Property(p => p.Kind).HasColumnName(CustomerNames.HomeAddressKindColumn).HasConversion();", dbContext); + Assert.Contains("b.Property(p => p.Kind).HasColumnName(\"homeAddress_kind\").HasConversion();", dbContext); Assert.Contains( - "b.Property(p => p.Grade).HasColumnName(CustomerNames.HomeAddressGradeColumn).HasConversion(v => v == Address.AddressGrade.LO ? 1 : 2, " + + "b.Property(p => p.Grade).HasColumnName(\"homeAddress_grade\").HasConversion(v => v == Address.AddressGrade.LO ? 1 : 2, " + "v => v == 1 ? Address.AddressGrade.LO : v == 2 ? Address.AddressGrade.HI : UnmappedEnumValue(v, \"grade\"));", dbContext); // ...and the fail-fast helper that converter names is declared, even though the ONLY @@ -269,13 +270,13 @@ public void DbContext_names_every_flattened_member_the_migration_creates() // A plain scalar member: the pre-existing rule, pinned here so the ordering of the // richer members below is anchored to something already known-correct. - Assert.Contains("b.Property(p => p.Handle).HasColumnName(CustomerNames.ProfileHandleColumn);", dbContext); + Assert.Contains("b.Property(p => p.Handle).HasColumnName(\"profile_handle\");", dbContext); // An ARRAY enum member. Native array column on the migrate side (text[] derived from // isArray), EF Core 8 primitive collection here, with the per-element conversion — // else the members persist as int ordinals inside the array. Assert.Contains( - "b.PrimitiveCollection(p => p.Roles).HasColumnName(CustomerNames.ProfileRolesColumn).ElementType().HasConversion();", + "b.PrimitiveCollection(p => p.Roles).HasColumnName(\"profile_roles\").ElementType().HasConversion();", dbContext); // A NESTED value object member: ONE json column at `_
` (migrate's @@ -286,7 +287,7 @@ public void DbContext_names_every_flattened_member_the_migration_creates() """ b.OwnsOne(p => p.Badge, nb => { - nb.ToJson(CustomerNames.ProfileBadgeColumn); + nb.ToJson("profile_badge"); nb.Property(p => p.Tier).HasConversion(); }); """, @@ -317,7 +318,7 @@ public void A_flattened_map_member_binds_its_prefixed_jsonb_column() // the shared helper. The VO value type is FULLY QUALIFIED — the DbContext's usings // cover entity namespaces only, and a value object is not an entity. Assert.Contains( - "b.Property(p => p.Prefs).HasColumnName(CustomerNames.ProfilePrefsColumn).HasColumnType(\"jsonb\")" + "b.Property(p => p.Prefs).HasColumnName(\"profile_prefs\").HasColumnType(\"jsonb\")" + ".HasConversion(MapJsonb.Converter()" + ", MapJsonb.Comparer());", dbContext); diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 5b9001497f..5ef4e0f22a 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -20,14 +20,16 @@ namespace MetaObjects.Codegen; /// /// Physical name + logical field name for one field (§A2/§A3 names artifact). -/// A @storage: "flattened" value object has NO column of its own: is null and names one column per member of the -/// value object, keyed by the member's field name, through core naming +/// is set only on a @storage: "flattened" value object, +/// and there it is the real column information: such a field has no column of its own, and +/// each member of the value object is a column of the owning table, named by core naming /// (, -/// the function meta migrate names them with). The field's own resolved column -/// (ship_to) does not exist in the database, so nothing here names it. +/// the function meta migrate names them with), keyed by the member's field name. +/// is kept unchanged from before existed, +/// so an owned copy of the names generator keeps compiling and emitting what it did; on a +/// flattened field it names no column of the table. /// -public sealed record FieldNames(string Name, string? Column, IReadOnlyDictionary? Members = null); +public sealed record FieldNames(string Name, string Column, IReadOnlyDictionary? Members = null); /// /// One source.rdb child, under the ROLE it plays. @@ -819,8 +821,10 @@ public static string SourceMemberName(string role, string member) => public static string KeyMemberName(string type, string keyName, string member) => Pascal(type) + PascalToken(keyName) + PascalToken(member); - /// One field member: EmailField / EmailColumn. See - /// for why this stays on . + /// The constant member naming a flattened member's column: ShipToStreetColumn. + public static string FlattenedColumnMemberName(string fieldName, string memberName) => + FieldMemberName(fieldName + Pascal(memberName), MEMBER_COLUMN); + /// /// One field's names. The flattened test is migrate's own: a field.object whose /// resolved @storage is flattened. A flattened field whose @objectRef @@ -828,21 +832,20 @@ public static string KeyMemberName(string type, string keyName, string member) = /// public static FieldNames FieldNamesOf(MetaField f, ColumnNamingStrategy strategy) { + var column = Column(f, strategy); if (f.SubType != FIELD_SUBTYPE_OBJECT || f.Storage != STORAGE_FLATTENED) - return new FieldNames(f.Name, Column(f, strategy)); + return new FieldNames(f.Name, column); var members = new Dictionary(StringComparer.Ordinal); if (NamingRefs.RefTarget(f, FIELD_ATTR_OBJECT_REF) is MetaObject vo) { foreach (var m in vo.Fields()) members[m.Name] = new FieldNames(m.Name, PhysicalNaming.ResolveFlattenedColumnName(f, m, strategy)); } - return new FieldNames(f.Name, null, members); + return new FieldNames(f.Name, column, members); } - /// The constant member naming a flattened member's column: ShipToStreetColumn. - public static string FlattenedColumnMemberName(string fieldName, string memberName) => - FieldMemberName(fieldName + Pascal(memberName), MEMBER_COLUMN); - + /// One field member: EmailField / EmailColumn. See + /// for why this stays on . public static string FieldMemberName(string fieldName, string member) => Pascal(fieldName) + Pascal(member); @@ -886,32 +889,11 @@ public static string FieldMemberName(string fieldName, string member) => public static string ColumnRef(MetaObject owner, MetaField field, ColumnNamingStrategy strategy, bool includeNames) { var names = includeNames ? ResolveObjectNames(owner, strategy) : null; - // A flattened field names no column (FieldNames.Column is null): the literal stands. - return names is not null && names.Fields.TryGetValue(field.Name, out var entry) && entry.Column is not null + return names is not null && names.Fields.ContainsKey(field.Name) ? $"{NamesClassName(owner)}.{FieldMemberName(field.Name, MEMBER_COLUMN)}" : $"\"{Column(field, strategy)}\""; } - /// - /// §A6 for a flattened value object's member: the <Owner>Names.<Field><Member>Column - /// constant when the names generator is in this run and the owner's artifact names - /// that member, the core-naming literal (quoted) otherwise — the same presence rule as - /// . - /// - public static string FlattenedColumnRef( - MetaObject owner, - MetaField field, - MetaField member, - ColumnNamingStrategy strategy, - bool includeNames) - { - var names = includeNames ? ResolveObjectNames(owner, strategy) : null; - return names is not null && names.Fields.TryGetValue(field.Name, out var entry) - && entry.Members is { } members && members.ContainsKey(member.Name) - ? $"{NamesClassName(owner)}.{FlattenedColumnMemberName(field.Name, member.Name)}" - : $"\"{PhysicalNaming.ResolveFlattenedColumnName(field, member, strategy)}\""; - } - /// /// I1/§A6 — the <Owner>Names.Source<Role><Alias> constant reference for 's physical table/view/proc name, when BOTH C1 ( s var sb = new StringBuilder(); sb.AppendLine($" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b =>"); sb.AppendLine(" {"); - // A6 -- each member's column is a constant of the OWNING entity's names artifact - // (`Names.Column`), never of the value object's: `vo` carries - // no source (FR-024 value purity), so it has no artifact, and the column belongs to - // the owner's table anyway. CSharpNaming.FlattenedColumnRef falls back to the - // core-naming literal when the names generator is not in the run. + // A6 -- NOT converted, on two independent grounds. `vo` (object.value) never + // carries a source (FR-024 value purity), so it has no Names artifact at + // all — CSharpNaming.ColumnRef would miss on every nf, always. And even with + // one, nestedCol is a COMPOSITE string (prefix + column), not the bare physical + // name a names constant holds — there is no single constant this could reference. // // Every member the migration flattens must be named here, in the value object's // declaration order. migrate's `flattenObjectField` (expected-schema.ts) iterates @@ -1205,7 +1205,6 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s foreach (var nf in vo.Fields()) { var nestedColAny = PhysicalNaming.ResolveFlattenedColumnName(field, nf, strategy); - var nestedColRef = CSharpNaming.FlattenedColumnRef(entity, field, nf, strategy, ctx.Config.IncludeNames); // An ARRAY enum: migrate gives it a native array column (subtypeToSqlType derives // text[] from isArray), and EF Core 8 maps it as a primitive collection. Same @@ -1214,7 +1213,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s if (nf.SubType == FIELD_SUBTYPE_ENUM && nf.ResolvedIsArray()) { sb.AppendLine($" b.PrimitiveCollection(p => p.{CSharpNaming.Pascal(nf.Name)})" - + $".HasColumnName({nestedColRef}).ElementType()" + + $".HasColumnName(\"{nestedColAny}\").ElementType()" + $".{EnumConversionCall(ValueObjectNames.TypeName(vo, ctx.Root), vo, nf, ctx.Config)};"); continue; } @@ -1230,7 +1229,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s var ownsCall = nf.ResolvedIsArray() ? "OwnsMany" : "OwnsOne"; sb.AppendLine($" b.{ownsCall}(p => p.{CSharpNaming.Pascal(nf.Name)}, nb =>"); sb.AppendLine(" {"); - sb.AppendLine($" nb.ToJson({nestedColRef});"); + sb.AppendLine($" nb.ToJson(\"{nestedColAny}\");"); // `nb`, not `b` — the nested builder shadows the outer one, and emitting `b.` // here would compile-fail the GENERATED file (the outer builder is out of the // nested lambda's intended scope and names the wrong entity type anyway). @@ -1249,7 +1248,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s if (nf.SubType == FIELD_SUBTYPE_MAP) { sb.AppendLine($" b.Property(p => p.{CSharpNaming.Pascal(nf.Name)})" - + $".HasColumnName({nestedColRef})" + MapJsonbSuffix(vo, nf, ctx) + ";"); + + $".HasColumnName(\"{nestedColAny}\")" + MapJsonbSuffix(vo, nf, ctx) + ";"); continue; } @@ -1264,10 +1263,11 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s + "mapping here, so EF will bind its own default name instead. See KNOWN_GAPS.md."); continue; } + var nestedCol = nestedColAny; // The enum type nests in the value object's class (EntityGenerator's // EmitValueObjectPoco), so the VO is the `owner` the conversion qualifies it by. var conversion = isEnum ? $".{EnumConversionCall(ValueObjectNames.TypeName(vo, ctx.Root), vo, nf, ctx.Config)}" : ""; - sb.AppendLine($" b.Property(p => p.{CSharpNaming.Pascal(nf.Name)}).HasColumnName({nestedColRef}){conversion};"); + sb.AppendLine($" b.Property(p => p.{CSharpNaming.Pascal(nf.Name)}).HasColumnName(\"{nestedCol}\"){conversion};"); } sb.Append(" });"); return sb.ToString(); diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index 8e5d7d464a..f4563b7ce0 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -121,6 +121,7 @@ private static Member Str(string name, string value, string nodePath) => /// private static List> MemberGroups(ObjectNames n, bool ownOnly) { + var skipped = CollidingFlattenedMembers(n); var groups = new List>(); // The object's own identity. `Name` is the METAMODEL name — it held the physical name @@ -158,11 +159,16 @@ private static List> MemberGroups(ObjectNames n, bool ownOnly) { var path = $"field \"{f.Name}\""; fieldMembers.Add(Str(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_FIELD), f.Name, path)); - if (f.Column is not null) - fieldMembers.Add(Str(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN), f.Column, path)); - // A flattened value object: one constant per member's column, none for the field. - foreach (var m in (f.Members ?? new Dictionary()).Values.OrderBy(v => v.Name, StringComparer.Ordinal)) - fieldMembers.Add(Str(CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name), m.Column!, $"field \"{f.Name}.{m.Name}\"")); + fieldMembers.Add(Str(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN), f.Column, path)); + // A flattened value object: one constant per member's column, beside the field's own + // (kept as it always was, so nothing that reads it changes). A member constant that + // would collide with another constant is not emitted; see CollidingFlattenedMembers. + foreach (var m in FlattenedMembers(f)) + { + var memberName = CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name); + if (!skipped.Contains(memberName)) + fieldMembers.Add(Str(memberName, m.Column, $"field \"{f.Name}.{m.Name}\"")); + } } groups.Add(fieldMembers); @@ -189,6 +195,55 @@ private static List> MemberGroups(ObjectNames n, bool ownOnly) return groups; } + private static IEnumerable FlattenedMembers(FieldNames f) => + (f.Members ?? new Dictionary()).Values.OrderBy(v => v.Name, StringComparer.Ordinal); + + /// + /// The flattened-member constants of that would share a name with + /// another constant of the same artifact — a field shipToStreet beside the member + /// street of a flattened shipTo. They are left out, with a warning, rather than + /// refused: such a model generated before member constants existed, and every other + /// constant it had is still emitted. Computed over the WHOLE resolved member set, so an + /// artifact and its base agree about what is skipped. + /// + private static HashSet CollidingFlattenedMembers(ObjectNames n) + { + var taken = new HashSet(StringComparer.Ordinal) + { + CSharpNaming.Pascal(CSharpNaming.MEMBER_TYPE), + CSharpNaming.Pascal(CSharpNaming.MEMBER_SUB_TYPE), + CSharpNaming.Pascal(CSharpNaming.MEMBER_NAME), + }; + foreach (var (role, src) in n.Sources) + { + taken.Add(CSharpNaming.SourceMemberName(role, CSharpNaming.MEMBER_TYPE)); + taken.Add(CSharpNaming.SourceMemberName(role, CSharpNaming.MEMBER_SUB_TYPE)); + taken.Add(CSharpNaming.SourceMemberName(role, CSharpNaming.MEMBER_KIND)); + taken.Add(CSharpNaming.SourceMemberName(role, SOURCE_ATTR_SCHEMA)); + if (src.PhysicalNameAlias is { } alias) taken.Add(CSharpNaming.SourceMemberName(role, alias)); + } + foreach (var f in n.Fields.Values) + { + taken.Add(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_FIELD)); + taken.Add(CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)); + } + foreach (var k in n.Identities.Values.Concat(n.Indexes.Values)) + { + foreach (var member in new[] { CSharpNaming.MEMBER_TYPE, CSharpNaming.MEMBER_SUB_TYPE, CSharpNaming.MEMBER_NAME, CSharpNaming.MEMBER_INDEX }) + taken.Add(CSharpNaming.KeyMemberName(k.Type, k.Name, member)); + } + var skipped = new HashSet(StringComparer.Ordinal); + foreach (var f in n.Fields.Values.OrderBy(v => v.Name, StringComparer.Ordinal)) + { + foreach (var m in FlattenedMembers(f)) + { + var name = CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name); + if (!taken.Add(name)) skipped.Add(name); + } + } + return skipped; + } + /// /// The member names this artifact's BASE CLASS CHAIN already declares — what a member /// emitted here would HIDE, so it is emitted with new. @@ -253,7 +308,22 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra byMember[m.Name] = m.NodePath; } + foreach (var member in CollidingFlattenedMembers(names).OrderBy(m => m, StringComparer.Ordinal)) + ctx.Warn($"names: {entity.Name}: the flattened column constant \"{member}\" would share its name " + + "with another constant of the artifact, so it is not emitted. Rename the field or the " + + "value-object member to get it."); + + // C# class inheritance makes every base constant a member of this class too. When this + // object resolves a field differently from its base (a flattened field redeclared as + // jsonb, say), a base constant can name a column this table does not have; then the + // artifact is emitted complete, with no base, rather than inheriting it. var inherited = InheritedMembers(entity, strategy); + var full = MemberGroups(names, ownOnly: false).SelectMany(g => g).Select(m => m.Name).ToHashSet(StringComparer.Ordinal); + if (superCls is not null && !inherited.IsSubsetOf(full)) + { + superCls = null; + inherited = []; + } var groups = MemberGroups(names, ownOnly: superCls is not null); var sb = new StringBuilder(); @@ -296,13 +366,17 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra var hides = superCls is null ? "" : "new "; sb.AppendLine($" public static {hides}readonly Dictionary ColumnsByField = new(System.StringComparer.Ordinal)"); sb.AppendLine(" {"); + var skippedMembers = CollidingFlattenedMembers(names); foreach (var f in names.Fields.Values.OrderBy(v => v.Name, StringComparer.Ordinal)) { - if (f.Column is not null) - sb.AppendLine($" [\"{f.Name}\"] = {CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)},"); + sb.AppendLine($" [\"{f.Name}\"] = {CSharpNaming.FieldMemberName(f.Name, CSharpNaming.MEMBER_COLUMN)},"); // A flattened member is keyed `.`, the path the naming corpus uses. - foreach (var m in (f.Members ?? new Dictionary()).Values.OrderBy(v => v.Name, StringComparer.Ordinal)) - sb.AppendLine($" [\"{f.Name}.{m.Name}\"] = {CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name)},"); + foreach (var m in FlattenedMembers(f)) + { + var memberName = CSharpNaming.FlattenedColumnMemberName(f.Name, m.Name); + if (!skippedMembers.Contains(memberName)) + sb.AppendLine($" [\"{f.Name}.{m.Name}\"] = {memberName},"); + } } sb.AppendLine(" };"); sb.AppendLine("}"); diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 7f03156170..4fb21db319 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -1337,14 +1337,10 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBaseNames` carries it as - // `__COLUMN` (KotlinNamesGenerator, from the same - // ColumnNaming.resolveFlattened); the literal only without the names artifact. - val colExpr = if (bindsThroughNames(entity)) { - val (_, shortName) = PackageMapping.splitFqn(entity.name) - "${KotlinNaming.namesObjectName(shortName)}.${KotlinNaming.flattenedColumnMember(parentName, subField.name)}" - } else "\"$colName\"" - val baseSpec = KotlinTypeMapper.exposedColumnSpec(subField, colExpr, api) + // Task 6 — out of scope: this composite name belongs to neither a + // single field of `entity` nor of `target` — Names has no + // constant for it. Always literal; useNames() does not reach here. + val baseSpec = KotlinTypeMapper.exposedColumnSpec(subField, "\"$colName\"", api) // Sub-column is nullable iff the parent is nullable OR the sub-field itself is. val nullable = parentNullable || !KotlinGenUtil.isRequiredField(subField) val full = if (nullable) "$baseSpec.nullable()" else baseSpec diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt index a18e1b648a..d3f9623a01 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt @@ -217,15 +217,17 @@ public object KotlinGenUtil { /** * §A2/§A3 — physical name + logical field name for one field. * - * A `@storage: "flattened"` value object has NO column of its own: [column] is null and - * [members] names one column per member of the value object, keyed by the member's field - * name, through core naming ([ColumnNaming.resolveFlattened], the rule `meta migrate` - * names them by). The field's own resolved column (`ship_to`) does not exist in the - * database, so nothing here names it. + * [members] is set only on a `@storage: "flattened"` value object, and there it is the + * real column information: such a field has no column of its own, and each member of the + * value object is a column of the owning table, named by core naming + * ([ColumnNaming.resolveFlattened], the rule `meta migrate` names them by), keyed by the + * member's field name. [column] is kept as it always was, so an owned copy of the names + * generator keeps compiling and emitting what it did; on a flattened field it names no + * column of the table. */ data class KotlinFieldNames( val name: String, - val column: String?, + val column: String, val members: Map? = null, ) @@ -469,11 +471,12 @@ public object KotlinGenUtil { private fun fieldNamesOf(f: MetaField<*>, strategy: String): KotlinFieldNames { val flattened = f is ObjectField && f.hasMetaAttr(ObjectField.ATTR_STORAGE, true) && ObjectField.STORAGE_FLATTENED == f.getMetaAttr(ObjectField.ATTR_STORAGE, true).valueAsString - if (!flattened) return KotlinFieldNames(f.name, resolveColumnName(f, strategy)) + val column = resolveColumnName(f, strategy) + if (!flattened) return KotlinFieldNames(f.name, column) val target = (f as ObjectField).objectRef val members = target?.metaFields.orEmpty() .associate { m -> m.name to KotlinFieldNames(m.name, ColumnNaming.resolveFlattened(f, m, strategy)) } - return KotlinFieldNames(f.name, null, members) + return KotlinFieldNames(f.name, column, members) } /** diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt index 1613e13b8b..0740c07b8f 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt @@ -4,6 +4,7 @@ package com.metaobjects.generator.kotlin // com.metaobjects.generator.kotlin when this generator is copied out via // `mvn metaobjects:eject` and its own package is renamed — an explicit import, not // same-package bare-name resolution, is what keeps the ejected copy compiling. +import org.slf4j.LoggerFactory import com.metaobjects.generator.kotlin.KotlinGenUtil import com.metaobjects.generator.kotlin.KotlinNaming import com.metaobjects.generator.kotlin.PackageMapping @@ -148,8 +149,23 @@ open class KotlinNamesGenerator : val value: String, val path: String, val section: String, + /** A flattened value object's member column: left out, not refused, when it collides. */ + val flattened: Boolean = false, ) + /** + * The flattened-member constants of [names] that would share a name with another + * constant of the same object — a field `shipToStreet` beside the member `street` of a + * flattened `shipTo`. They are left out, with a warning, rather than refused: such a model + * generated before member constants existed, and every other constant it had is still + * emitted. Computed over the WHOLE resolved set, so an object and its base agree. + */ + protected fun collidingFlattenedMembers(names: KotlinGenUtil.KotlinObjectNames): Set { + val raw = rawMembersOf(names, all = true) + val taken = raw.filter { !it.flattened }.mapTo(mutableSetOf()) { it.member } + return raw.filter { it.flattened && !taken.add(it.member) }.mapTo(sortedSetOf()) { it.member } + } + /** @return true when a file was written. */ protected open fun emit( entity: MetaObject, @@ -181,6 +197,11 @@ open class KotlinNamesGenerator : val resolved = membersOf(names, all = true) val own = membersOf(names, all = false) + for (skipped in collidingFlattenedMembers(names)) { + LOG.warn("names: {}: the flattened column constant {} would share its name with another " + + "constant of the object, so it is not emitted. Rename the field or the value-object " + + "member to get it.", entity.name, skipped) + } // Two nodes whose SCREAMING_SNAKE member forms collide would emit duplicate const // members. Kotlin would refuse to compile it, but the error would name a generated @@ -235,10 +256,13 @@ open class KotlinNamesGenerator : // lookup surface, and a miss on an inherited field is exactly the // fallback-to-literal this artifact removes. append("\n val COLUMNS_BY_FIELD: Map = mapOf(\n") + val skippedMembers = collidingFlattenedMembers(names) val rows = names.fields.values.flatMap { f -> - (if (f.column != null) listOf(f.name to "${KotlinNaming.namesMember(f.name)}_COLUMN") else emptyList()) + + listOf(f.name to "${KotlinNaming.namesMember(f.name)}_COLUMN") + // A flattened member is keyed `.`, the path the naming corpus uses. - f.members.orEmpty().values.map { m -> "${f.name}.${m.name}" to KotlinNaming.flattenedColumnMember(f.name, m.name) } + f.members.orEmpty().values + .map { m -> "${f.name}.${m.name}" to KotlinNaming.flattenedColumnMember(f.name, m.name) } + .filter { (_, constant) -> constant !in skippedMembers } }.sortedBy { it.first } for ((key, constant) in rows) { append(" \"$key\" to $constant,\n") @@ -265,6 +289,11 @@ open class KotlinNamesGenerator : * are re-exported, with no `inheritsSource` flag needed to say so. */ protected fun membersOf(names: KotlinGenUtil.KotlinObjectNames, all: Boolean): List { + val skipped = collidingFlattenedMembers(names) + return rawMembersOf(names, all).filterNot { it.flattened && it.member in skipped } + } + + private fun rawMembersOf(names: KotlinGenUtil.KotlinObjectNames, all: Boolean): List { val out = mutableListOf() val self = names.name out += NameConst("TYPE", names.type, self, "self") @@ -300,10 +329,10 @@ open class KotlinNamesGenerator : val member = KotlinNaming.namesMember(f.name) val path = "$self.fields.${f.name}" out += NameConst("${member}_FIELD", f.name, path, "fields") - f.column?.let { out += NameConst("${member}_COLUMN", it, path, "fields") } - // A flattened value object: one constant per member's column, none for the field. + out += NameConst("${member}_COLUMN", f.column, path, "fields") + // A flattened value object: one constant per member's column, beside the field's own. for (m in f.members.orEmpty().values.sortedBy { it.name }) { - out += NameConst(KotlinNaming.flattenedColumnMember(f.name, m.name), m.column!!, "$path.${m.name}", "fields") + out += NameConst(KotlinNaming.flattenedColumnMember(f.name, m.name), m.column, "$path.${m.name}", "fields", flattened = true) } } @@ -357,4 +386,8 @@ open class KotlinNamesGenerator : PackageMapping.splitFqn(md.name).first.replace('.', '/') override fun getSingleOutputFilename(md: MetaObject): String = KotlinNaming.namesObjectName(PackageMapping.splitFqn(md.name).second) + ".kt" + + private companion object { + val LOG = LoggerFactory.getLogger(KotlinNamesGenerator::class.java) + } } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt index cb55fef69a..c69915b6f6 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt @@ -291,7 +291,7 @@ class KotlinExposedTableGeneratorTest { } } - @Test fun flattenedColumnsReferenceTheNamesConstants() { + @Test fun flattenedColumnsKeepTheirLiteralWithTheNamesArtifactInTheRun() { val outDir = Files.createTempDirectory("ktbl-flat-names-") try { val model = """{ @@ -312,9 +312,11 @@ class KotlinExposedTableGeneratorTest { gen.execute(loadString("flat-names", model)) val src = Files.readString(outDir.resolve("acme/demo/UserTable.kt")) - assertTrue("val workStreet = text(UserNames.WORK_STREET_COLUMN)" in src, - "expected the flattened column through its names constant; saw:\n$src") - assertFalse("\"office_street\"" in src, "the literal must not be spelled; saw:\n$src") + // An owned (ejected) names generator from before member constants does not emit + // UserNames.WORK_STREET_COLUMN, so the table must not reference it. + assertTrue("val workStreet = text(\"office_street\")" in src, + "expected the flattened column's literal; saw:\n$src") + assertFalse("WORK_STREET_COLUMN" in src, "saw:\n$src") } finally { outDir.toFile().deleteRecursively() } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt index d3437659f9..bc3230a525 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt @@ -546,29 +546,31 @@ class KotlinNamesGeneratorTest { ] } }""".trimIndent() - @Test fun `a flattened member gets a column constant and its field gets none`() { + @Test fun `a flattened member gets a column constant beside its field constants`() { val src = emit(flattenedModel).getValue("acme/ship/ShipmentNames.kt") - assertTrue("const val SHIP_TO_FIELD: String = \"shipTo\"" in src, src) assertTrue("const val SHIP_TO_STREET_COLUMN: String = \"ship_to_street\"" in src, src) assertTrue("const val SHIP_TO_POSTAL_CODE_COLUMN: String = \"ship_to_ZIP\"" in src, src) - // The field's own resolved column, `ship_to`, is not a column of the table. - assertFalse("SHIP_TO_COLUMN" in src, src) - assertFalse("\"ship_to\"" in src, src) - // A jsonb object is one column, as before. + // The field's own constants are kept as they were, so nothing that reads them changes. + assertTrue("const val SHIP_TO_FIELD: String = \"shipTo\"" in src, src) + assertTrue("const val SHIP_TO_COLUMN: String = \"ship_to\"" in src, src) assertTrue("const val PAYLOAD_COLUMN: String = \"payload\"" in src, src) + assertTrue("\"shipTo\" to SHIP_TO_COLUMN" in src, src) assertTrue("\"shipTo.street\" to SHIP_TO_STREET_COLUMN" in src, src) assertTrue("\"shipTo.postalCode\" to SHIP_TO_POSTAL_CODE_COLUMN" in src, src) - assertFalse("\"shipTo\" to" in src, src) } - @Test fun `a flattened member constant colliding with a field constant is refused`() { + @Test fun `a flattened member constant colliding with a field constant is left out`() { val model = flattenedModel.replace( "\"@storage\": \"flattened\" }", "\"@storage\": \"flattened\", \"@flattenedColumnPrefix\": \"st_\" } },\n" + " { \"field.string\": { \"name\": \"shipToStreet\" }") - val ex = assertFailsWith { emit(model) } - assertTrue("SHIP_TO_STREET_COLUMN" in ex.message.orEmpty(), ex.message) + val src = emit(model).getValue("acme/ship/ShipmentNames.kt") + + // The field's constant wins; the model generates, as it did before member constants. + assertTrue("const val SHIP_TO_STREET_COLUMN: String = \"ship_to_street\"" in src, src) + assertFalse("\"st_street\"" in src, src) + assertTrue("const val SHIP_TO_POSTAL_CODE_COLUMN: String = \"st_ZIP\"" in src, src) } /** The cross-port naming corpus: every `..` key is a constant, under every rule. */ diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt index 803726e84d..f80bdcc651 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/NoMagicPhysicalNamesTest.kt @@ -37,10 +37,12 @@ import kotlin.test.assertTrue * gate is only ever as wide as its fixture, so treat the model below as the load-bearing * part of this file and add to it whenever a generator grows a new path. * - * This port has ZERO ESCAPE and ZERO KNOWN_LITERAL rows. Every row that left — the replica - * view, the two index names, and last the FLATTENED `object.value`'s member column — left - * because `Names` grew the member it was pinned as lacking, which is what a - * self-extinguishing ledger row is for. + * As of 0.25.0 this port has ZERO ESCAPE and ZERO KNOWN_LITERAL rows but one, and the one + * that remains is genuinely structural rather than undone: a FLATTENED `object.value`'s + * nested column is a composite the artifact has no single member for. The three rows that + * left — the replica view and the two index names — left because `Names` grew the + * members they were pinned as lacking, which is what a self-extinguishing ledger row is + * for. * * Every token carries its REACH — see [Reach]. Every non-[Reach.CONSTANT] value is PINNED, * not exempted: the gate asserts the condition it names is still true, so the day a @@ -172,12 +174,11 @@ class NoMagicPhysicalNamesTest { Token(colFk, "OrderNames.CUSTOMER_ID_COLUMN"), Token(jsonbCol, "CustomerNames.PROFILE_COLUMN"), Token( - flatCol, "CustomerNames.ADDRESS_ROAD_COLUMN", Reach.CONSTANT, - "Promoted from KNOWN_LITERAL. A flattened object.value's member column is a COMPOSITE " + - "(core naming: the field's prefix + the member's column), and the old reason it had " + - "no constant was true: the value object has no source and so no Names, and the " + - "owner's artifact carried one constant per FIELD. It now carries one per flattened " + - "MEMBER (__COLUMN), and the Exposed table references it.", + flatCol, "(no constant exists)", Reach.KNOWN_LITERAL, + "A flattened object.value's nested column is a COMPOSITE (owner field column + \"_\" + " + + "member column). The value object has no source (FR-024 value purity) and so no " + + "Names, and the owner's artifact carries one constant per FIELD, not per " + + "flattened member — there is no single constant to reference.", ), Token(view, "CustomerSummaryNames.SOURCE_PRIMARY_VIEW"), // The write-through entity's TWO physical names, each under the member for the role diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java index 6bc71092ce..1ecf76b3a8 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java @@ -113,6 +113,8 @@ public class SpringNamesGenerator extends MultiFileDirectGeneratorBase implements EmitsPhysicalNameConstants { + private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(SpringNamesGenerator.class); + @Override protected Class getFilterClass() { return MetaObject.class; @@ -166,12 +168,13 @@ public void execute(MetaDataLoader loader) { /** Physical name + logical field name for one field. */ /** - * One field's names. A {@code @storage: "flattened"} value object has NO column of its own: - * {@code column} is null and {@code members} names one column per member of the value - * object, keyed by the member's field name, through core naming - * ({@link ColumnNaming#resolveFlattened(MetaField, MetaField, String)}, the rule - * {@code meta migrate} names them by). The field's own resolved column ({@code ship_to}) - * does not exist in the database, so nothing here names it. + * One field's names. {@code members} is set only on a {@code @storage: "flattened"} value + * object, and there it is the real column information: such a field has no column of its + * own, and each member of the value object is a column of the owning table, named by core + * naming ({@link ColumnNaming#resolveFlattened(MetaField, MetaField, String)}, the rule + * {@code meta migrate} names them by), keyed by the member's field name. {@code column} is + * kept as it always was, so the {@code _COLUMN} constant code already reads is unchanged; + * on a flattened field it names no column of the table. */ private record FieldNames(String name, String column, Map members) { FieldNames(String name, String column) { this(name, column, null); } @@ -366,6 +369,7 @@ private static FieldNames fieldNamesOf(MetaField field, String strategy) { field.getMetaAttr(ObjectField.ATTR_STORAGE, true).getValueAsString())) { return new FieldNames(field.getName(), ColumnNaming.resolve(field, strategy)); } + String column = ColumnNaming.resolve(field, strategy); Map members = new LinkedHashMap<>(); MetaObject target = ((ObjectField) field).getObjectRef(); if (target != null) { @@ -374,7 +378,7 @@ private static FieldNames fieldNamesOf(MetaField field, String strategy) { ColumnNaming.resolveFlattened(field, member, strategy))); } } - return new FieldNames(field.getName(), null, members); + return new FieldNames(field.getName(), column, members); } /** The constant naming a flattened member's column: {@code SHIP_TO_STREET_COLUMN}. */ @@ -480,10 +484,32 @@ static String namesMember(String name) { * one blank line between the object's own identity, its sources, its fields, its * identities and its indexes. It is never read as data.

*/ - private record Member(String member, String literal, String path, String section) {} + private record Member(String member, String literal, String path, String section, boolean flattened) {} private static Member str(String member, String value, String path, String section) { - return new Member(member, "\"" + value + "\"", path, section); + return new Member(member, "\"" + value + "\"", path, section, false); + } + + /** A flattened value object's member column: left out, not refused, when it collides. */ + private static Member flattenedStr(String member, String value, String path) { + return new Member(member, "\"" + value + "\"", path, "fields", true); + } + + /** + * The flattened-member constants of {@code names} that would share a name with another + * constant of the same class — a field {@code shipToStreet} beside the member + * {@code street} of a flattened {@code shipTo}. They are left out, with a warning, rather + * than refused: such a model generated before member constants existed, and every other + * constant it had is still emitted. Computed over the WHOLE resolved set, so a class and + * its base agree about what is skipped. + */ + private static Set collidingFlattenedMembers(ObjectNames names) { + Set taken = new HashSet<>(); + Set skipped = new java.util.TreeSet<>(); + List all = rawMembersOf(names, true); + for (Member m : all) if (!m.flattened()) taken.add(m.member()); + for (Member m : all) if (m.flattened() && !taken.add(m.member())) skipped.add(m.member()); + return skipped; } /** @return true when a file was written. */ @@ -502,6 +528,29 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean ? null : SpringNaming.namesName(SpringNaming.splitFqn(names.superObject().getName())[1]); + for (String skipped : collidingFlattenedMembers(names)) { + LOG.warn("names: {}: the flattened column constant {} would share its name with another " + + "constant of the class, so it is not emitted. Rename the field or the value-object " + + "member to get it.", entity.getName(), skipped); + } + + // Java static inheritance makes every base constant reachable through this class too. + // When this object resolves a field differently from its base (a flattened field + // redeclared as jsonb, say), a base constant can name a column this table does not + // have; then the class is emitted complete, with no base, rather than inheriting it. + if (superClass != null) { + MetaObject sup = names.superObject(); + ObjectNames supNames = resolveObjectNames(sup, strategy); + if (supNames == null) supNames = resolveSuperFragmentNames(sup, strategy); + if (supNames != null) { + Set own = new HashSet<>(); + for (Member m : membersOf(names, true)) own.add(m.member()); + for (Member m : membersOf(supNames, true)) { + if (!own.contains(m.member())) { superClass = null; break; } + } + } + } + // Two nodes whose SCREAMING_SNAKE member forms collide would emit duplicate // constants. javac would refuse to compile the file, but the error would name a // generated .java and read as a codegen bug rather than a model one. Fail here, @@ -569,13 +618,17 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean // artifact removes. It repeats no LITERAL: an inherited entry's value is the base's // own constant, reached through Java's static-member inheritance. Hiding the base's // field of the same name is what makes Names.COLUMNS_BY_FIELD the complete one. + Set skippedMembers = collidingFlattenedMembers(names); List allRows = new ArrayList<>(); for (FieldNames f : names.fields().values()) { - if (f.column() != null) allRows.add(new String[] { namesMember(f.name()) + "_COLUMN", f.name() }); + allRows.add(new String[] { namesMember(f.name()) + "_COLUMN", f.name() }); // A flattened member is keyed `.`, the path the naming corpus uses. if (f.members() != null) { for (FieldNames m : f.members().values()) { - allRows.add(new String[] { flattenedColumnMember(f.name(), m.name()), f.name() + "." + m.name() }); + String constant = flattenedColumnMember(f.name(), m.name()); + if (!skippedMembers.contains(constant)) { + allRows.add(new String[] { constant, f.name() + "." + m.name() }); + } } } } @@ -620,6 +673,15 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean * are what a consumer reaches.

*/ private static List membersOf(ObjectNames names, boolean all) { + Set skipped = collidingFlattenedMembers(names); + List out = new ArrayList<>(); + for (Member m : rawMembersOf(names, all)) { + if (!(m.flattened() && skipped.contains(m.member()))) out.add(m); + } + return out; + } + + private static List rawMembersOf(ObjectNames names, boolean all) { List out = new ArrayList<>(); String self = names.name(); out.add(str("TYPE", names.type(), self, "self")); @@ -650,13 +712,13 @@ private static List membersOf(ObjectNames names, boolean all) { String member = namesMember(f.name()); String path = self + ".fields." + f.name(); out.add(str(member + "_FIELD", f.name(), path, "fields")); - if (f.column() != null) out.add(str(member + "_COLUMN", f.column(), path, "fields")); - // A flattened value object: one constant per member's column, none for the field. + out.add(str(member + "_COLUMN", f.column(), path, "fields")); + // A flattened value object: one constant per member's column, beside the field's own. if (f.members() != null) { for (String m : sorted(f.members())) { FieldNames mn = f.members().get(m); - out.add(str(flattenedColumnMember(f.name(), mn.name()), mn.column(), - path + "." + mn.name(), "fields")); + out.add(flattenedStr(flattenedColumnMember(f.name(), mn.name()), mn.column(), + path + "." + mn.name())); } } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java index 0cebf9298a..f9883443fb 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringNamesGeneratorTest.java @@ -737,34 +737,60 @@ private void compileAll(Path root) throws Exception { }"""; @Test - public void aFlattenedMemberGetsAColumnConstantAndItsFieldGetsNone() throws IOException { + public void aFlattenedMemberGetsAColumnConstantBesideItsFieldConstants() throws IOException { String src = emit(FLATTENED_FIXTURE, "acme/ship/ShipmentNames.java", Map.of()); - assertTrue(src, src.contains("public static final String SHIP_TO_FIELD = \"shipTo\";")); assertTrue(src, src.contains("public static final String SHIP_TO_STREET_COLUMN = \"ship_to_street\";")); assertTrue(src, src.contains("public static final String SHIP_TO_POSTAL_CODE_COLUMN = \"ship_to_ZIP\";")); - // The field's own resolved column, `ship_to`, is not a column of the table. - assertFalse(src, src.contains("SHIP_TO_COLUMN")); - assertFalse(src, src.contains("\"ship_to\"")); - // A jsonb object is one column, as before. + // The field's own constants are kept as they were, so nothing that reads them changes. + assertTrue(src, src.contains("public static final String SHIP_TO_FIELD = \"shipTo\";")); + assertTrue(src, src.contains("public static final String SHIP_TO_COLUMN = \"ship_to\";")); assertTrue(src, src.contains("public static final String PAYLOAD_COLUMN = \"payload\";")); + assertTrue(src, src.contains("Map.entry(\"shipTo\", SHIP_TO_COLUMN)")); assertTrue(src, src.contains("Map.entry(\"shipTo.street\", SHIP_TO_STREET_COLUMN)")); assertTrue(src, src.contains("Map.entry(\"shipTo.postalCode\", SHIP_TO_POSTAL_CODE_COLUMN)")); - assertFalse(src, src.contains("Map.entry(\"shipTo\",")); } @Test - public void aFlattenedMemberConstantCollidingWithAFieldConstantIsRefused() { + public void aFlattenedMemberConstantCollidingWithAFieldConstantIsLeftOut() throws IOException { String model = FLATTENED_FIXTURE.replace( "\"@storage\": \"flattened\" }", "\"@storage\": \"flattened\", \"@flattenedColumnPrefix\": \"st_\" } },\n" + " { \"field.string\": { \"name\": \"shipToStreet\" }"); - try { - emit(model, "acme/ship/ShipmentNames.java", Map.of()); - fail("expected the SHIP_TO_STREET_COLUMN collision to be refused"); - } catch (GeneratorException | IOException e) { - assertTrue(e.getMessage(), e.getMessage().contains("SHIP_TO_STREET_COLUMN")); - } + String src = emit(model, "acme/ship/ShipmentNames.java", Map.of()); + + // The field's constant wins; the model generates, as it did before member constants. + assertTrue(src, src.contains("public static final String SHIP_TO_STREET_COLUMN = \"ship_to_street\";")); + assertFalse(src, src.contains("\"st_street\"")); + assertTrue(src, src.contains("public static final String SHIP_TO_POSTAL_CODE_COLUMN = \"st_ZIP\";")); + } + + @Test + public void aChildThatRedeclaresAFlattenedFieldAsJsonbDoesNotInheritItsMemberConstants() throws IOException { + String model = """ + { + "metadata.root": { "package": "acme::ship", "children": [ + { "object.value": { "name": "Address", "children": [ + { "field.string": { "name": "street" } } + ] } }, + { "object.entity": { "name": "Base", "abstract": true, "children": [ + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "flattened" } } + ] } }, + { "object.entity": { "name": "Order", "extends": "acme::ship::Base", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "shipTo", "@objectRef": "Address", "@storage": "jsonb" } }, + { "identity.primary": { "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + }"""; + String src = emit(model, "acme/ship/OrderNames.java", Map.of()); + + // Extending BaseNames would make BaseNames.SHIP_TO_STREET_COLUMN reachable as + // OrderNames.SHIP_TO_STREET_COLUMN, naming a column `orders` does not have. + assertTrue(src, src.contains("public abstract class OrderNames {")); + assertFalse(src, src.contains("SHIP_TO_STREET_COLUMN")); + assertTrue(src, src.contains("public static final String SHIP_TO_COLUMN = \"ship_to\";")); } /** diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index b15f6549d3..046653c1c5 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -75,6 +75,8 @@ """ from __future__ import annotations +from collections.abc import Callable + import re from dataclasses import dataclass @@ -264,15 +266,21 @@ def _flattened_members(field: MetaData, strategy: str) -> list[tuple[str, str]] return [(m.name, resolve_flattened_column_name(field, m, strategy)) for m in target.fields()] -def _flattened_consts(field: MetaData, members: list[tuple[str, str]]) -> list[_Const]: - """A flattened value object: the field's ``_FIELD`` name, one ``__COLUMN`` - per member, and NO ``_COLUMN`` for the field — its own resolved column (``ship_to``) is - not a column of the table.""" +def _flattened_member_consts( + field: MetaData, members: list[tuple[str, str]] +) -> list[tuple[str, _Const]]: + """A flattened value object's ``__COLUMN`` constants, one per member, + emitted beside the field's own ``_FIELD``/``_COLUMN`` pair (kept as it always was, so + nothing that imports it changes; on a flattened field ``_COLUMN`` names no column of the + table).""" member = _member(field.name) - out = [_Const(f"{member}_FIELD", _q(field.name), f"field {field.name!r}")] - for name, column in sorted(members): - out.append(_Const(f"{member}_{_member(name)}_COLUMN", _q(column), f"field {field.name}.{name!r}")) - return out + return [ + ( + f"{field.name}.{name}", + _Const(f"{member}_{_member(name)}_COLUMN", _q(column), f"field {field.name + '.' + name!r}"), + ) + for name, column in sorted(members) + ] #: The node types a names module carries. A frozenset of module-level constants rather @@ -377,7 +385,13 @@ def _sources_by_role(entity: MetaObject) -> dict[str, MetaSource]: return out -def render_names(entity: MetaObject, strategy: str, *, fragment: bool = False) -> str | None: +def render_names( + entity: MetaObject, + strategy: str, + *, + fragment: bool = False, + warn: Callable[[str], None] | None = None, +) -> str | None: """Render the names module for ``entity``, or ``None`` when it declares (and inherits) no primary ``source.rdb`` at all (#248). @@ -444,16 +458,36 @@ def carried_by_super(node: MetaData) -> bool: # (COLUMNS_BY_FIELD key, constant member) — a flattened member is keyed # `.`, the path the naming corpus uses. columns: list[tuple[str, str]] = [] + flattened: list[tuple[MetaData, list[tuple[str, _Const]]]] = [] for field in sorted(entity.fields(), key=lambda f: f.name): + column = resolve_column_name(field, strategy) + columns.append((field.name, f"{_member(field.name)}_COLUMN")) + groups.append(("fields", _field_consts(field, column), carried_by_super(field))) members = _flattened_members(field, strategy) - if members is None: - column = resolve_column_name(field, strategy) - columns.append((field.name, f"{_member(field.name)}_COLUMN")) - groups.append(("fields", _field_consts(field, column), carried_by_super(field))) - continue - for name, _column in members: - columns.append((f"{field.name}.{name}", f"{_member(field.name)}_{_member(name)}_COLUMN")) - groups.append(("fields", _flattened_consts(field, members), carried_by_super(field))) + if members: + flattened.append((field, _flattened_member_consts(field, members))) + + # A flattened member's constant that would share a name with another constant — a field + # `shipToStreet` beside the member `street` of a flattened `shipTo` — is left out, with a + # warning, rather than refused: such a model generated before member constants existed, + # and every other constant it had is still emitted. + taken = {c.member for _s, consts, _i in groups for c in consts} + for field, consts in flattened: + kept = [] + for key, const in consts: + if const.member in taken: + if warn is not None: + warn( + f"names: {entity.name}: the flattened column constant {upper}_{const.member} " + "would share its name with another constant of the module, so it is not " + "emitted. Rename the field or the value-object member to get it." + ) + continue + taken.add(const.member) + kept.append(const) + columns.append((key, const.member)) + if kept: + groups.append(("fields", kept, carried_by_super(field))) for type_name in (TYPE_IDENTITY, TYPE_INDEX): keys = sorted( @@ -553,7 +587,7 @@ def generate(self, ctx: GenContext) -> list[EmittedFile]: emitted: set[str] = set() def one(entity: MetaObject, *, fragment: bool) -> list[EmittedFile]: - source = render_names(entity, ctx.config.column_naming, fragment=fragment) + source = render_names(entity, ctx.config.column_naming, fragment=fragment, warn=ctx.warn) if source is None: return [] emitted.add(entity.resolution_key()) diff --git a/server/python/tests/codegen/test_names_flattened.py b/server/python/tests/codegen/test_names_flattened.py index 4b2e405a02..f08e7ab350 100644 --- a/server/python/tests/codegen/test_names_flattened.py +++ b/server/python/tests/codegen/test_names_flattened.py @@ -1,7 +1,7 @@ """A flattened value object has no column of its own: each member is a column of the owning table, named by core naming (``resolve_flattened_column_name``). The names module -carries one ``___COLUMN`` constant per member and no ``_COLUMN`` for -the field itself, whose resolved column (``ship_to``) is not a column of the table. +carries one ``___COLUMN`` constant per member, beside the field's own +``_FIELD``/``_COLUMN`` pair, which is kept as it was so nothing that imports it changes. Mirrors the C# ``NamesGenerator``, the Java/Kotlin names generators and the TypeScript ``names.ts``; the corpus test runs the shared cross-port naming fixture. @@ -54,29 +54,33 @@ def _load(model: dict[str, object]) -> MetaObject: return result.root -def test_a_flattened_member_gets_a_column_constant_and_its_field_gets_none() -> None: +def test_a_flattened_member_gets_a_column_constant_beside_its_field_constants() -> None: src = render_names(_object(_load(_MODEL), "Shipment"), "snake_case") - assert 'SHIPMENT_SHIP_TO_FIELD: Final[str] = "shipTo"' in src assert 'SHIPMENT_SHIP_TO_STREET_COLUMN: Final[str] = "ship_to_street"' in src assert 'SHIPMENT_SHIP_TO_POSTAL_CODE_COLUMN: Final[str] = "ship_to_ZIP"' in src - # The field's own resolved column, `ship_to`, is not a column of the table. - assert "SHIPMENT_SHIP_TO_COLUMN" not in src - assert '"ship_to"' not in src - # A jsonb object is one column, as before. + # The field's own constants are kept as they were, so nothing that imports them changes. + assert 'SHIPMENT_SHIP_TO_FIELD: Final[str] = "shipTo"' in src + assert 'SHIPMENT_SHIP_TO_COLUMN: Final[str] = "ship_to"' in src assert 'SHIPMENT_PAYLOAD_COLUMN: Final[str] = "payload"' in src + assert '"shipTo": SHIPMENT_SHIP_TO_COLUMN,' in src assert '"shipTo.street": SHIPMENT_SHIP_TO_STREET_COLUMN,' in src assert '"shipTo.postalCode": SHIPMENT_SHIP_TO_POSTAL_CODE_COLUMN,' in src - assert '"shipTo":' not in src -def test_a_flattened_member_constant_colliding_with_a_field_constant_is_refused() -> None: +def test_a_flattened_member_constant_colliding_with_a_field_constant_is_left_out_with_a_warning() -> None: model = json.loads(json.dumps(_MODEL)) shipment = model["metadata.root"]["children"][1]["object.entity"]["children"] shipment[2]["field.object"]["@flattenedColumnPrefix"] = "st_" shipment.insert(3, {"field.string": {"name": "shipToStreet"}}) - with pytest.raises(ValueError, match="SHIPMENT_SHIP_TO_STREET_COLUMN"): - render_names(_object(_load(model), "Shipment"), "snake_case") + warnings: list[str] = [] + src = render_names(_object(_load(model), "Shipment"), "snake_case", warn=warnings.append) + + # The field's constant wins; the model generates, as it did before member constants. + assert 'SHIPMENT_SHIP_TO_STREET_COLUMN: Final[str] = "ship_to_street"' in src + assert '"st_street"' not in src + assert 'SHIPMENT_SHIP_TO_POSTAL_CODE_COLUMN: Final[str] = "st_ZIP"' in src + assert any("SHIPMENT_SHIP_TO_STREET_COLUMN" in w for w in warnings) @pytest.mark.parametrize("case", _CASES, ids=lambda c: c["name"]) diff --git a/server/typescript/packages/codegen-ts/src/names.ts b/server/typescript/packages/codegen-ts/src/names.ts index 3f3b75d7cb..e5afa42dc5 100644 --- a/server/typescript/packages/codegen-ts/src/names.ts +++ b/server/typescript/packages/codegen-ts/src/names.ts @@ -35,41 +35,42 @@ import { crossEntitySpecifier } from "./import-path.js"; import type { RenderContext } from "./render-context.js"; import { effectivePackage } from "./docs-paths.js"; -/** A field stored in one column. */ -export interface ColumnFieldNames { readonly name: string; readonly column: string; } - /** - * A `@storage: "flattened"` value object: it has NO column of its own. Each member of the - * value object is a column of the owning table, named by core naming + * One field's names. `column` is the field's resolved column. + * + * `members` is present only on a `@storage: "flattened"` value object, and there it is the + * only real column information: such a field has no column of its own, and each member of + * the value object is a column of the owning table, named by core naming * (`resolveFlattenedColumnName`, the function `meta migrate` names it with), keyed by the - * member's field name. There is deliberately no `column` here: the field's own resolved - * column (`ship_to`) does not exist in the database, so reading one is a compile error. + * member's field name. Its `column` is kept, unchanged from before `members` existed, so + * code that already reads it — an owned copy of this artifact's renderer included — keeps + * compiling; on a flattened field it names no column of the table, so read `members`. */ -export interface FlattenedFieldNames { +export interface FieldNames { readonly name: string; - readonly members: Readonly>; + readonly column: string; + readonly members?: Readonly> | undefined; } -export type FieldNames = ColumnFieldNames | FlattenedFieldNames; - /** - * One field's names. The flattened test is migrate's own (`expected-schema.ts`): a - * `field.object` whose RESOLVED `@storage` is `flattened` (ADR-0039 — it may be inherited). - * A flattened field whose `@objectRef` does not resolve has no members; the loader refuses - * that model before codegen runs. + * The flattened test is migrate's own (`expected-schema.ts`): a `field.object` whose + * RESOLVED `@storage` is `flattened` (ADR-0039 — it may be inherited). A flattened field + * whose `@objectRef` does not resolve has no members; the loader refuses that model before + * codegen runs. */ function fieldNamesOf(f: MetaField, strategy: ColumnNamingStrategy | undefined): FieldNames { - if (f.subType === FIELD_SUBTYPE_OBJECT && f.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED) { - const target = refTarget(f, FIELD_ATTR_OBJECT_REF); - const members: Record = {}; - if (target !== undefined && isMetaObject(target)) { - for (const m of target.fields()) { - members[m.name] = { name: m.name, column: resolveFlattenedColumnName(f, m, strategy) }; - } + const column = resolveColumnName(f, strategy); + if (f.subType !== FIELD_SUBTYPE_OBJECT || f.attr(FIELD_ATTR_STORAGE) !== STORAGE_FLATTENED) { + return { name: f.name, column }; + } + const target = refTarget(f, FIELD_ATTR_OBJECT_REF); + const members: Record = {}; + if (target !== undefined && isMetaObject(target)) { + for (const m of target.fields()) { + members[m.name] = { name: m.name, column: resolveFlattenedColumnName(f, m, strategy) }; } - return { name: f.name, members }; } - return { name: f.name, column: resolveColumnName(f, strategy) }; + return { name: f.name, column, members }; } /** @@ -666,9 +667,7 @@ export function columnExpr( literal: string, ): Code { const entry = names?.resolved.fields[fieldName]; - // A flattened field carries members, not a column (see FlattenedFieldNames): there is no - // constant to reference, so the caller's literal stands. - return names !== undefined && entry !== undefined && "column" in entry + return names !== undefined && entry !== undefined ? code`${names.symbol}.fields.${fieldName}.column` : code`${JSON.stringify(literal)}`; } diff --git a/server/typescript/packages/codegen-ts/src/templates/names-decl.ts b/server/typescript/packages/codegen-ts/src/templates/names-decl.ts index 8c3b5d05fd..0a6a2797bf 100644 --- a/server/typescript/packages/codegen-ts/src/templates/names-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/names-decl.ts @@ -109,11 +109,11 @@ export function renderNamesDecl( }; const fieldsBlock = collection("fields", n.fields, n.ownFields, - (f: FieldNames) => "column" in f + (f: FieldNames) => f.members === undefined ? `{ name: ${q(f.name)}, column: ${q(f.column)} }` - // A flattened value object: one column per member, and none of its own. - : `{ name: ${q(f.name)}, members: { ${Object.keys(f.members).sort() - .map((m) => `${key(m)}: { name: ${q(f.members[m]!.name)}, column: ${q(f.members[m]!.column)} }`) + // A flattened value object: each member's column, beside the field's own entry. + : `{ name: ${q(f.name)}, column: ${q(f.column)}, members: { ${Object.keys(f.members).sort() + .map((m) => `${key(m)}: { name: ${q(f.members![m]!.name)}, column: ${q(f.members![m]!.column)} }`) .join(", ")} } }`); // `type` and `subType` on every entry, because the artifact mirrors the metadata tree diff --git a/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts b/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts index cbf50ada9d..8041c3f4dd 100644 --- a/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts +++ b/server/typescript/packages/codegen-ts/src/templates/projection-decl.ts @@ -158,7 +158,7 @@ export function renderProjectionDecl( // normal, not a divergence — fall back to the literal, same as every other §A6 site. const namesEntry = names?.resolved.fields[f.name]; const dbColExpr: Code = - names !== undefined && namesEntry !== undefined && "column" in namesEntry + names !== undefined && namesEntry !== undefined ? code`${names.symbol}.fields.${f.name}.column` : code`${JSON.stringify(dbCol)}`; // #356 — a projection's descriptor is the same shape the entity descriptor emits, diff --git a/server/typescript/packages/codegen-ts/test/names-flattened.test.ts b/server/typescript/packages/codegen-ts/test/names-flattened.test.ts index a179f9f7ac..78621bd701 100644 --- a/server/typescript/packages/codegen-ts/test/names-flattened.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-flattened.test.ts @@ -1,8 +1,8 @@ // A flattened value object has no column of its own: each member is a column of the owning // table, named by core naming (`resolveFlattenedColumnName`). The names artifact carries -// those columns under the field, and no `column` for the field itself, so code that needs a -// flattened column reads a constant instead of spelling it, and a lookup of the phantom -// `ship_to` column is a compile error rather than a query against a column that is not there. +// those columns under the field's `members`, so code that needs a flattened column reads a +// constant instead of spelling it. The field's own entry is unchanged (its `column` is kept +// for code that already reads it), so the addition breaks nothing. // // The corpus is the cross-port naming fixture: every `..` key in it is // a flattened column, and the artifact must name each one exactly as `meta migrate` does, @@ -50,8 +50,8 @@ function artifactColumn(root: MetaRoot, key: string): string | undefined { const names = resolveObjectNames(root.findObject(objectName) as MetaObject); const entry: FieldNames | undefined = names?.fields[fieldName]; if (entry === undefined) return undefined; - if (memberName === undefined) return "column" in entry ? entry.column : undefined; - return "members" in entry ? entry.members[memberName]?.column : undefined; + if (memberName === undefined) return entry.column; + return entry.members?.[memberName]?.column; } describe("names artifact — flattened columns (cross-port naming corpus)", () => { @@ -64,14 +64,12 @@ describe("names artifact — flattened columns (cross-port naming corpus)", () = }); } - test("a flattened field names no column of its own", async () => { + test("a flattened field keeps its own entry, unchanged, and gains members", async () => { const root = await loadCorpusModel(corpus.cases[0]!); const names = resolveObjectNames(root.findObject("Shipment") as MetaObject); - for (const field of ["shipTo", "billTo", "returnTo", "giftTo", "homeTo"]) { - const entry = names?.fields[field]; - expect(entry).toBeDefined(); - expect("column" in entry!).toBe(false); - } + expect(names?.fields.shipTo?.column).toBe("ship_to"); + expect(Object.keys(names?.fields.shipTo?.members ?? {}).sort()).toEqual(["country", "postalCode", "street"]); + expect(names?.fields.id?.members).toBeUndefined(); }); }); @@ -95,16 +93,15 @@ describe("names artifact — rendered flattened members", () => { }, }; - test("members under the field, each with its column; a jsonb object keeps its one column", async () => { + test("members beside the field's own entry, each with its column; a jsonb object is unchanged", async () => { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(DOC))]); expect(errors).toEqual([]); const out = renderNamesDecl(root.findObject("Shipment") as MetaObject, { strategy: "snake_case" }); expect(out).toContain( - 'shipTo: { name: "shipTo", members: { postalCode: { name: "postalCode", column: "ship_to_ZIP" }, ' + + 'shipTo: { name: "shipTo", column: "ship_to", members: { postalCode: { name: "postalCode", column: "ship_to_ZIP" }, ' + 'street: { name: "street", column: "ship_to_street" } } }', ); expect(out).toContain('payload: { name: "payload", column: "payload" }'); - expect(out).not.toContain('column: "ship_to"'); }); }); diff --git a/server/typescript/packages/codegen-ts/test/names.test.ts b/server/typescript/packages/codegen-ts/test/names.test.ts index 384162de51..439513a281 100644 --- a/server/typescript/packages/codegen-ts/test/names.test.ts +++ b/server/typescript/packages/codegen-ts/test/names.test.ts @@ -106,7 +106,7 @@ describe("resolveObjectNames", () => { }, ]); const n = resolveObjectNames(obj(root, "Thing"), "snake_case"); - expect(n?.fields.firstName).toEqual({ name: "firstName", column: "given_name" }); + expect(n?.fields.firstName?.column).toBe("given_name"); }); // A single role==="primary" source that happens to be READ-ONLY, beside a non-primary diff --git a/server/typescript/packages/test-generators/src/templates/projection-decl.ts b/server/typescript/packages/test-generators/src/templates/projection-decl.ts index ac90598b31..e9ab1e45d2 100644 --- a/server/typescript/packages/test-generators/src/templates/projection-decl.ts +++ b/server/typescript/packages/test-generators/src/templates/projection-decl.ts @@ -158,7 +158,7 @@ export function renderProjectionDecl( // normal, not a divergence — fall back to the literal, same as every other §A6 site. const namesEntry = names?.resolved.fields[f.name]; const dbColExpr: Code = - names !== undefined && namesEntry !== undefined && "column" in namesEntry + names !== undefined && namesEntry !== undefined ? code`${names.symbol}.fields.${f.name}.column` : code`${JSON.stringify(dbCol)}`; // #356 — a projection's descriptor is the same shape the entity descriptor emits, From 167ce4934a612089d8e415b33b6f8dbbe9a108eb Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 07:10:21 -0500 Subject: [PATCH 016/267] feat(enums): a string-stored enum's column length, from @maxLength or enums.maxLength @maxLength on field.enum (all ports' registries) makes a string-stored enum's column VARCHAR(n), and "enums": { "maxLength": n } in .metaobjects/config.json gives every enum without one a default. With neither the column stays unbounded text, as before. - Every port reads the `enums` block (refusing a non-object, an unknown key, or a non-positive / non-integer length), carries it on the loaded root beside the naming rules, and resolves the length through one core function: resolveEnumMaxLength (TS), EnumLength.ResolveMaxLength (C#), EnumLength.resolveMaxLength (JVM), resolve_enum_max_length (Python). - The loader refuses an @maxLength a member does not fit (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH) and @maxLength beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP); the resolver refuses a member longer than the project default, which meta migrate and meta verify report by name. - meta migrate emits VARCHAR(n); Drizzle (Postgres varchar, MySQL), Prisma (@db.VarChar), EF Core (HasMaxLength) and Exposed (enumerationByName / varchar) name the same length. Array enums stay text[]. - Conformance: three new metamodel fixtures and a shared enum-length corpus (fixtures/enum-length-conformance/) run in every port. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 11 ++ docs/CONFORMANCE.md | 9 +- docs/features/field-types.md | 18 ++- examples/showcase/site-payload.json | 4 +- fixtures/conformance/ERROR-CODES.json | 2 + .../conformance/enum-max-length/expected.json | 38 ++++++ .../enum-max-length/input/meta.enums.json | 23 ++++ .../expected-errors.json | 15 +++ .../input/meta.enums.json | 24 ++++ .../expected-errors.json | 15 +++ .../input/meta.enums.json | 23 ++++ fixtures/enum-length-conformance/README.md | 24 ++++ fixtures/enum-length-conformance/cases.json | 35 ++++++ .../enum-length-conformance/meta.enums.json | 29 +++++ fixtures/metamodel-docs/expected/providers.md | 2 +- .../metamodel-docs/expected/types/field.md | 1 + .../expected-registry.json | 7 ++ scripts/check-doc-examples.ts | 2 + .../EnumLengthCodegenTests.cs | 55 +++++++++ .../EnumLengthConformanceTests.cs | 101 ++++++++++++++++ .../Generators/DbContextGenerator.cs | 8 +- .../MetaObjects/Config/MetadataLocation.cs | 10 +- .../MetaObjects/Config/NeutralConfig.cs | 35 +++++- server/csharp/MetaObjects/Errors.cs | 2 + .../MetaObjects/Loader/MetaDataLoader.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 52 ++++++++ server/csharp/MetaObjects/Meta/EnumLength.cs | 51 ++++++++ server/csharp/MetaObjects/Meta/MetaRoot.cs | 7 ++ .../MetaObjects/SpecMetamodel/field.json | 1 + .../kotlin/KotlinExposedTableGenerator.kt | 2 +- .../kotlin/KotlinStoredProcGenerator.kt | 2 +- .../generator/kotlin/KotlinTypeMapper.kt | 10 +- .../kotlin/KotlinExposedTableGeneratorTest.kt | 35 ++++++ .../mojo/AbstractMetaDataMojo.java | 4 + .../main/java/com/metaobjects/ErrorCode.java | 2 + .../main/java/com/metaobjects/MetaRoot.java | 16 +++ .../com/metaobjects/config/EnumDefaults.java | 35 ++++++ .../com/metaobjects/config/NeutralConfig.java | 41 ++++++- .../metaobjects/config/SourceResolver.java | 5 + .../com/metaobjects/database/EnumLength.java | 64 ++++++++++ .../java/com/metaobjects/field/EnumField.java | 10 ++ .../metaobjects/loader/MetaDataLoader.java | 5 + .../metaobjects/loader/ValidationPhase.java | 65 ++++++++++ .../util/ErrorMessageConstants.java | 14 +++ .../database/EnumLengthConformanceTest.java | 112 ++++++++++++++++++ server/python/src/metaobjects/cli.py | 3 + .../src/metaobjects/config/dependencies.py | 4 + .../src/metaobjects/config/neutral_config.py | 39 ++++++ .../src/metaobjects/config/source_resolver.py | 3 + server/python/src/metaobjects/enum_length.py | 79 ++++++++++++ server/python/src/metaobjects/errors.py | 2 + .../metaobjects/loader/meta_data_loader.py | 2 + .../metaobjects/loader/validation_passes.py | 51 ++++++++ .../python/src/metaobjects/meta/meta_root.py | 4 + .../src/metaobjects/spec_metamodel/field.json | 1 + .../test_enum_length_conformance.py | 65 ++++++++++ .../packages/cli/src/commands/migrate.ts | 3 + .../packages/cli/src/commands/verify.ts | 6 + .../cli/src/lib/collection-load-options.ts | 3 +- .../cli/src/lib/enum-length-refusal.ts | 16 +++ .../cli/test/migrate-enum-max-length.test.ts | 65 ++++++++++ .../cli/test/verify-schema-refusals.test.ts | 21 ++++ .../packages/codegen-ts/src/column-mapper.ts | 19 ++- .../src/prisma/build-prisma-schema.ts | 3 + .../test/drizzle-enum-max-length.test.ts | 49 ++++++++ .../test/prisma/prisma-schema.test.ts | 12 ++ .../core/field/field-definition.embedded.ts | 8 ++ .../packages/metadata/src/enum-length.ts | 63 ++++++++++ .../packages/metadata/src/errors.ts | 3 + .../typescript/packages/metadata/src/index.ts | 2 + .../metadata/src/loader/meta-data-loader.ts | 6 +- .../metadata/src/loader/validation-passes.ts | 54 +++++++++ .../packages/metadata/src/shared/meta-root.ts | 7 ++ .../metadata/test/enum-max-length.test.ts | 70 +++++++++++ .../field-definition-completeness.test.ts | 4 +- .../migrate-ts/src/expected-schema.ts | 10 +- .../test/unit/enum-max-length.test.ts | 59 +++++++++ .../typescript/packages/sdk/src/collection.ts | 9 +- server/typescript/packages/sdk/src/config.ts | 18 +++ server/typescript/packages/sdk/src/index.ts | 2 +- server/typescript/packages/sdk/src/memory.ts | 11 +- .../sdk/test/enum-length-conformance.test.ts | 81 +++++++++++++ site-reference/providers.html | 2 +- site-reference/types/field.html | 9 ++ spec/metamodel/field.json | 1 + 86 files changed, 1869 insertions(+), 30 deletions(-) create mode 100644 fixtures/conformance/enum-max-length/expected.json create mode 100644 fixtures/conformance/enum-max-length/input/meta.enums.json create mode 100644 fixtures/conformance/error-enum-max-length-int-value-map/expected-errors.json create mode 100644 fixtures/conformance/error-enum-max-length-int-value-map/input/meta.enums.json create mode 100644 fixtures/conformance/error-enum-value-exceeds-max-length/expected-errors.json create mode 100644 fixtures/conformance/error-enum-value-exceeds-max-length/input/meta.enums.json create mode 100644 fixtures/enum-length-conformance/README.md create mode 100644 fixtures/enum-length-conformance/cases.json create mode 100644 fixtures/enum-length-conformance/meta.enums.json create mode 100644 server/csharp/MetaObjects.Codegen.Tests/EnumLengthCodegenTests.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/EnumLengthConformanceTests.cs create mode 100644 server/csharp/MetaObjects/Meta/EnumLength.cs create mode 100644 server/java/metadata/src/main/java/com/metaobjects/config/EnumDefaults.java create mode 100644 server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java create mode 100644 server/java/metadata/src/test/java/com/metaobjects/database/EnumLengthConformanceTest.java create mode 100644 server/python/src/metaobjects/enum_length.py create mode 100644 server/python/tests/conformance/test_enum_length_conformance.py create mode 100644 server/typescript/packages/cli/src/lib/enum-length-refusal.ts create mode 100644 server/typescript/packages/cli/test/migrate-enum-max-length.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts create mode 100644 server/typescript/packages/metadata/src/enum-length.ts create mode 100644 server/typescript/packages/metadata/test/enum-max-length.test.ts create mode 100644 server/typescript/packages/migrate-ts/test/unit/enum-max-length.test.ts create mode 100644 server/typescript/packages/sdk/test/enum-length-conformance.test.ts diff --git a/AGENTS.md b/AGENTS.md index 31c4c7fa80..3a796bed17 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (423 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (426 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 34406ebf68..af1d6f7cfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,17 @@ here.** that generated before still generates. In C# and Java, a names class no longer extends its base's when that would make a base constant that is not a column of its own table reachable through it (a flattened field redeclared as jsonb, say); it is emitted complete instead. +- **A string-stored enum's column length: `@maxLength` on `field.enum`, and `enums.maxLength`.** + `@maxLength` on a `field.enum` makes its column `VARCHAR(n)`, and `"enums": { "maxLength": n }` + in `.metaobjects/config.json` gives every enum without one a default; with neither, the column + stays unbounded text, as before. Every port reads the setting and resolves the length through + one core function (`resolveEnumMaxLength`, `EnumLength.ResolveMaxLength`, + `EnumLength.resolveMaxLength`, `resolve_enum_max_length`), and `meta migrate`, the Drizzle, + Prisma, EF Core and Exposed bindings use it. A member longer than the length is refused + (`ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH`): at load for `@maxLength`, when the column is sized for + the project default, which `meta migrate` and `meta verify` report by name. `@maxLength` beside + `@intValueMap` is refused at load (`ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP`). A new shared + corpus, `fixtures/enum-length-conformance/`, pins the resolution in every port. - **A `PascalCase` column rule.** `"naming": { "columns": "PascalCase" }` in `.metaobjects/config.json` upper-cases a field name's first letter and changes nothing else (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`), in every port: the column names EF Core diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d7e9157567..ae9200511d 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **35 shared conformance corpora** under +The MetaObjects standard ships **36 shared conformance corpora** under [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to it* and asserts the same expected behaviour against the same fixtures. **This page is the inverse index**: fixture → feature doc + per-port pass status, and it is the @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 423 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 426 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -58,6 +58,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 26 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`) | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | +| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 3 cases + 1 overflow + 5 refusals | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | ✓ | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (FR-044 — reporting vocabulary: what is lowered, what stays inert) | 1 model pair (`reporting/with` vs `reporting/without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | @@ -285,7 +286,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (423) +### `fixtures/conformance/` — metamodel loader + canonical serializer (426) | Fixture prefix | Feature doc | |---|---| @@ -611,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 423 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 426 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 3a17110090..ad81748789 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -190,7 +190,23 @@ must be a non-empty set of unique members matching `^[A-Za-z_][A-Za-z0-9_]*$`. The loader enforces members own-only and emits `ERR_BAD_ATTR_VALUE` on a bad member or `ERR_MISSING_REQUIRED_ATTR` on missing `@values`. -**Int-backed storage:** `@intValueMap` switches the DB column from string to integer while +**Column length:** a string-stored enum is an unbounded text column unless it has a length. +`@maxLength` on the field gives it one, and `"enums": { "maxLength": n }` in +`.metaobjects/config.json` gives every enum without its own `@maxLength` a default: + +```json +{ "field.enum": { "name": "status", "@values": ["DRAFT", "PUBLISHED", "ARCHIVED"], "@maxLength": 16 } } +``` + +The column is then `VARCHAR(n)`: `meta migrate` creates it, and the Drizzle, Prisma, EF Core +(`HasMaxLength(n)`) and Exposed bindings name the same length. Every member must fit. A member +longer than `@maxLength` is refused at load, and one longer than the project default is refused +when the column is sized, both as `ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH`, with the member named. +`@maxLength` beside `@intValueMap` is refused (`ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP`): an +int-backed enum's column is an integer. An array of enums stays a `text[]` column. Kotlin's +Exposed binding keeps its 64-character width when the enum has no length. + +**Int-backed storage:** `@intValueMap` switches the DB column from string to integer while**Int-backed storage:** `@intValueMap` switches the DB column from string to integer while preserving the string wire format and generated enum type. Keys must match `@values` exactly; values must be unique integers. Display labels and native Postgres `ENUM` types remain deferred (see [enum-datatype-design.md](../superpowers/specs/2026-05-23-enum-datatype-design.md)). diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 6e9ec3f63d..eafa11982f 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,8 +7,8 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 423, - "corpora": 35, + "fixtures": 426, + "corpora": 36, "baseTypes": 17 }, "snippets": { diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 019c46b02c..13b6814ec5 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -53,6 +53,8 @@ "ERR_TEMPLATE_ENGINE_UNSUPPORTED": "Build-time verify and render (ADR-0061): a template body is written for an engine this port does not ship — a Jinja body (.jinja / .j2 / .jinja2) in the Java, Kotlin or C# port, which render Mustache only. path = the template ref.", "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate or object.report (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", + "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", + "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", "ERR_STORAGE_WITHOUT_OBJECT_REF": "@storage was set on a field that has no @objectRef.", "ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF": "ADR-0013: a field.object declares no @objectRef. A field.object models a typed nested value and REQUIRES @objectRef. The message states the whole ladder rather than only the escape hatch: a known key set is an object.value the field @objectRefs; dynamic keys over a known value type are a field.map (@objectRef for a value object, @valueType for a scalar); only a bag no reader pins a key in is @dbColumnType: jsonb on a field.string. Naming the escape hatch alone is what taught adopters to reach for the bag by default.", diff --git a/fixtures/conformance/enum-max-length/expected.json b/fixtures/conformance/enum-max-length/expected.json new file mode 100644 index 0000000000..f48725ddb3 --- /dev/null +++ b/fixtures/conformance/enum-max-length/expected.json @@ -0,0 +1,38 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "status", + "@maxLength": 9, + "@values": [ + "DRAFT", + "PUBLISHED", + "ARCHIVED" + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/enum-max-length/input/meta.enums.json b/fixtures/conformance/enum-max-length/input/meta.enums.json new file mode 100644 index 0000000000..fad79bf83b --- /dev/null +++ b/fixtures/conformance/enum-max-length/input/meta.enums.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["DRAFT", "PUBLISHED", "ARCHIVED"], + "@maxLength": 9 + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-max-length-int-value-map/expected-errors.json b/fixtures/conformance/error-enum-max-length-int-value-map/expected-errors.json new file mode 100644 index 0000000000..412a138aba --- /dev/null +++ b/fixtures/conformance/error-enum-max-length-int-value-map/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-max-length-int-value-map/input/meta.enums.json b/fixtures/conformance/error-enum-max-length-int-value-map/input/meta.enums.json new file mode 100644 index 0000000000..b455875959 --- /dev/null +++ b/fixtures/conformance/error-enum-max-length-int-value-map/input/meta.enums.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["DRAFT", "PUBLISHED"], + "@intValueMap": { "DRAFT": 0, "PUBLISHED": 1 }, + "@maxLength": 9 + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-value-exceeds-max-length/expected-errors.json b/fixtures/conformance/error-enum-value-exceeds-max-length/expected-errors.json new file mode 100644 index 0000000000..caf054c0c3 --- /dev/null +++ b/fixtures/conformance/error-enum-value-exceeds-max-length/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-value-exceeds-max-length/input/meta.enums.json b/fixtures/conformance/error-enum-value-exceeds-max-length/input/meta.enums.json new file mode 100644 index 0000000000..d6f75adf1f --- /dev/null +++ b/fixtures/conformance/error-enum-value-exceeds-max-length/input/meta.enums.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["DRAFT", "PUBLISHED", "AWAITING_REVIEW"], + "@maxLength": 9 + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/enum-length-conformance/README.md b/fixtures/enum-length-conformance/README.md new file mode 100644 index 0000000000..a381562a1e --- /dev/null +++ b/fixtures/enum-length-conformance/README.md @@ -0,0 +1,24 @@ +# Enum-length conformance + +A string-stored `field.enum` is a `VARCHAR(n)` column when it has a length: its own `@maxLength`, +else the project's default, `"enums": { "maxLength": n }` in `.metaobjects/config.json`. With +neither it stays an unbounded text column, as before. An `@intValueMap` enum is an integer +column and takes no length. Every member must fit: the loader refuses an `@maxLength` a member +is longer than (`ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH`, pinned in `fixtures/conformance/`), and the +core resolver refuses a member longer than the project default, so every consumer that sizes +the column refuses the same model. + +[`cases.json`](./cases.json) holds the `enums` blocks every port must accept, with the length +each enum in [`meta.enums.json`](./meta.enums.json) resolves to under them, the overflow every +port must refuse, and the blocks every port must refuse when it reads the file. Each port runs +it through its own config reader and core resolver: + +| Port | Test | +|---|---| +| TypeScript | `server/typescript/packages/sdk/test/enum-length-conformance.test.ts` | +| C# | `server/csharp/MetaObjects.Codegen.Tests/EnumLengthConformanceTests.cs` | +| Java / Kotlin | `server/java/metadata/src/test/java/com/metaobjects/database/EnumLengthConformanceTest.java` | +| Python | `server/python/tests/conformance/test_enum_length_conformance.py` | + +The column each port's bindings emit is described in +[`docs/features/field-types.md`](../../docs/features/field-types.md). diff --git a/fixtures/enum-length-conformance/cases.json b/fixtures/enum-length-conformance/cases.json new file mode 100644 index 0000000000..4167935f62 --- /dev/null +++ b/fixtures/enum-length-conformance/cases.json @@ -0,0 +1,35 @@ +{ + "_comment": "The column length of a string-stored field.enum, per port. Each case is the `enums` block of a project's .metaobjects/config.json (null: no block). Each port reads it with its own config reader, puts it on the loaded meta.enums.json root, and resolves every Ticket enum's length through its core resolver (resolveEnumMaxLength and its per-port equivalents). null in `lengths` means no length: an unbounded text column. `overflow` cases must be refused when the named field's length is resolved, with ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH. Each `invalid` block must be refused when the config is read.", + "cases": [ + { + "name": "no enums block: only an explicit @maxLength sizes a column", + "enums": null, + "lengths": { "status": null, "channel": 20, "priority": 8, "rank": null } + }, + { + "name": "an empty block is the same as none", + "enums": {}, + "lengths": { "status": null, "channel": 20, "priority": 8, "rank": null } + }, + { + "name": "the project default sizes every enum without its own @maxLength", + "enums": { "maxLength": 32 }, + "lengths": { "status": 32, "channel": 20, "priority": 8, "rank": null } + } + ], + "overflow": [ + { + "name": "a member longer than the project default is refused", + "enums": { "maxLength": 10 }, + "field": "status", + "member": "IN_PROGRESS" + } + ], + "invalid": [ + { "name": "maxLength is a positive integer, not zero", "enums": { "maxLength": 0 } }, + { "name": "maxLength is an integer", "enums": { "maxLength": 12.5 } }, + { "name": "maxLength is a number, not a string", "enums": { "maxLength": "32" } }, + { "name": "an unknown key is refused", "enums": { "length": 32 } }, + { "name": "enums is an object", "enums": 32 } + ] +} diff --git a/fixtures/enum-length-conformance/meta.enums.json b/fixtures/enum-length-conformance/meta.enums.json new file mode 100644 index 0000000000..717d319ab9 --- /dev/null +++ b/fixtures/enum-length-conformance/meta.enums.json @@ -0,0 +1,29 @@ +{ + "metadata.root": { + "package": "acme::enums", + "children": [ + { + "field.enum": { + "name": "Priority", + "abstract": true, + "@values": ["LOW", "HIGH"], + "@maxLength": 8 + } + }, + { + "object.entity": { + "name": "Ticket", + "children": [ + { "source.rdb": {} }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["OPEN", "IN_PROGRESS", "CLOSED"] } }, + { "field.enum": { "name": "channel", "@values": ["EMAIL", "PHONE"], "@maxLength": 20 } }, + { "field.enum": { "name": "priority", "extends": "acme::enums::Priority" } }, + { "field.enum": { "name": "rank", "@values": ["A", "B"], "@intValueMap": { "A": 1, "B": 2 } } }, + { "identity.primary": { "name": "pk", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 3790f21eea..703a3723c5 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -20,7 +20,7 @@ Core metaobjects metamodel types and subtypes. - `field.base`: `@default`, `@mutability`, `@required`, `@unique` - `field.currency`: `@currency` - `field.decimal`: `@precision`, `@scale` -- `field.enum`: `@intValueMap`, `@provided`, `@values` +- `field.enum`: `@intValueMap`, `@maxLength`, `@provided`, `@values` - `field.inet`: `@lenient` - `field.map`: `@objectRef`, `@valueType` - `field.object`: `@objectRef` diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index 77a8d92433..45618552ec 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -240,6 +240,7 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@formExclude` | boolean | no | | | metaobjects-ui | When true, the field is omitted from generated forms, and the generated create, PATCH and PUT routes ignore a value sent for it (reads of it are unchanged); inert on fields for which no form is generated (e.g. projection/derived fields). | | `@instruction` | string | no | | | metaobjects-prompt | FR-010: a short instruction for this field, shown in the generated output-format prompt fragment. | | `@intValueMap` | intMap | no | | | metaobjects-core-types | Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language. | +| `@maxLength` | int | no | | | metaobjects-core-types | Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer. | | `@mutability` | string | no | | `readWrite`, `writeOnce`, `readOnly` | metaobjects-core-types | FR-037 R1: who may write this field, and when. 'readWrite' (the default when absent) — the caller may set it on create and change it on update. 'writeOnce' — the caller sets it on create; it is excluded from the update shape thereafter, so a value presented on PATCH is ignored rather than rejected. 'readOnly' — nobody writes it: codegen emits no setter / writable property, the persistence layer skips the column on INSERT/UPDATE, and Zod/Pydantic/class-validator schemas omit it from input variants; the value is populated by the database (computed column, default expression, trigger), by replication, or by another external owner. The three are mutually exclusive modes of ONE axis — who may write, and when — so the illegal pair is unrepresentable and inheritance has a total order: a subtype may TIGHTEN an inherited mode (readWrite < writeOnce < readOnly) and never loosen it (ERR_MUTABILITY_DOWNGRADE). Pairing a non-readWrite mode with @autoSet is ERR_MUTABILITY_AUTOSET_CONFLICT: @autoSet already says the SERVER supplies the value, which is a different axis from who may write it. | | `@normalize` | string | no | `strip` | `none`, `collapse`, `strip` | metaobjects-prompt | ASCII normalization mode for tolerant enum extract (none\|collapse\|strip, default strip). On field.enum it is per-field; on object.value it is the default for the object's enum fields. | | `@provided` | boolean | no | | | metaobjects-core-types | FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 826bc5a7a7..498513646e 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1119,6 +1119,13 @@ "required": false, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { + "name": "maxLength", + "valueType": "int", + "isArray": false, + "required": false, + "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." + }, { "name": "mutability", "valueType": "string", diff --git a/scripts/check-doc-examples.ts b/scripts/check-doc-examples.ts index c845a9c08f..9220502587 100644 --- a/scripts/check-doc-examples.ts +++ b/scripts/check-doc-examples.ts @@ -155,6 +155,8 @@ const FAIL_CODES = new Set([ "ERR_READONLY_ASSIGNED_PRIMARY", "ERR_STORAGE_FLATTENED_ARRAY", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE", + "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", + "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", "ERR_PHYSICAL_NAME_KIND_MISMATCH", "ERR_PHYSICAL_NAME_MULTIPLE", "ERR_SQL_BODY_ON_WRITABLE_KIND", diff --git a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCodegenTests.cs new file mode 100644 index 0000000000..d5213eb399 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCodegenTests.cs @@ -0,0 +1,55 @@ +// A string-stored enum with a column length (its @maxLength, else the project's +// enums.maxLength — EnumLength.ResolveMaxLength) maps with HasMaxLength(n), the VARCHAR(n) +// `meta migrate` creates; with none, the mapping is unchanged. +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class EnumLengthCodegenTests +{ + private static string DbContextFor(string statusAttrs, long? projectDefault = null) + { + var model = $$$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["OPEN", "CLOSED"]{{{statusAttrs}}} } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "enum-length.json")]); + Assert.Empty(r.Errors); + if (projectDefault is { } d) r.Root.EnumDefaults = new EnumDefaults(d); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, + }; + return new DbContextGenerator().Generate(ctx).Single().Content; + } + + [Fact] + public void An_enum_with_maxLength_maps_with_that_length() + { + Assert.Contains("HasConversion().HasMaxLength(16);", DbContextFor(""", "@maxLength": 16""")); + } + + [Fact] + public void The_project_default_sizes_an_enum_with_no_maxLength() + { + Assert.Contains("HasConversion().HasMaxLength(24);", DbContextFor("", projectDefault: 24)); + } + + [Fact] + public void No_length_anywhere_leaves_the_mapping_unchanged() + { + var dbContext = DbContextFor(""); + Assert.Contains("HasConversion();", dbContext); + Assert.DoesNotContain("HasMaxLength", dbContext); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthConformanceTests.cs new file mode 100644 index 0000000000..fe0a3c2557 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthConformanceTests.cs @@ -0,0 +1,101 @@ +// EnumLengthConformanceTests — runs the shared cross-port enum-length corpus +// (fixtures/enum-length-conformance/) against the C# port. Each case's `enums` block is +// written to a throwaway project's .metaobjects/config.json and read with NeutralConfig (the +// reader every project-aware load uses), put on the loaded meta.enums.json root, and every +// Ticket enum's column length resolved through EnumLength.ResolveMaxLength. Each `overflow` +// case must be refused with ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, and each `invalid` block +// refused when the config is read. +using System.Text.Json; +using MetaObjects; +using MetaObjects.Config; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class EnumLengthConformanceTests +{ + private static string FixtureDir => + Path.Combine(CorpusPaths.RepoRoot(), "fixtures", "enum-length-conformance"); + + private static JsonDocument Corpus() => JsonDocument.Parse(File.ReadAllText(Path.Combine(FixtureDir, "cases.json"))); + + private static JsonElement Entry(string section, string name) + { + using var doc = Corpus(); + return doc.RootElement.GetProperty(section).EnumerateArray() + .Single(c => c.GetProperty("name").GetString() == name).Clone(); + } + + private static TheoryData Names(string section) + { + var data = new TheoryData(); + using var doc = Corpus(); + foreach (var el in doc.RootElement.GetProperty(section).EnumerateArray()) data.Add(el.GetProperty("name").GetString()!); + return data; + } + + public static TheoryData CaseNames() => Names("cases"); + public static TheoryData OverflowNames() => Names("overflow"); + public static TheoryData InvalidNames() => Names("invalid"); + + /// Reads as a project's config.json `enums` block. + private static EnumDefaults ReadEnums(JsonElement enums) + { + var dir = Path.Combine(Path.GetTempPath(), "mo-enums-conf-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path.Combine(dir, ".metaobjects")); + var body = enums.ValueKind == JsonValueKind.Null + ? """{ "schema_version": 1 }""" + : $$"""{ "schema_version": 1, "enums": {{enums.GetRawText()}} }"""; + File.WriteAllText(Path.Combine(dir, ".metaobjects", "config.json"), body); + try + { + return NeutralConfig.Read(dir)?.Enums ?? EnumDefaults.Default; + } + finally + { + Directory.Delete(dir, recursive: true); + } + } + + private static MetaField TicketField(EnumDefaults defaults, string name) + { + var result = new MetaDataLoader().Load([new FileSource(Path.Combine(FixtureDir, "meta.enums.json"))]); + Assert.True(result.Errors.Count == 0, string.Join("\n", result.Errors.Select(e => $"{e.Code}: {e.Message}"))); + result.Root.EnumDefaults = defaults; + return result.Root.FindObject("Ticket")!.Fields().Single(f => f.Name == name); + } + + [Theory] + [MemberData(nameof(CaseNames))] + public void Resolves_every_enum_column_length(string name) + { + var c = Entry("cases", name); + var defaults = ReadEnums(c.GetProperty("enums")); + foreach (var p in c.GetProperty("lengths").EnumerateObject()) + { + long? expected = p.Value.ValueKind == JsonValueKind.Null ? null : p.Value.GetInt64(); + Assert.Equal(expected, EnumLength.ResolveMaxLength(TicketField(defaults, p.Name))); + } + } + + [Theory] + [MemberData(nameof(OverflowNames))] + public void Refuses_a_member_longer_than_the_project_default(string name) + { + var o = Entry("overflow", name); + var field = TicketField(ReadEnums(o.GetProperty("enums")), o.GetProperty("field").GetString()!); + var ex = Assert.Throws(() => EnumLength.ResolveMaxLength(field)); + Assert.Equal(ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, ex.Code); + Assert.Contains(o.GetProperty("member").GetString()!, ex.Message); + } + + [Theory] + [MemberData(nameof(InvalidNames))] + public void Refuses_an_invalid_enums_block(string name) + { + var bad = Entry("invalid", name); + Assert.Throws(() => ReadEnums(bad.GetProperty("enums"))); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index de985e3ac1..fb78d00bd4 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -926,7 +926,13 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met private static string EnumConversionCall(string owner, MetaObject entity, MetaField f, GenConfig config) { var intMap = IntValueMapOf(f); - if (intMap is null) return "HasConversion()"; + // A string-backed enum's column length (EnumLength.ResolveMaxLength: its @maxLength, else + // the project's enums.maxLength) is the VARCHAR(n) `meta migrate` creates. An array enum + // is a text[] column, whose elements carry no length. + if (intMap is null) + return !f.ResolvedIsArray() && EnumLength.ResolveMaxLength(f) is { } length + ? $"HasConversion().HasMaxLength({length})" + : "HasConversion()"; var members = f.EffectiveEnumValues ?? new List(); if (members.Count == 0) return "HasConversion()"; diff --git a/server/csharp/MetaObjects/Config/MetadataLocation.cs b/server/csharp/MetaObjects/Config/MetadataLocation.cs index a86dcbe822..1455553ed0 100644 --- a/server/csharp/MetaObjects/Config/MetadataLocation.cs +++ b/server/csharp/MetaObjects/Config/MetadataLocation.cs @@ -42,7 +42,8 @@ namespace MetaObjects.Config; /// public sealed record ResolvedMetadata( string Directory, IReadOnlyList? Files, IReadOnlyList Libraries, PhysicalNaming Naming, - WireFormat? Wire = null, string? OutDir = null, ImportScope? Imports = null, string? Namespace = null) + WireFormat? Wire = null, string? OutDir = null, ImportScope? Imports = null, string? Namespace = null, + EnumDefaults? Enums = null) { /// Load this metadata, with the project's libraries, and set the loaded /// root's from (ADR-0058) and its @@ -57,6 +58,7 @@ public LoadResult Load(bool strict = false) Directory, MetaDataLoader.DefaultRegistry(), Libraries, leading, strict: strict); result.Root.PhysicalNaming = Naming; result.Root.WireFormat = Wire ?? WireFormat.Default; + result.Root.EnumDefaults = Enums ?? EnumDefaults.Default; if (Imports is null) return result; result.Root.ImportScope = Imports; @@ -117,7 +119,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) // No config found means no project to read a lock from: nothing is imported. var explicitImports = explicitCfg is null ? ImportScope.None : ImportScope.Resolve(explicitCfg.ConfigDir, explicitCfg); return new ResolvedMetadata( - metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace); + metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace, explicitCfg?.Enums); } var cfg = NeutralConfig.Read(cwd); @@ -132,7 +134,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) // No declared sources: resolve the DEFAULT directory through the same ladder // the shared conformance corpus gates (ERR_COLLECTION_NOT_FOUND when absent). var defaultFiles = SourceResolver.ResolveCollection(cwd); - return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace); + return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, cfg?.Enums); } if (specs.Count > 1) @@ -162,6 +164,6 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) "\"sources\" at the file's containing directory."); } - return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace); + return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, cfg?.Enums); } } diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index b776047458..6eee87a039 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -87,6 +87,10 @@ public sealed class NeutralConfig /// absent key at its native default. Never null. public WireFormat Wire { get; } + /// The project's enum storage defaults (`enums` in config.json). Never null: an absent + /// block is no default, same as an empty `enums: {}`. + public EnumDefaults Enums { get; private init; } = EnumDefaults.Default; + /// The C# port's generated-code directory (`csharp.outDir` in config.json), resolved /// against the directory holding `.metaobjects/` so it reads the same from any working /// directory. Null when the key is absent. `--out` on the command line wins over it. @@ -272,7 +276,7 @@ private NeutralConfig( // lists read above, are IGNORED by design — see the file header. return new NeutralConfig(specs, libraries, new PhysicalNaming(columns, tables), ReadWire(root, path), ReadCSharp(root, path, configDir), dependencies, scopeInclude, migrateScope, - Path.GetFullPath(configDir)); + Path.GetFullPath(configDir)) { Enums = ReadEnums(root, path) }; } } @@ -335,6 +339,35 @@ private static (string? OutDir, string? Namespace) ReadCSharp(JsonElement root, return (outDir, ns); } + /// The `enums` block: `maxLength`, a positive integer, is the column length of a string-stored + /// enum with no @maxLength. An unknown key, a wrong-typed value, or a non-object block is + /// refused, the same rule as `naming`. + private static EnumDefaults ReadEnums(JsonElement root, string path) + { + if (!root.TryGetProperty("enums", out var enums)) return EnumDefaults.Default; + if (enums.ValueKind != JsonValueKind.Object) + throw new MetaModelException($"{path}: \"enums\" must be an object", ErrorCode.ERR_BAD_ATTR_VALUE); + long? maxLength = null; + foreach (var p in enums.EnumerateObject()) + { + switch (p.Name) + { + case "maxLength": + if (p.Value.ValueKind != JsonValueKind.Number || !p.Value.TryGetInt64(out var n) || n <= 0) + throw new MetaModelException( + $"{path}: \"enums.maxLength\" must be a positive integer", + ErrorCode.ERR_BAD_ATTR_VALUE); + maxLength = n; + break; + default: + throw new MetaModelException( + $"{path}: \"enums\" has an unknown key \"{p.Name}\" (expected \"maxLength\")", + ErrorCode.ERR_BAD_ATTR_VALUE); + } + } + return maxLength is null ? EnumDefaults.Default : new EnumDefaults(maxLength); + } + /// The `wire` block (ADR-0019 Amendment 2): an unknown key, an unknown value, or a /// non-object block is refused, the same rule as `naming`. private static WireFormat ReadWire(JsonElement root, string path) diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index b86562fcf3..f11fa6ab62 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -142,6 +142,8 @@ public enum ErrorCode ERR_STORAGE_FLATTENED_ARRAY, // @flattenedColumnPrefix on a field.object whose @storage is not "flattened" (absent is jsonb). ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, + ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, ERR_INVALID_TEMPLATE, ERR_SOURCE_NO_PRIMARY, ERR_SOURCE_MULTIPLE_PRIMARY, diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index f5796338fa..0ac515cfc7 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -171,6 +171,7 @@ internal static LoadResult FromDirectory(string directory, TypeRegistry registry { result.Root.PhysicalNaming = cfg.Naming; result.Root.WireFormat = cfg.Wire; + result.Root.EnumDefaults = cfg.Enums; } return result; } @@ -535,6 +536,7 @@ public LoadResult Load(IReadOnlyList sources) // Pass 8b: field.map — exactly one of @valueType (scalar) or @objectRef (VO), // and @valueType (when set) must name a known scalar subtype. errors.AddRange(ValidationPasses.ValidateFieldMap(root)); + errors.AddRange(ValidationPasses.ValidateEnumMaxLength(root)); // Pass 9: template @payloadRef / @requiredSlots resolution errors.AddRange(ValidationPasses.ValidateTemplatePayloadRefs(root)); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index b40223bdaf..0135e02f6b 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2090,6 +2090,58 @@ private static void ValidateAttrSchemaNode( } } + // --------------------------------------------------------------------------- + // field.enum @maxLength — the column length of a string-stored enum: + // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the + // longest offender named; + // 2. it is refused beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP): an + // int-stored enum's column is an integer, so a length would change nothing. + // Read RESOLVING (ADR-0039), reported on the node that DECLARES one of the three, so an + // enum that only inherits them is not reported twice. Every field.enum in the tree is + // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. + // --------------------------------------------------------------------------- + public static IReadOnlyList ValidateEnumMaxLength(MetaData root) + { + var errors = new List(); + void Visit(MetaData node) + { + foreach (var child in node.OwnChildren()) + { + if (child.Type == TYPE_FIELD && child.SubType == FIELD_SUBTYPE_ENUM && child is MetaField f) CheckEnum(f); + if (child.Type != TYPE_FIELD) Visit(child); + } + } + void CheckEnum(MetaField field) + { + var declares = new[] { FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP } + .Any(a => field.OwnAttr(a) is not null); + if (!declares || field.MaxLength is not { } maxLength) return; + var owner = field.Parent; + var label = owner is not null && owner.Type == TYPE_OBJECT ? $"{owner.Name}.{field.Name}" : field.Name; + if (field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null) + { + errors.Add(new MetaError( + $"field.enum \"{label}\" sets @maxLength {maxLength} and @intValueMap; an @intValueMap enum is stored as an integer, so a column length does not apply. Remove @maxLength.", + ErrorCode.ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, + Envelope: field.Source)); + return; + } + var tooLong = (field.EffectiveEnumValues ?? []) + .Where(v => v.Length > maxLength) + .OrderByDescending(v => v.Length) + .FirstOrDefault(); + if (tooLong is not null) + { + errors.Add(new MetaError( + $"field.enum \"{label}\" @maxLength {maxLength} is shorter than its member \"{tooLong}\" ({tooLong.Length} characters). Raise @maxLength to at least {tooLong.Length}, or shorten the member.", + ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + Envelope: field.Source)); + } + } + Visit(root); + return errors; + } + // ------------------------------------------------------------------------- // Attr-type check helper — mirrors valueMatchesType() in attr-schema-validate.ts // diff --git a/server/csharp/MetaObjects/Meta/EnumLength.cs b/server/csharp/MetaObjects/Meta/EnumLength.cs new file mode 100644 index 0000000000..eeaa7dfe45 --- /dev/null +++ b/server/csharp/MetaObjects/Meta/EnumLength.cs @@ -0,0 +1,51 @@ +// The column length of a string-stored field.enum: the field's @maxLength, else the project's +// default (`enums.maxLength` in .metaobjects/config.json, carried on the loaded root beside the +// naming rules), else none — an unbounded text column. Mirrors TS enum-length.ts. + +using static MetaObjects.Core.Field.FieldConstants; +using static MetaObjects.Shared.BaseTypes; + +namespace MetaObjects.Meta; + +/// The project's enum storage defaults: enums in .metaobjects/config.json. +/// The column length of a string-stored enum that declares no @maxLength. +public sealed record EnumDefaults(long? MaxLength) +{ + /// No project default: an enum with no @maxLength is an unbounded text column. + public static readonly EnumDefaults Default = new((long?)null); + + /// The enum defaults for the tree belongs to: what its root carries, else none. + public static EnumDefaults Of(MetaData node) => (node.Root() as MetaRoot)?.EnumDefaults ?? Default; +} + +/// Core resolution of a string-stored enum's column length. +public static class EnumLength +{ + /// + /// The column length of , a string-stored field.enum: its + /// @maxLength (ADR-0039 — resolving), else the project default, else null. Null for an + /// @intValueMap enum, whose column is an integer, and for any other field. + /// The loader refuses an @maxLength a member does not fit; it does not see the + /// project config, so a member longer than the project DEFAULT is refused here + /// (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), by every consumer that sizes the column. + /// + public static long? ResolveMaxLength(MetaField field) + { + if (field.SubType != FIELD_SUBTYPE_ENUM || field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null) return null; + if (field.MaxLength is { } own) return own; + if (EnumDefaults.Of(field).MaxLength is not { } fallback) return null; + var longest = (field.EffectiveEnumValues ?? []) + .OrderByDescending(v => v.Length).FirstOrDefault(); + if (longest is not null && longest.Length > fallback) + { + var owner = field.Parent; + var label = owner is not null && owner.Type == TYPE_OBJECT ? $"{owner.Name}.{field.Name}" : field.Name; + throw new MetaModelException( + $"field.enum \"{label}\" has the member \"{longest}\" ({longest.Length} characters), longer than " + + $"the project's enums.maxLength {fallback}. Give the field its own @maxLength of at least " + + $"{longest.Length}, raise enums.maxLength, or shorten the member.", + ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH); + } + return fallback; + } +} diff --git a/server/csharp/MetaObjects/Meta/MetaRoot.cs b/server/csharp/MetaObjects/Meta/MetaRoot.cs index cf7ada93a6..d0235e3f04 100644 --- a/server/csharp/MetaObjects/Meta/MetaRoot.cs +++ b/server/csharp/MetaObjects/Meta/MetaRoot.cs @@ -27,6 +27,13 @@ public class MetaRoot(TypeId typeId, string name) : MetaData(typeId, name) /// public WireFormat WireFormat { get; set; } = WireFormat.Default; + /// + /// The project's enum storage defaults (enums in .metaobjects/config.json), set by + /// the same project-aware load as and read through + /// . A tree loaded with no project has none. + /// + public EnumDefaults EnumDefaults { get; set; } = EnumDefaults.Default; + /// /// FR-023 — what the project imports from metadata dependencies, set by the same project-aware load /// as . Null for a tree loaded with no project (nothing is imported). diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index b054bda765..847f0ea66e 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -151,6 +151,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, + { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } ] }, diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 4fb21db319..b7f2a08bd2 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -2460,7 +2460,7 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase ...`). diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt index d0930db219..a3f568b230 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinStoredProcGenerator.kt @@ -402,7 +402,7 @@ open class KotlinStoredProcGenerator : MultiFileDirectGeneratorBase( is DateField -> "${ExposedImports.javatime(exposedApi, "JavaLocalDateColumnType")}()" is TimestampField -> "${ExposedImports.javatime(exposedApi, "JavaInstantColumnType")}()" is CurrencyField -> "${ExposedImports.core(exposedApi, "LongColumnType")}()" - is EnumField -> "${ExposedImports.core(exposedApi, "VarCharColumnType")}(${KotlinTypeMapper.ENUM_VARCHAR_LEN})" + is EnumField -> "${ExposedImports.core(exposedApi, "VarCharColumnType")}(${KotlinTypeMapper.enumVarcharLength(field)})" // issue #390: java.util.UUID columns MUST use the core.java UUIDColumnType under 1.x — // bare core.UUIDColumnType (if it even existed there) would be the kotlin.uuid.Uuid // binding the 0.x name no longer provides; see KotlinTypeMapper's [UuidField] branches. diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt index 21ccdeb380..2192631e7e 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt @@ -51,6 +51,14 @@ object KotlinTypeMapper { /** Default VARCHAR width for string-backed `field.enum` storage (v1). */ const val ENUM_VARCHAR_LEN = 64 + /** + * The VARCHAR width of a string-backed `field.enum`'s column: core's + * [com.metaobjects.database.EnumLength.resolveMaxLength] (its `@maxLength`, else the + * project's `enums.maxLength`, refusing a member that does not fit), else [ENUM_VARCHAR_LEN]. + */ + fun enumVarcharLength(field: EnumField): Long = + com.metaobjects.database.EnumLength.resolveMaxLength(field) ?: ENUM_VARCHAR_LEN.toLong() + /** * Threshold beyond which a [StringField]'s `@maxLength` is treated as unbounded text and * emitted as Exposed `text(name)` rather than `varchar(name, N)`. Chosen at 4000 — the @@ -548,7 +556,7 @@ object KotlinTypeMapper { // Enum stored as VARCHAR for v1. Proper enum-column handling needs the generated // enum class (Exposed's `customEnumeration` / `enumerationByName` takes a KClass) // and is intentionally deferred. - is EnumField -> "varchar($colExpr, $ENUM_VARCHAR_LEN)" + is EnumField -> "varchar($colExpr, ${enumVarcharLength(field)})" // field.uuid → Exposed's first-class `uuid(name)` under 0.x (native Postgres uuid // column, java.util.UUID) or `javaUUID(name)` under 1.x (issue #390 — 1.x's `uuid()` // binds `kotlin.uuid.Uuid` instead; `javaUUID` is the replacement that keeps diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt index c69915b6f6..6c8c172e15 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGeneratorTest.kt @@ -322,6 +322,41 @@ class KotlinExposedTableGeneratorTest { } } + private fun enumTable(statusDecl: String, maxLength: Long? = null): String { + val outDir = Files.createTempDirectory("ktbl-enum-len-") + try { + val model = """{ + "metadata.root": { "package": "acme::demo", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", $statusDecl } }, + { "source.rdb": { "@table": "tickets" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + }""".trimIndent() + val loader = loadString("enum-len", model) + if (maxLength != null) loader.root.enumDefaults = com.metaobjects.config.EnumDefaults(maxLength) + val gen = KotlinExposedTableGenerator() + gen.setArgs(mapOf("outputDir" to outDir.toString())) + gen.execute(loader) + return Files.readString(outDir.resolve("acme/demo/TicketTable.kt")) + } finally { + outDir.toFile().deleteRecursively() + } + } + + @Test fun anEnumColumnTakesItsLengthFromMaxLengthThenTheProjectDefault() { + val values = "\"@values\": [\"OPEN\", \"CLOSED\"]" + val own = enumTable("$values, \"@maxLength\": 16") + assertTrue("enumerationByName(\"status\", 16, " in own, own) + val byDefault = enumTable(values, maxLength = 24) + assertTrue("enumerationByName(\"status\", 24, " in byDefault, byDefault) + // No length anywhere: the width it always had. + val none = enumTable(values) + assertTrue("enumerationByName(\"status\", ${KotlinTypeMapper.ENUM_VARCHAR_LEN}, " in none, none) + } + @Test fun storageJsonbEmitsJsonbColumn() { val outDir = Files.createTempDirectory("ktbl-jsonb-") try { diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index 7551d86102..216e08da34 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -705,6 +705,10 @@ protected MetaDataLoader createLoader(ClassLoader projectClassLoader) { loader.getRoot().setWireFormat(resolveProjectConfig(srcDir) .map(com.metaobjects.config.NeutralConfig::getWireFormat) .orElse(com.metaobjects.config.WireFormat.DEFAULT)); + // The enum storage defaults (`enums`), from the same file, read by the table generators. + loader.getRoot().setEnumDefaults(resolveProjectConfig(srcDir) + .map(com.metaobjects.config.NeutralConfig::getEnumDefaults) + .orElse(com.metaobjects.config.EnumDefaults.DEFAULT)); getLog().info("MetaData Mojo > Create Loader: " + loader.toString()); diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index f880efc6a2..191d9ccc9a 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -295,6 +295,8 @@ public enum ErrorCode { /** @flattenedColumnPrefix on a field.object whose @storage is not "flattened" (absent is jsonb). */ ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, + ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, /** @storage was set on a field that has no @objectRef. */ ERR_STORAGE_WITHOUT_OBJECT_REF, diff --git a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java index ec99e0c8c5..de98496cd6 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java +++ b/server/java/metadata/src/main/java/com/metaobjects/MetaRoot.java @@ -213,6 +213,22 @@ public void setPhysicalNaming(com.metaobjects.database.PhysicalNaming physicalNa private transient com.metaobjects.config.WireFormat wireFormat = com.metaobjects.config.WireFormat.DEFAULT; + /** + * The project's enum storage defaults ({@code enums} in {@code .metaobjects/config.json}), + * set by the same project-aware load as the naming rules and read through + * {@link com.metaobjects.config.EnumDefaults#of(MetaData)}. A tree loaded with no project has none. + */ + private transient com.metaobjects.config.EnumDefaults enumDefaults = + com.metaobjects.config.EnumDefaults.DEFAULT; + + public com.metaobjects.config.EnumDefaults getEnumDefaults() { + return enumDefaults; + } + + public void setEnumDefaults(com.metaobjects.config.EnumDefaults enumDefaults) { + this.enumDefaults = (enumDefaults != null) ? enumDefaults : com.metaobjects.config.EnumDefaults.DEFAULT; + } + /** The project's wire-format setting for this tree. Never {@code null}. */ public com.metaobjects.config.WireFormat getWireFormat() { return wireFormat; diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/EnumDefaults.java b/server/java/metadata/src/main/java/com/metaobjects/config/EnumDefaults.java new file mode 100644 index 0000000000..2a0c19006c --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/config/EnumDefaults.java @@ -0,0 +1,35 @@ +package com.metaobjects.config; + +import com.metaobjects.MetaData; +import com.metaobjects.MetaRoot; + +/** + * The project's enum storage defaults: {@code enums} in {@code .metaobjects/config.json}. + * {@code maxLength} is the column length (VARCHAR(n)) of a string-stored {@code field.enum} + * that declares no {@code @maxLength}; absent means no default (an unbounded text column). + * Carried on the loaded root beside the naming rules. Mirrors TS {@code enum-length.ts}. + */ +public final class EnumDefaults { + + /** No project default. */ + public static final EnumDefaults DEFAULT = new EnumDefaults(null); + + private final Long maxLength; + + public EnumDefaults(Long maxLength) { + this.maxLength = maxLength; + } + + /** The default column length, or {@code null} when the project declares none. */ + public Long getMaxLength() { + return maxLength; + } + + /** The enum defaults for the tree {@code node} belongs to: what its root carries, else none. */ + public static EnumDefaults of(MetaData node) { + for (MetaData n = node; n != null; n = n.getParent()) { + if (n instanceof MetaRoot root) return root.getEnumDefaults(); + } + return DEFAULT; + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java index 7c30658a46..90d234b8a6 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/NeutralConfig.java @@ -69,6 +69,7 @@ public final class NeutralConfig { private final List migrateScope; private final PhysicalNaming physicalNaming; private final WireFormat wireFormat; + private EnumDefaults enumDefaults = EnumDefaults.DEFAULT; private NeutralConfig(List> sources, List> dependencies, List scopeInclude, List migrateScope, @@ -134,6 +135,11 @@ public WireFormat getWireFormat() { return wireFormat; } + /** The project's enum storage defaults ({@code enums} in this file). Never {@code null}. */ + public EnumDefaults getEnumDefaults() { + return enumDefaults; + } + /** * Returns empty when {@code /.metaobjects/config.json} does not exist. * A file that EXISTS but is malformed throws — swallowing it would make a typo'd @@ -328,8 +334,41 @@ public static NeutralConfig parse(String content, String origin) { // Unknown top-level keys, and every key of `scope`/`migrate` but the two read above, // are IGNORED by design — see the class javadoc. - return new NeutralConfig(specs, dependencies, scopeInclude, migrateScope, physicalNaming, + NeutralConfig cfg = new NeutralConfig(specs, dependencies, scopeInclude, migrateScope, physicalNaming, wireFormat); + cfg.enumDefaults = parseEnums(root.get("enums"), origin); + return cfg; + } + + /** + * The {@code enums} block: {@code maxLength}, a positive integer, is the column length of a + * string-stored enum with no {@code @maxLength}. An unknown key, a wrong-typed value, or a + * non-object block is refused, the same rule as {@code naming}. + */ + private static EnumDefaults parseEnums(JsonElement enums, String origin) { + if (enums == null) return EnumDefaults.DEFAULT; + if (!enums.isJsonObject()) { + throw new MetaDataException(origin + ": \"enums\" must be an object", ErrorCode.ERR_BAD_ATTR_VALUE); + } + Long maxLength = null; + JsonObject obj = enums.getAsJsonObject(); + for (String key : obj.keySet()) { + if (!"maxLength".equals(key)) { + throw new MetaDataException( + origin + ": \"enums\" has unknown key \"" + key + "\"; expected \"maxLength\"", + ErrorCode.ERR_BAD_ATTR_VALUE); + } + JsonElement v = obj.get(key); + java.math.BigDecimal n = v.isJsonPrimitive() && v.getAsJsonPrimitive().isNumber() + ? v.getAsBigDecimal() : null; + if (n == null || n.signum() <= 0 || n.stripTrailingZeros().scale() > 0) { + throw new MetaDataException( + origin + ": \"enums.maxLength\" must be a positive integer", + ErrorCode.ERR_BAD_ATTR_VALUE); + } + maxLength = n.longValueExact(); + } + return maxLength == null ? EnumDefaults.DEFAULT : new EnumDefaults(maxLength); } /** Mirrors the TS {@code DependencyName} regex (DESIGN §3.1). */ diff --git a/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java b/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java index b9985dbc8a..fac3312f07 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java +++ b/server/java/metadata/src/main/java/com/metaobjects/config/SourceResolver.java @@ -225,6 +225,11 @@ public static java.util.Optional discoverWireFormat(List discoverEnumDefaults(List uris) { + return discoverConfig(uris).map(NeutralConfig::getEnumDefaults); + } + /** * ADR-0058 — the physical-naming rules of the {@code .metaobjects/config.json} found by * walking up from the first {@code file:} URI (stopping after a directory holding diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java new file mode 100644 index 0000000000..195b6290cd --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java @@ -0,0 +1,64 @@ +package com.metaobjects.database; + +import com.metaobjects.ErrorCode; +import com.metaobjects.MetaData; +import com.metaobjects.MetaDataException; +import com.metaobjects.config.EnumDefaults; +import com.metaobjects.field.EnumField; +import com.metaobjects.field.MetaField; +import com.metaobjects.object.MetaObject; +import com.metaobjects.util.ErrorMessageConstants; + +import java.util.List; + +/** + * The column length of a string-stored {@code field.enum}: its {@code @maxLength}, else the + * project's {@code enums.maxLength}, else none (an unbounded text column). Mirrors TS + * {@code resolveEnumMaxLength}. + */ +public final class EnumLength { + + private EnumLength() {} + + /** + * The column length of {@code field}, a string-stored {@code field.enum}: its + * {@code @maxLength} (ADR-0039 — resolving), else the project default, else {@code null}. + * {@code null} for an {@code @intValueMap} enum, whose column is an integer, and for any + * other field. + * + *

The loader refuses an {@code @maxLength} a member does not fit; it does not see the + * project config, so a member longer than the project DEFAULT is refused here + * ({@code ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH}), by every consumer that sizes the column.

+ */ + public static Long resolveMaxLength(MetaField field) { + if (!(field instanceof EnumField) || field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null; + if (field.hasMetaAttr(EnumField.ATTR_MAX_LENGTH)) { + Object own = field.getMetaAttr(EnumField.ATTR_MAX_LENGTH).getValue(); + if (own instanceof Number n) return n.longValue(); + } + Long fallback = EnumDefaults.of(field).getMaxLength(); + if (fallback == null) return null; + String longest = null; + Object raw = field.hasMetaAttr(EnumField.ATTR_VALUES) + ? field.getMetaAttr(EnumField.ATTR_VALUES).getValue() : null; + if (raw instanceof List values) { + for (Object o : values) { + String v = String.valueOf(o); + if (longest == null || v.length() > longest.length()) longest = v; + } + } + if (longest != null && longest.length() > fallback) { + MetaData owner = field.getParent(); + String label = owner instanceof MetaObject o + ? o.getShortName() + "." + field.getShortName() : field.getShortName(); + throw new MetaDataException( + ErrorMessageConstants.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH + + ": field.enum \"" + label + "\" has the member \"" + longest + "\" (" + + longest.length() + " characters), longer than the project's enums.maxLength " + + fallback + ". Give the field its own @maxLength of at least " + longest.length() + + ", raise enums.maxLength, or shorten the member.", + ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH); + } + return fallback; + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java b/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java index f8d86f6fe4..9bae5e39bb 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java +++ b/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java @@ -63,6 +63,9 @@ public class EnumField extends PrimitiveField { */ public static final String ATTR_VALUES = "values"; + /** The column length of a string-stored enum. Same name as {@link StringField#ATTR_MAX_LENGTH}. */ + public static final String ATTR_MAX_LENGTH = StringField.ATTR_MAX_LENGTH; + /** * Name of the optional off-vocabulary → canonical-member alias map (properties). * Consumed by FR-010 extract: maps raw input tokens to their canonical enum member. @@ -221,6 +224,13 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(com.metaobjects.attr.IntMapAttribute.SUBTYPE_INT_MAP) .asSingle(); + // Optional @maxLength — the column length of a string-stored enum (VARCHAR(n)). + // Every member must fit, and it is refused beside @intValueMap; both checked + // post-load in ValidationPhase.validateEnumMaxLength. + def.optionalAttributeWithConstraints(ATTR_MAX_LENGTH) + .ofType(com.metaobjects.attr.IntAttribute.SUBTYPE_INT) + .asSingle(); + // FR-033: @enumDoc and @coerceDefault are re-homed to the // metaobjects-prompt concern provider (reads // spec/metamodel/prompt.json's field.enum extends). diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java b/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java index 28b6c0326b..f1e8cf62dd 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/MetaDataLoader.java @@ -732,6 +732,9 @@ public static MetaDataLoader fromDirectory(String name, Path directory, loader.getRoot().setWireFormat(com.metaobjects.config.SourceResolver .discoverWireFormat(List.of(directory.toAbsolutePath().toUri())) .orElse(com.metaobjects.config.WireFormat.DEFAULT)); + loader.getRoot().setEnumDefaults(com.metaobjects.config.SourceResolver + .discoverEnumDefaults(List.of(directory.toAbsolutePath().toUri())) + .orElse(com.metaobjects.config.EnumDefaults.DEFAULT)); } catch (MetaDataLoadingException e) { throw e; } catch (Exception e) { @@ -819,6 +822,8 @@ public static MetaDataLoader fromUris(String name, List uris, LoaderOptions // ADR-0019 Amendment 2: the wire setting from the same file, else the native default. loader.getRoot().setWireFormat(com.metaobjects.config.SourceResolver .discoverWireFormat(uris).orElse(com.metaobjects.config.WireFormat.DEFAULT)); + loader.getRoot().setEnumDefaults(com.metaobjects.config.SourceResolver + .discoverEnumDefaults(uris).orElse(com.metaobjects.config.EnumDefaults.DEFAULT)); } catch (MetaDataLoadingException e) { throw e; } catch (Exception e) { diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 9f059bcd7c..7d2f88af61 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -262,6 +262,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // FR-024 B6 — derived-field providability (entity origin fields need a read source). pass(collected, () -> validateDerivedFieldProvidability(root)); pass(collected, () -> validateObjectFieldStorage(root)); + pass(collected, () -> validateEnumMaxLength(root)); pass(collected, () -> validateFieldMap(root)); pass(collected, () -> validateIdentityFieldsAndGeneration(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). @@ -2369,6 +2370,70 @@ private static List junctionReferenceFkFields(MetaObject junction) { // already rejected by the constraint phase. // ========================================================================= + // ========================================================================= + // field.enum @maxLength — the column length of a string-stored enum: + // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the + // longest offender named; + // 2. it is refused beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP). + // Read RESOLVING (ADR-0039), reported on the node that DECLARES one of the three, so an + // enum that only inherits them is not reported twice. Every field.enum in the tree is + // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. + // ========================================================================= + + static void validateEnumMaxLength(MetaRoot root) { + walkEnumMaxLength(root); + } + + private static void walkEnumMaxLength(MetaData node) { + for (MetaData child : node.getChildren(MetaData.class, false)) { + if (child instanceof EnumField) { + validateEnumMaxLengthNode((EnumField) child); + } else if (!(child instanceof com.metaobjects.field.MetaField)) { + walkEnumMaxLength(child); + } + } + } + + private static void validateEnumMaxLengthNode(EnumField field) { + boolean declares = field.hasMetaAttr(EnumField.ATTR_MAX_LENGTH, false) + || field.hasMetaAttr(EnumField.ATTR_VALUES, false) + || field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP, false); + if (!declares || !field.hasMetaAttr(EnumField.ATTR_MAX_LENGTH)) return; + Object rawLength = field.getMetaAttr(EnumField.ATTR_MAX_LENGTH).getValue(); + if (!(rawLength instanceof Number)) return; + long maxLength = ((Number) rawLength).longValue(); + MetaData owner = field.getParent(); + String label = owner instanceof MetaObject + ? ((MetaObject) owner).getShortName() + "." + field.getShortName() + : field.getShortName(); + if (field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) { + throw new MetaDataException( + ErrorMessageConstants.ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP + + ": field.enum \"" + label + "\" sets @maxLength " + maxLength + + " and @intValueMap; an @intValueMap enum is stored as an integer, so a column" + + " length does not apply. Remove @maxLength.", + ErrorCode.ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, field.getSource()); + } + String tooLong = null; + Object raw = field.hasMetaAttr(EnumField.ATTR_VALUES) + ? field.getMetaAttr(EnumField.ATTR_VALUES).getValue() : null; + if (raw instanceof List) { + for (Object o : (List) raw) { + String v = String.valueOf(o); + if (v.length() > maxLength && (tooLong == null || v.length() > tooLong.length())) tooLong = v; + } + } + if (tooLong != null) { + throw new MetaDataException( + ErrorMessageConstants.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH + + ": field.enum \"" + label + "\" @maxLength " + maxLength + + " is shorter than its member \"" + tooLong + "\" (" + tooLong.length() + + " characters). Raise @maxLength to at least " + tooLong.length() + + ", or shorten the member.", + ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, field.getSource()); + } + } + static void validateObjectFieldStorage(MetaRoot root) { walkObjectFieldStorage(root); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java index dd64b5f2a2..87f7bda1de 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java +++ b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java @@ -177,6 +177,20 @@ private ErrorMessageConstants() { public static final String ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE = "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE"; + /** + * A string-stored {@code field.enum}'s {@code @maxLength} (its column length) is shorter + * than one of its {@code @values} members, or the project's {@code enums.maxLength} is. + * Cross-language contract: {@code ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH}. + */ + public static final String ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH = "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH"; + + /** + * A {@code field.enum} sets both {@code @maxLength} and {@code @intValueMap}: an int-stored + * enum's column is an integer, so a length would change nothing. + * Cross-language contract: {@code ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP}. + */ + public static final String ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP"; + /** * Error code emitted when {@code field.object @storage} is set on a field that * has no {@code @objectRef} — storage shape only applies to referenced objects. diff --git a/server/java/metadata/src/test/java/com/metaobjects/database/EnumLengthConformanceTest.java b/server/java/metadata/src/test/java/com/metaobjects/database/EnumLengthConformanceTest.java new file mode 100644 index 0000000000..ae4386fc07 --- /dev/null +++ b/server/java/metadata/src/test/java/com/metaobjects/database/EnumLengthConformanceTest.java @@ -0,0 +1,112 @@ +package com.metaobjects.database; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.ErrorCode; +import com.metaobjects.MetaDataException; +import com.metaobjects.config.EnumDefaults; +import com.metaobjects.config.NeutralConfig; +import com.metaobjects.field.MetaField; +import com.metaobjects.loader.FileSource; +import com.metaobjects.loader.LoaderOptions; +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.object.MetaObject; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * The shared cross-port enum-length corpus ({@code fixtures/enum-length-conformance/}) run + * against the Java port: each case's {@code enums} block parsed with {@link NeutralConfig} + * (the reader every project-aware load uses), put on the loaded {@code meta.enums.json} root, + * and every Ticket enum's column length resolved through {@link EnumLength#resolveMaxLength}. + * Each {@code overflow} case is refused with {@code ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH}, and + * each {@code invalid} block when the config is read. + */ +public class EnumLengthConformanceTest extends SharedRegistryTestBase { + + private static Path corpusDir() { + Path dir = Paths.get("").toAbsolutePath(); + while (dir != null && !Files.isDirectory(dir.resolve("fixtures"))) dir = dir.getParent(); + if (dir == null) throw new IllegalStateException("could not locate the repository fixtures/ directory"); + return dir.resolve("fixtures/enum-length-conformance"); + } + + private static JsonObject corpus() throws IOException { + return JsonParser.parseString(new String( + Files.readAllBytes(corpusDir().resolve("cases.json")), StandardCharsets.UTF_8)).getAsJsonObject(); + } + + private static EnumDefaults parseEnums(JsonElement enums) { + JsonObject doc = new JsonObject(); + doc.addProperty("schema_version", 1); + if (enums != null && !enums.isJsonNull()) doc.add("enums", enums); + return NeutralConfig.parse(doc.toString(), "enum-length-corpus").getEnumDefaults(); + } + + private MetaField ticketField(EnumDefaults defaults, String name) throws IOException { + MetaDataLoader loader = new MetaDataLoader( + LoaderOptions.create(false, false, true), MetaDataLoader.SUBTYPE_MANUAL, "enum_length_conformance"); + loader.init(); + loader.load(List.of(new FileSource(corpusDir().resolve("meta.enums.json")))); + if (!loader.getErrors().isEmpty()) fail("expected a clean load, got: " + loader.getErrors()); + loader.getRoot().setEnumDefaults(defaults); + for (MetaObject obj : loader.getMetaObjects()) { + if (obj.getShortName().equals("Ticket")) return obj.getMetaField(name); + } + throw new AssertionError("no Ticket in the corpus model"); + } + + @Test + public void resolvesEveryEnumColumnLength() throws IOException { + for (JsonElement el : corpus().getAsJsonArray("cases")) { + JsonObject c = el.getAsJsonObject(); + EnumDefaults defaults = parseEnums(c.get("enums")); + for (Map.Entry e : c.getAsJsonObject("lengths").entrySet()) { + Long expected = e.getValue().isJsonNull() ? null : e.getValue().getAsLong(); + assertEquals(c.get("name").getAsString() + ": " + e.getKey(), + expected, EnumLength.resolveMaxLength(ticketField(defaults, e.getKey()))); + } + } + } + + @Test + public void refusesAMemberLongerThanTheProjectDefault() throws IOException { + for (JsonElement el : corpus().getAsJsonArray("overflow")) { + JsonObject o = el.getAsJsonObject(); + MetaField field = ticketField(parseEnums(o.get("enums")), o.get("field").getAsString()); + try { + EnumLength.resolveMaxLength(field); + fail(o.get("name").getAsString() + ": expected a refusal"); + } catch (MetaDataException e) { + assertEquals(java.util.Optional.of(ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), e.getCode()); + assertTrue(e.getMessage(), e.getMessage().contains(o.get("member").getAsString())); + } + } + } + + @Test + public void refusesAnInvalidEnumsBlock() throws IOException { + for (JsonElement el : corpus().getAsJsonArray("invalid")) { + JsonObject bad = el.getAsJsonObject(); + try { + parseEnums(bad.get("enums")); + fail(bad.get("name").getAsString() + ": expected the config to be refused"); + } catch (MetaDataException expected) { + // refused when read + } + } + } +} diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index f28d2d9ea8..905a68989b 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -62,6 +62,7 @@ from pathlib import Path from typing import Any, Callable +from metaobjects.enum_length import EnumDefaults from metaobjects import MetaDataLoader from metaobjects.errors import ErrorCode, MetaError, ParseError from metaobjects.config.dependencies import ( @@ -508,6 +509,7 @@ def load(strict_load: bool) -> LoadResult: # invocation) read the same values `gen`/`verify --codegen` would. result.root.naming = neutral.naming if neutral is not None else NamingRules() result.root.wire = neutral.wire if neutral is not None else WireFormat() + result.root.enum_defaults = neutral.enums if neutral is not None else EnumDefaults() return result.root, [] @@ -571,6 +573,7 @@ def _load_collection_result( # it to the loaded root so codegen, the runtime and `verify` agree. result.root.naming = collection.naming result.root.wire = collection.wire + result.root.enum_defaults = collection.enums return result diff --git a/server/python/src/metaobjects/config/dependencies.py b/server/python/src/metaobjects/config/dependencies.py index 039baabc84..11fd3b935f 100644 --- a/server/python/src/metaobjects/config/dependencies.py +++ b/server/python/src/metaobjects/config/dependencies.py @@ -16,6 +16,7 @@ from metaobjects.errors import ErrorCode, ParseError from metaobjects.meta.meta_data import MetaData +from metaobjects.enum_length import EnumDefaults from metaobjects.naming import NamingRules, package_of_resolution_key from metaobjects.wire import WireFormat from metaobjects.registry_manifest import METAMODEL_VERSION @@ -664,6 +665,9 @@ class Collection: #: attached to the loaded root beside `naming`. wire: WireFormat = WireFormat() + #: The project's `enums` block, read at the same rung; attached beside `naming`. + enums: EnumDefaults = EnumDefaults() + def imported(self, fqn: str) -> bool: """Is `fqn` in a package one of this project's dependencies owns?""" return package_of_resolution_key(fqn) in self.imported_packages diff --git a/server/python/src/metaobjects/config/neutral_config.py b/server/python/src/metaobjects/config/neutral_config.py index 93bfd7495c..9f53a3f49e 100644 --- a/server/python/src/metaobjects/config/neutral_config.py +++ b/server/python/src/metaobjects/config/neutral_config.py @@ -5,6 +5,7 @@ from dataclasses import dataclass from pathlib import Path +from metaobjects.enum_length import EnumDefaults from metaobjects.errors import ErrorCode, ParseError from metaobjects.naming import COLUMN_NAMING_STRATEGIES, TABLE_NAMING_RULES, NamingRules from metaobjects.wire import WIRE_DECIMALS, WIRE_NULL_MEMBERS, WireFormat @@ -82,6 +83,11 @@ class NeutralConfig: #: for the same reason `naming` is. wire: WireFormat = WireFormat() + #: The `enums` block: `maxLength`, the column length of a string-stored enum with no + #: @maxLength. Absent or `{}` ⇒ no default. Attached to the loaded root + #: (`MetaRoot.enum_defaults`) beside `naming`; validated HERE for the same reason. + enums: EnumDefaults = EnumDefaults() + def find_project_dir(start: Path) -> Path | None: """The nearest directory at or above *start* that holds ``.metaobjects/config.json``, @@ -175,6 +181,7 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: libraries = _read_libraries(raw, path) naming = _read_naming(raw, path) wire = _read_wire(raw, path) + enums = _read_enums(raw, path) # Unknown top-level keys are IGNORED by design — see the module docstring. return NeutralConfig( @@ -185,6 +192,7 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: libraries=libraries, naming=naming, wire=wire, + enums=enums, ) @@ -305,6 +313,37 @@ def _read_naming(raw: dict[str, object], path: Path) -> NamingRules: return NamingRules(columns=columns, tables=tables) +#: Every key the `enums` block accepts, and the ONLY ones it accepts (refused, not ignored, like `naming`). +_ENUMS_KEYS = ("maxLength",) + + +def _read_enums(raw: dict[str, object], path: Path) -> EnumDefaults: + """The `enums` block: `maxLength`, a positive integer, is the column length of a + string-stored enum with no @maxLength. Absent or `{}` ⇒ no default. Refuses a non-object + block, an unknown key, or a value that is not a positive integer, the same rule as + `naming`.""" + if "enums" not in raw: + return EnumDefaults() + enums = raw["enums"] + if not isinstance(enums, dict): + raise ParseError(f"{path}: 'enums' must be an object", code=ErrorCode.ERR_BAD_ATTR_VALUE) + unknown = sorted(set(enums) - set(_ENUMS_KEYS)) + if unknown: + raise ParseError( + f"{path}: 'enums' has unknown key(s) {unknown}; accepted: {list(_ENUMS_KEYS)}", + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + if "maxLength" not in enums: + return EnumDefaults() + value = enums["maxLength"] + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ParseError( + f"{path}: 'enums.maxLength' must be a positive integer, got {value!r}", + code=ErrorCode.ERR_BAD_ATTR_VALUE, + ) + return EnumDefaults(max_length=value) + + #: Every key the `wire` block accepts, and the ONLY ones it accepts (refused, not ignored, like `naming`). _WIRE_KEYS = ("decimals", "nullMembers") diff --git a/server/python/src/metaobjects/config/source_resolver.py b/server/python/src/metaobjects/config/source_resolver.py index 87c4879da2..2b3807d031 100644 --- a/server/python/src/metaobjects/config/source_resolver.py +++ b/server/python/src/metaobjects/config/source_resolver.py @@ -6,6 +6,7 @@ from metaobjects.errors import ErrorCode, ParseError from metaobjects.loader.sources import DirectorySource +from metaobjects.enum_length import EnumDefaults from metaobjects.naming import NamingRules, package_of_resolution_key from metaobjects.wire import WireFormat from metaobjects.scope import compile_scope, matches_scope @@ -157,6 +158,7 @@ def _collection_from_own_files( libraries: list[str] = cfg.libraries if cfg is not None else [] naming: NamingRules = cfg.naming if cfg is not None else NamingRules() wire: WireFormat = cfg.wire if cfg is not None else WireFormat() + enums: EnumDefaults = cfg.enums if cfg is not None else EnumDefaults() lock = read_lock(root) dependencies: list[ResolvedDependency] = ( @@ -188,6 +190,7 @@ def _collection_from_own_files( libraries=tuple(libraries), naming=naming, wire=wire, + enums=enums, ) diff --git a/server/python/src/metaobjects/enum_length.py b/server/python/src/metaobjects/enum_length.py new file mode 100644 index 0000000000..1d3a85ab4e --- /dev/null +++ b/server/python/src/metaobjects/enum_length.py @@ -0,0 +1,79 @@ +"""The column length of a string-stored ``field.enum``: its ``@maxLength``, else the project's +``enums.maxLength`` (in ``.metaobjects/config.json``, carried on the loaded root beside the +naming rules), else none — an unbounded text column. Mirrors TS ``enum-length.ts``.""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +from .errors import ErrorCode, ParseError +from .meta.core.field.field_constants import ( + FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_MAX_LENGTH, + FIELD_ATTR_VALUES, + FIELD_SUBTYPE_ENUM, +) +from .shared.base_types import TYPE_OBJECT + +if TYPE_CHECKING: + from .meta.meta_data import MetaData + + +@dataclass(frozen=True) +class EnumDefaults: + """The resolved ``enums`` block. ``max_length`` is the column length of a string-stored + enum that declares no ``@maxLength``; ``None`` means no default.""" + + max_length: int | None = None + + +def enum_defaults_of(node: "MetaData") -> EnumDefaults: + """The enum defaults for the tree *node* belongs to: what its root carries, else none.""" + cur = node + while cur.parent is not None: + cur = cur.parent + defaults = getattr(cur, "enum_defaults", None) + return defaults if isinstance(defaults, EnumDefaults) else EnumDefaults() + + +def resolve_enum_max_length(field: "MetaData") -> int | None: + """The column length of *field*, a string-stored ``field.enum``: its ``@maxLength`` + (ADR-0039 — resolving), else the project default, else ``None``. ``None`` for an + ``@intValueMap`` enum, whose column is an integer, and for any other field. + + The loader refuses an ``@maxLength`` a member does not fit; it does not see the project + config, so a member longer than the project DEFAULT is refused here + (``ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH``), by every consumer that sizes the column. + """ + if field.sub_type != FIELD_SUBTYPE_ENUM or field.get_meta_attr(FIELD_ATTR_INT_VALUE_MAP) is not None: + return None + own = field.get_meta_attr(FIELD_ATTR_MAX_LENGTH) + if isinstance(own, int) and not isinstance(own, bool): + return own + fallback = enum_defaults_of(field).max_length + if fallback is None: + return None + values = field.get_meta_attr(FIELD_ATTR_VALUES) + members = [v for v in (values if isinstance(values, list) else []) if isinstance(v, str)] + longest = max(members, key=len, default=None) + if longest is not None and len(longest) > fallback: + owner = field.parent + label = f"{owner.name}.{field.name}" if owner is not None and owner.type == TYPE_OBJECT else field.name + raise ParseError( + f'field.enum "{label}" has the member "{longest}" ({len(longest)} characters), longer ' + f"than the project's enums.maxLength {fallback}. Give the field its own @maxLength of " + f"at least {len(longest)}, raise enums.maxLength, or shorten the member.", + code=ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + ) + return fallback + + +def attach_enum_defaults(root: "MetaData", project_dir: Path) -> "MetaData": + """Set ``root.enum_defaults`` from *project_dir*'s ``.metaobjects/config.json`` and return + *root*, for a load site that bypasses the CLI's collection ladder.""" + from .config.neutral_config import read_neutral_config + + cfg = read_neutral_config(project_dir) + root.enum_defaults = cfg.enums if cfg is not None else EnumDefaults() # type: ignore[attr-defined] + return root diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index 297f672242..b3300b564e 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -205,6 +205,8 @@ class ErrorCode(str, Enum): # folds `userId` and `userID` together, or two fields share an @column). ERR_COLUMN_NAME_COLLISION = "ERR_COLUMN_NAME_COLLISION" ERR_STORAGE_FLATTENED_ARRAY = "ERR_STORAGE_FLATTENED_ARRAY" + ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH = "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" + ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP" ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE = ( "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE" ) diff --git a/server/python/src/metaobjects/loader/meta_data_loader.py b/server/python/src/metaobjects/loader/meta_data_loader.py index 4589a04003..917e7aca1c 100644 --- a/server/python/src/metaobjects/loader/meta_data_loader.py +++ b/server/python/src/metaobjects/loader/meta_data_loader.py @@ -60,11 +60,13 @@ def _apply_discovered_naming(result: "LoadResult", start: Path) -> None: from ..config.neutral_config import find_project_dir from ..naming import attach_naming from ..wire import attach_wire + from ..enum_length import attach_enum_defaults project = find_project_dir(start if start.is_dir() else start.parent) if project is not None: attach_naming(result.root, project) attach_wire(result.root, project) + attach_enum_defaults(result.root, project) return warnings.warn( f"no .metaobjects/config.json found at or above {start}: physical names use the " diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 241fac62f5..024216fa1c 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -28,6 +28,7 @@ FIELD_ATTR_COERCE_DEFAULT, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_REQUIRED, FIELD_ATTR_SORTABLE, @@ -248,6 +249,8 @@ def run_validations( # FR-015 — source.rdb @parameterRef typed-input rules. validate_source_parameter_ref(root, errors) _validate_field_object_storage(root, errors) + # field.enum @maxLength — every member fits; refused with @intValueMap. + _validate_enum_max_length(root, errors) # field.map — exactly one of @valueType (scalar) or @objectRef (VO), and # @valueType (when set) must name a known scalar subtype. _validate_field_map(root, errors) @@ -3717,6 +3720,54 @@ def _validate_sortable_has_supported_subtype( # members columns of their own to prefix). +# field.enum @maxLength — the column length of a string-stored enum: +# 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the longest +# offender named; +# 2. it is refused beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP). +# Read RESOLVING (ADR-0039), reported on the node that DECLARES one of the three, so an enum +# that only inherits them is not reported twice. Mirrors TS validateEnumMaxLength. +def _validate_enum_max_length(root: MetaData, errors: list[MetaError]) -> None: + for node in _walk(root): + if node.type != TYPE_FIELD or node.sub_type != FIELD_SUBTYPE_ENUM: + continue + declares = any( + node.attr(a) is not None + for a in (FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP) + ) + max_length = node.get_meta_attr(FIELD_ATTR_MAX_LENGTH) # ADR-0039 resolving + if not declares or not isinstance(max_length, int) or isinstance(max_length, bool): + continue + owner = node.parent + label = f"{owner.name}.{node.name}" if owner is not None and owner.type == TYPE_OBJECT else node.name + if node.get_meta_attr(FIELD_ATTR_INT_VALUE_MAP) is not None: + errors.append(MetaError( + code=ErrorCode.ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, + message=( + f'field.enum "{label}" sets @maxLength {max_length} and @intValueMap; an ' + f"@intValueMap enum is stored as an integer, so a column length does not " + f"apply. Remove @maxLength." + ), + envelope=node.source, + )) + continue + values = node.get_meta_attr(FIELD_ATTR_VALUES) + too_long = sorted( + (v for v in (values if isinstance(values, list) else []) if isinstance(v, str) and len(v) > max_length), + key=len, + reverse=True, + ) + if too_long: + errors.append(MetaError( + code=ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + message=( + f'field.enum "{label}" @maxLength {max_length} is shorter than its member ' + f'"{too_long[0]}" ({len(too_long[0])} characters). Raise @maxLength to at ' + f"least {len(too_long[0])}, or shorten the member." + ), + envelope=node.source, + )) + + def _validate_field_object_storage(root: MetaData, errors: list[MetaError]) -> None: for node in _walk(root): if node.type != TYPE_FIELD or node.sub_type != FIELD_SUBTYPE_OBJECT: diff --git a/server/python/src/metaobjects/meta/meta_root.py b/server/python/src/metaobjects/meta/meta_root.py index 81f0156d02..38e16100a4 100644 --- a/server/python/src/metaobjects/meta/meta_root.py +++ b/server/python/src/metaobjects/meta/meta_root.py @@ -2,6 +2,7 @@ from __future__ import annotations from ..naming import NamingRules +from ..enum_length import EnumDefaults from ..wire import WireFormat from .meta_data import MetaData @@ -21,3 +22,6 @@ def __init__(self, type_: str, sub_type: str, name: str) -> None: # REST surface), attached by the same project-aware loads as `naming`; read with # `wire_of()`. `native` for both keys until a load attaches the project's own. self.wire: WireFormat = WireFormat() + # The project `enums` block (string-stored enum column length), attached by the same + # project-aware loads as `naming`; read with `enum_defaults_of()`. None by default. + self.enum_defaults: EnumDefaults = EnumDefaults() diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index b054bda765..847f0ea66e 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -151,6 +151,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, + { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } ] }, diff --git a/server/python/tests/conformance/test_enum_length_conformance.py b/server/python/tests/conformance/test_enum_length_conformance.py new file mode 100644 index 0000000000..cb8deba076 --- /dev/null +++ b/server/python/tests/conformance/test_enum_length_conformance.py @@ -0,0 +1,65 @@ +"""The shared cross-port enum-length corpus (``fixtures/enum-length-conformance/``) run against +the Python port: each case's ``enums`` block is written to a project's +``.metaobjects/config.json`` and read with :func:`read_neutral_config` (the reader the CLI's +load path uses), put on the loaded ``meta.enums.json`` root, and every Ticket enum's column +length resolved through :func:`resolve_enum_max_length`. Each ``overflow`` case must be refused +with ``ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH``, and each ``invalid`` block when the config is read. +""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from metaobjects import FileSource, MetaDataLoader +from metaobjects.config.neutral_config import read_neutral_config +from metaobjects.enum_length import EnumDefaults, resolve_enum_max_length +from metaobjects.errors import ErrorCode, ParseError +from metaobjects.meta.core.object.meta_object import MetaObject +from metaobjects.shared.base_types import TYPE_OBJECT + +REPO = Path(__file__).parents[4] +CORPUS = REPO / "fixtures" / "enum-length-conformance" +_SPEC = json.loads((CORPUS / "cases.json").read_text()) + + +def _read_enums(tmp_path: Path, enums: object) -> EnumDefaults: + raw: dict[str, object] = {"schema_version": 1} + if enums is not None: + raw["enums"] = enums + (tmp_path / ".metaobjects").mkdir(parents=True, exist_ok=True) + (tmp_path / ".metaobjects" / "config.json").write_text(json.dumps(raw), encoding="utf-8") + cfg = read_neutral_config(tmp_path) + return cfg.enums if cfg is not None else EnumDefaults() + + +def _ticket_field(defaults: EnumDefaults, name: str): + result = MetaDataLoader().load([FileSource(CORPUS / "meta.enums.json")]) + assert not result.errors, [f"{e.code}: {e.message}" for e in result.errors] + result.root.enum_defaults = defaults + ticket = next(c for c in result.root.children() if c.type == TYPE_OBJECT and c.name == "Ticket") + assert isinstance(ticket, MetaObject) + return next(f for f in ticket.fields() if f.name == name) + + +@pytest.mark.parametrize("case", _SPEC["cases"], ids=lambda c: c["name"]) +def test_resolves_every_enum_column_length(case: dict, tmp_path: Path) -> None: + defaults = _read_enums(tmp_path, case["enums"]) + actual = {name: resolve_enum_max_length(_ticket_field(defaults, name)) for name in case["lengths"]} + assert actual == case["lengths"] + + +@pytest.mark.parametrize("case", _SPEC["overflow"], ids=lambda c: c["name"]) +def test_refuses_a_member_longer_than_the_project_default(case: dict, tmp_path: Path) -> None: + field = _ticket_field(_read_enums(tmp_path, case["enums"]), case["field"]) + with pytest.raises(ParseError) as exc: + resolve_enum_max_length(field) + assert exc.value.code == ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH + assert case["member"] in str(exc.value) + + +@pytest.mark.parametrize("case", _SPEC["invalid"], ids=lambda c: c["name"]) +def test_refuses_an_invalid_enums_block(case: dict, tmp_path: Path) -> None: + with pytest.raises(ParseError): + _read_enums(tmp_path, case["enums"]) diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index 0320c1cc5d..29d5bea596 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -1,4 +1,5 @@ import { resolve as resolvePath } from "node:path"; +import { ENUM_LENGTH_HINT, isEnumLengthRefusal } from "../lib/enum-length-refusal.js"; import { mkdir } from "node:fs/promises"; import { existsSync } from "node:fs"; import { spawn } from "node:child_process"; @@ -1172,6 +1173,8 @@ export async function migrateCommand( if (isDuplicateSqlNameError(err)) return refuseEngineError(err, DUPLICATE_SQL_NAME_HINT, fmt); // A metadata defect too: a foreign key whose target columns are not a unique key there. if (isFkTargetNotUniqueError(err)) return refuseEngineError(err, FK_TARGET_NOT_UNIQUE_HINT, fmt); + // A metadata defect too: an enum member longer than the project's enums.maxLength. + if (isEnumLengthRefusal(err)) return refuseEngineError(err, ENUM_LENGTH_HINT, fmt); // A config error: `migrate.conventions` names a preset this version does not ship. if (isUnknownSchemaConventionsError(err)) { refuseEngineError(err, "set migrate.conventions in .metaobjects/config.json to one of the presets, or supply your own conventions from metaobjects.config.ts", fmt); diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index c3c6c3058a..1cce63cf60 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -7,6 +7,7 @@ // silently break a prompt" guarantee, enforced at the last fixed point before // the text ships. Required-slot misses are warnings (don't fail the build). +import { ENUM_LENGTH_HINT, isEnumLengthRefusal } from "../lib/enum-length-refusal.js"; import { existsSync } from "node:fs"; import { join, relative, resolve as resolvePath } from "node:path"; import { parseVerifyArgs, type MigrateFlags } from "../lib/args.js"; @@ -1408,6 +1409,11 @@ export async function verifyCommand( log.error("verify: declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"); return 1; } + if (isEnumLengthRefusal(err)) { + log.error(`verify: ${err.message}`); + log.error(`verify: ${ENUM_LENGTH_HINT}`); + return 1; + } if (isUnknownSchemaConventionsError(err)) { log.error(`verify: ${err.message}`); return 2; diff --git a/server/typescript/packages/cli/src/lib/collection-load-options.ts b/server/typescript/packages/cli/src/lib/collection-load-options.ts index 78a7c91bf8..d645e7e465 100644 --- a/server/typescript/packages/cli/src/lib/collection-load-options.ts +++ b/server/typescript/packages/cli/src/lib/collection-load-options.ts @@ -26,7 +26,7 @@ import type { Collection, LoadMemoryOptions } from "@metaobjectsdev/sdk"; */ export function collectionLoadOptions( collection: Collection, -): Required> & Pick { +): Required> & Pick { return { files: collection.files, fileIds: collection.fileIds, @@ -40,6 +40,7 @@ export function collectionLoadOptions( libraries: collection.libraries, physicalNaming: collection.physicalNaming, wireFormat: collection.wireFormat, + enumDefaults: collection.enumDefaults, ...(collection.schemaConventions !== undefined ? { schemaConventions: collection.schemaConventions } : {}), }; } diff --git a/server/typescript/packages/cli/src/lib/enum-length-refusal.ts b/server/typescript/packages/cli/src/lib/enum-length-refusal.ts new file mode 100644 index 0000000000..9f20d669ef --- /dev/null +++ b/server/typescript/packages/cli/src/lib/enum-length-refusal.ts @@ -0,0 +1,16 @@ +/** + * A string-stored enum member longer than the project's `enums.maxLength`: core's + * resolveEnumMaxLength refuses it while the expected schema is built. A metadata (or config) + * defect, so `meta migrate` and `meta verify` report it by name rather than as an + * unexpected error. Matched by name and code, not `instanceof`: two physical copies of + * @metaobjectsdev/metadata in one process give the class two identities. + */ +export const ENUM_LENGTH_CODE = "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH"; + +export const ENUM_LENGTH_HINT = + "give the enum field its own @maxLength that fits its longest member, raise enums.maxLength in .metaobjects/config.json, or shorten the member"; + +export function isEnumLengthRefusal(err: unknown): err is Error { + return err instanceof Error && err.name === "MetaModelError" + && (err as { code?: unknown }).code === ENUM_LENGTH_CODE; +} diff --git a/server/typescript/packages/cli/test/migrate-enum-max-length.test.ts b/server/typescript/packages/cli/test/migrate-enum-max-length.test.ts new file mode 100644 index 0000000000..590d7afea2 --- /dev/null +++ b/server/typescript/packages/cli/test/migrate-enum-max-length.test.ts @@ -0,0 +1,65 @@ +/** + * `enums.maxLength` in .metaobjects/config.json reaches `meta migrate` through the + * project-aware load: an enum with no @maxLength gets VARCHAR(n), and a member longer than + * the default is refused by name — a metadata defect, not an "unexpected error". + */ +import { describe, test, expect, afterAll, beforeEach, afterEach, spyOn } from "bun:test"; +import { mkdtemp, rm, mkdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { migrateCommand } from "../src/commands/migrate.js"; +import { log } from "../src/lib/log.js"; + +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +function model(values: string[]): string { + return JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": values } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ] } }, + ] } }); +} + +async function project(values: string[], maxLength: number): Promise { + const root = await mkdtemp(join(tmpdir(), "enum-max-length-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), model(values), "utf8"); + await mkdir(join(root, ".metaobjects", "migrations"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), + JSON.stringify({ schema_version: 1, enums: { maxLength }, migrate: { dialect: "postgres" } }), "utf8"); + return root; +} + +let out: string[] = []; +let spies: ReturnType[] = []; +beforeEach(() => { + out = []; + spies = (["info", "error", "warn"] as const).map((k) => + spyOn(log, k).mockImplementation((m: string) => { out.push(String(m)); })); +}); +afterEach(() => { for (const s of spies) s.mockRestore(); }); + +const dryRun = (root: string) => + migrateCommand(["--from-db", "--db", `file:${join(root, "t.db")}`, "--dialect", "sqlite", "--dry-run"], root); + +describe("meta migrate with enums.maxLength", () => { + test("an enum with no @maxLength gets the project's length", async () => { + const root = await project(["OPEN", "CLOSED"], 24); + expect(await dryRun(root)).toBe(0); + expect(out.join("\n")).toMatch(/"status" (VARCHAR|varchar)\(24\)/); + }); + + test("a member longer than the default is refused by name, not as an unexpected error", async () => { + const root = await project(["OPEN", "IN_PROGRESS"], 10); + const code = await dryRun(root); + const text = out.join("\n"); + expect(code).toBe(1); + expect(text).toContain('field.enum "Ticket.status" has the member "IN_PROGRESS"'); + expect(text).not.toContain("unexpected error"); + }); +}); diff --git a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts index 73ffa397cb..c41716ac95 100644 --- a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts +++ b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts @@ -78,4 +78,25 @@ describe("meta verify — schema refusals", () => { expect(withDb.code).toBe(2); expect(withDb.out).not.toContain("failed to introspect"); }); + + test("--db: an enum member longer than enums.maxLength is refused by name, not as an introspection failure", async () => { + const root = await mkdtemp(join(tmpdir(), "verify-schema-refusals-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["OPEN", "IN_PROGRESS"] } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, + ] } }, + ] } }), "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, enums: { maxLength: 10 } }), "utf8"); + + const { code, out } = await capture(() => verifyCommand(["--db", `file:${join(root, "t.db")}`], root)); + expect(code).toBe(1); + expect(out).toContain('field.enum "Ticket.status" has the member "IN_PROGRESS"'); + expect(out).not.toContain("failed to introspect"); + }); }); diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index df69132fa4..1fa2e4c2a6 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -45,6 +45,7 @@ import { AGG_ANY, AGG_ALL, AGG_COLLECT, + resolveEnumMaxLength, } from "@metaobjectsdev/metadata"; import { columnNameFromField } from "./naming.js"; import { enumValues, intValueMapOf, intValueForMember } from "./enum-meta.js"; @@ -514,6 +515,10 @@ function mapMysqlColumn( const t = buildEnumIntCustomType(field, im); return t !== undefined ? { fnName: t.fnConstName, enumIntCustomType: t } : { fnName: "int" }; } + // The column `meta migrate` creates: the enum's length (core's resolveEnumMaxLength — + // its @maxLength, else the project's enums.maxLength), else the longest member. + const sized = resolveEnumMaxLength(field); + if (sized !== undefined) return varchar(sized); const values = enumValues(field) ?? []; const longest = values.reduce((n, v) => Math.max(n, v.length), 1); return varchar(longest); @@ -781,7 +786,15 @@ export function mapColumnType( enumIntCustomType = buildEnumIntCustomType(field, im); fnName = enumIntCustomType?.fnConstName ?? "integer"; } else { - fnName = "text"; + // A length (core's resolveEnumMaxLength) is the VARCHAR(n) `meta migrate` + // creates; with none the column is unbounded text, as before. + const sized = resolveEnumMaxLength(field); + if (sized !== undefined) { + fnName = "varchar"; + fnOptions = { length: sized }; + } else { + fnName = "text"; + } } } break; @@ -798,7 +811,9 @@ export function mapColumnType( // arrays use { mode: "json" }, and the enum members go through Zod // validation at the Insert/Update layer instead. Mirrors the Zod // emission, which already uses z.enum([...]). - if (subType === FIELD_SUBTYPE_ENUM && !isArray && (fnName === "text" || (dialect === "mysql" && fnName === "varchar"))) { + // A sized enum is a varchar on Postgres too (resolveEnumMaxLength); pg-core's varchar + // takes the same `enum` option. + if (subType === FIELD_SUBTYPE_ENUM && !isArray && (fnName === "text" || fnName === "varchar")) { const values = enumValues(field); if (values !== undefined && values.length > 0) { fnOptions = { ...(fnOptions ?? {}), enum: values }; diff --git a/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts b/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts index 25869f52e4..1bcfb54331 100644 --- a/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts +++ b/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts @@ -338,6 +338,9 @@ function mysqlColumnType(t: SqlType, field: MetaField, needsLength: boolean): Co return { scalar: "Float", list: false, native: "@db.Float" }; case FIELD_SUBTYPE_ENUM: { if (t.kind === "integer") return { scalar: "Int", list: false }; + // A length the expected schema carries (resolveEnumMaxLength: @maxLength, else the + // project's enums.maxLength) is the column; with none, the longest member sizes it. + if (t.kind === "text" && t.maxLength !== undefined) return varchar(t.maxLength); // ADR-0039: resolving — @values may be inherited. const raw = field.attr(FIELD_ATTR_VALUES); const values = Array.isArray(raw) ? raw.map(String) : []; diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts new file mode 100644 index 0000000000..03496dfc4a --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts @@ -0,0 +1,49 @@ +// A string-stored enum with a column length (its @maxLength, else the project's +// enums.maxLength) binds a varchar of that length, the column `meta migrate` creates; +// with none it stays text on Postgres and sizes to the longest member on MySQL, as before. +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { renderDrizzleSchema } from "../src/templates/drizzle-schema.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import type { Dialect } from "../src/metaobjects-config.js"; + +async function emit(statusDecl: Record, dialect: Dialect, maxLength?: number) { + const json = JSON.stringify({ "metadata.root": { children: [ + { "object.entity": { name: "Order", children: [ + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", ...statusDecl } }, + { "source.rdb": { name: "src", "@table": "orders" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + if (maxLength !== undefined) res.root.enumDefaults = { maxLength }; + const ctx = makeRenderContext({ + dialect, loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root), + }); + return renderDrizzleSchema(res.root.findObject("Order")!, ctx).toString(); +} + +const VALUES = ["DRAFT", "PUBLISHED"]; + +describe("Drizzle: a string-stored enum's column length", () => { + test("Postgres: @maxLength → varchar of that length", async () => { + expect(await emit({ "@values": VALUES, "@maxLength": 16 }, "postgres")).toContain('varchar("status", { length: 16, enum:'); + }); + + test("Postgres: the project default sizes an enum with no @maxLength", async () => { + expect(await emit({ "@values": VALUES }, "postgres", 32)).toContain('varchar("status", { length: 32, enum:'); + }); + + test("Postgres: no length anywhere → text, as before", async () => { + expect(await emit({ "@values": VALUES }, "postgres")).toContain('text("status", { enum:'); + }); + + test("MySQL: @maxLength beats the longest member", async () => { + expect(await emit({ "@values": VALUES, "@maxLength": 16 }, "mysql")).toContain('varchar("status", { length: 16, enum:'); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts index e68c5da270..dbbaf884d9 100644 --- a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts +++ b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts @@ -125,6 +125,18 @@ describe("prisma-schema — what the schema says", () => { expect(spec.checks.map((c) => c.name)).toContain("customers_tier_chk"); }); + test("a string-stored enum with a length is a VarChar of it, on Postgres and MySQL", async () => { + const root = await loadJson(model([entity("Ticket", [ + { "source.rdb": { "@table": "tickets" } }, longId, + { "field.enum": { name: "status", "@values": ["OPEN", "CLOSED"], "@maxLength": 16 } }, pk, + ])])); + for (const provider of ["postgresql", "mysql"] as const) { + const status = buildPrismaSchema(root, { provider }).models.find((m) => m.name === "Ticket")! + .fields.find((f) => f.name === "status")!; + expect(status.attributes).toContain("@db.VarChar(16)"); + } + }); + test("a self relation is named, so its two ends pair", async () => { const spec = buildPrismaSchema(await loadShop(), { provider: "postgresql" }); const employee = spec.models.find((m) => m.name === "Employee")!; diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index 75209e3a82..7162656fe0 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -285,6 +285,14 @@ export const FIELD_DEFINITION: ProviderDefinition = { "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, + { + "type": "attr", + "subType": "int", + "name": "maxLength", + "min": 0, + "max": 1, + "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." + }, { "type": "attr", "subType": "intMap", diff --git a/server/typescript/packages/metadata/src/enum-length.ts b/server/typescript/packages/metadata/src/enum-length.ts new file mode 100644 index 0000000000..568c077adb --- /dev/null +++ b/server/typescript/packages/metadata/src/enum-length.ts @@ -0,0 +1,63 @@ +// The column length of a string-stored field.enum: the field's @maxLength, else the +// project's default (`enums.maxLength` in .metaobjects/config.json, carried on the loaded +// root beside the naming rules), else none — an unbounded text column, as before. + +import type { MetaData } from "./shared/meta-data.js"; +import { MetaModelError } from "./errors.js"; +import { + FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_MAX_LENGTH, + FIELD_ATTR_VALUES, + FIELD_SUBTYPE_ENUM, +} from "./core/field/field-constants.js"; +import { TYPE_OBJECT } from "./shared/base-types.js"; + +/** The `enums` block in `.metaobjects/config.json`. */ +export const ENUMS_KEY_MAX_LENGTH = "maxLength"; + +/** The project's enum storage defaults: `enums` in `.metaobjects/config.json`. */ +export interface EnumDefaults { + /** The column length of a string-stored enum that declares no @maxLength. */ + readonly maxLength?: number | undefined; +} + +/** No project default: an enum with no @maxLength is an unbounded text column. */ +export const DEFAULT_ENUM_DEFAULTS: EnumDefaults = Object.freeze({}); + +/** The enum defaults for the tree `node` belongs to: what its root carries, else none. */ +export function enumDefaultsOf(node: MetaData): EnumDefaults { + const defaults = (node.root() as { enumDefaults?: EnumDefaults }).enumDefaults; + return defaults ?? DEFAULT_ENUM_DEFAULTS; +} + +/** + * The column length of `field`, a string-stored `field.enum`: its @maxLength (ADR-0039 — + * resolving, it may be inherited), else the project default, else undefined. Undefined for + * an @intValueMap enum, whose column is an integer, and for any other field. + * + * The loader refuses an @maxLength a member does not fit; it does not see the project + * config, so a member longer than the project DEFAULT is refused here, by every consumer + * that sizes the column (`meta migrate`, the generated bindings). + */ +export function resolveEnumMaxLength(field: MetaData): number | undefined { + if (field.subType !== FIELD_SUBTYPE_ENUM || field.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined) return undefined; + const own = field.attr(FIELD_ATTR_MAX_LENGTH); + if (typeof own === "number") return own; + const fallback = enumDefaultsOf(field).maxLength; + if (fallback === undefined) return undefined; + const values = field.attr(FIELD_ATTR_VALUES); + const longest = (Array.isArray(values) ? values : []) + .filter((v): v is string => typeof v === "string") + .reduce((a, v) => (a === undefined || v.length > a.length ? v : a), undefined); + if (longest !== undefined && longest.length > fallback) { + const owner = field.parent; + const label = owner !== undefined && owner.type === TYPE_OBJECT ? `${owner.name}.${field.name}` : field.name; + throw new MetaModelError( + `field.enum "${label}" has the member "${longest}" (${longest.length} characters), longer than ` + + `the project's enums.maxLength ${fallback}. Give the field its own @maxLength of at least ` + + `${longest.length}, raise enums.maxLength, or shorten the member.`, + { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" }, + ); + } + return fallback; +} diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index bc239a88a6..b589da340a 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -151,6 +151,9 @@ export const ERROR_CODES = [ "ERR_BAD_ATTR_FILTER", "ERR_STORAGE_FLATTENED_ARRAY", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE", + // field.enum @maxLength: a member longer than the column, or a length on an int-stored enum. + "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", + "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", "ERR_STORAGE_WITHOUT_OBJECT_REF", // ADR-0013 — a field.object REQUIRES @objectRef (open/untyped JSON uses // the physical @dbColumnType: jsonb escape hatch on field.string instead). diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 0dc844767a..dd4a315d7e 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -379,6 +379,8 @@ export { stripPackage, packageOfResolutionKey, } from "./naming.js"; export type { EntityNameMap, ColumnNamingStrategy, PhysicalNaming, TableNamingRule } from "./naming.js"; +export { resolveEnumMaxLength, enumDefaultsOf, DEFAULT_ENUM_DEFAULTS, ENUMS_KEY_MAX_LENGTH } from "./enum-length.js"; +export type { EnumDefaults } from "./enum-length.js"; // Wire format (ADR-0019 Amendment 2): the `wire` block of .metaobjects/config.json. export { diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index f939431360..ffe7e05e1d 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -25,7 +25,8 @@ import { ParseError } from "../errors.js"; import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; -import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; +import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, + validateEnumMaxLength, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -724,6 +725,9 @@ export class MetaDataLoader { // @valueType (when set) must name a known scalar subtype. errors.push(...validateFieldMap(root)); + // field.enum @maxLength — every member fits; refused with @intValueMap. + errors.push(...validateEnumMaxLength(root)); + // Tenth pass: one-primary multi-source rule — if an object has ≥1 source, // exactly one must carry role "primary" (ERR_SOURCE_NO_PRIMARY / // ERR_SOURCE_MULTIPLE_PRIMARY). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 523da5f18b..de7fa31d70 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -77,6 +77,9 @@ import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, + FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_MAX_LENGTH, + FIELD_ATTR_VALUES, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_ATTR_REQUIRED, @@ -1676,6 +1679,57 @@ export function validateDerivedFieldProvidability(root: MetaData): ParseError[] return errors; } +// --------------------------------------------------------------------------- +// field.enum @maxLength — the column length of a string-stored enum: +// 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the +// longest offender named; +// 2. it is refused beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP): an +// int-stored enum's column is an integer, so a length would change nothing. +// Read RESOLVING (ADR-0039: all three may be inherited through extends), and reported on +// the node that DECLARES one of them, so an enum that only inherits them is not +// reported a second time. Every field.enum in the tree is checked, root-level abstract +// enums included. The project default (enums.maxLength) is not this pass's: the loader +// does not see the project config; resolveEnumMaxLength refuses an overflow of it. +// --------------------------------------------------------------------------- + +export function validateEnumMaxLength(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + const visit = (node: MetaData): void => { + // ADR-0039: own children — every node is visited once, where it is declared. + for (const child of node.ownChildren()) { + if (child.type === TYPE_FIELD && child.subType === FIELD_SUBTYPE_ENUM) checkEnum(child); + if (child.type !== TYPE_FIELD) visit(child); + } + }; + const checkEnum = (field: MetaData): void => { + const declares = [FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP] + .some((a) => field.ownAttr(a) !== undefined); + const maxLength = field.attr(FIELD_ATTR_MAX_LENGTH); + if (!declares || typeof maxLength !== "number") return; + const owner = field.parent; + const label = owner !== undefined && owner.type === TYPE_OBJECT ? `${owner.name}.${field.name}` : field.name; + if (field.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined) { + errors.push(new ParseError( + `field.enum "${label}" sets @maxLength ${maxLength} and @intValueMap; an @intValueMap enum is stored as an integer, so a column length does not apply. Remove @maxLength.`, + { code: "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", source: field.source }, + )); + return; + } + const values = field.attr(FIELD_ATTR_VALUES); + const tooLong = (Array.isArray(values) ? values : []) + .filter((v): v is string => typeof v === "string" && v.length > maxLength) + .sort((a, b) => b.length - a.length); + if (tooLong.length > 0) { + errors.push(new ParseError( + `field.enum "${label}" @maxLength ${maxLength} is shorter than its member "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, + { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", source: field.source }, + )); + } + }; + visit(root); + return errors; +} + // --------------------------------------------------------------------------- // field.object + @storage cross-attribute validation // diff --git a/server/typescript/packages/metadata/src/shared/meta-root.ts b/server/typescript/packages/metadata/src/shared/meta-root.ts index e6665bf159..70333b957c 100644 --- a/server/typescript/packages/metadata/src/shared/meta-root.ts +++ b/server/typescript/packages/metadata/src/shared/meta-root.ts @@ -9,6 +9,7 @@ import type { MetaObject } from "../core/object/meta-object.js"; import type { MetaField } from "../core/field/meta-field.js"; import { DEFAULT_PHYSICAL_NAMING, type PhysicalNaming } from "../naming.js"; import { DEFAULT_WIRE_FORMAT, type WireFormat } from "../wire.js"; +import { DEFAULT_ENUM_DEFAULTS, type EnumDefaults } from "../enum-length.js"; import { PACKAGE_SEPARATOR } from "./structural.js"; import { lookupCanonical } from "../naming-refs.js"; @@ -26,6 +27,12 @@ export class MetaRoot extends MetaData { */ wireFormat: WireFormat = DEFAULT_WIRE_FORMAT; + /** + * The project's enum storage defaults (`enums` in `.metaobjects/config.json`), set by the + * project-aware load beside `physicalNaming` and read through `enumDefaultsOf`. + */ + enumDefaults: EnumDefaults = DEFAULT_ENUM_DEFAULTS; + /** * The project's schema conventions for `meta migrate`: a preset name from * `migrate.conventions` in `.metaobjects/config.json`, or a conventions object the project diff --git a/server/typescript/packages/metadata/test/enum-max-length.test.ts b/server/typescript/packages/metadata/test/enum-max-length.test.ts new file mode 100644 index 0000000000..0145c4dd2e --- /dev/null +++ b/server/typescript/packages/metadata/test/enum-max-length.test.ts @@ -0,0 +1,70 @@ +// A string-stored field.enum's column length: its @maxLength, else the project's +// enums.maxLength (carried on the loaded root, like the naming rules), else none (an +// unbounded text column, as before). Every member must fit the length that applies; the +// loader checks an explicit @maxLength, and the resolver refuses a project default that a +// member overflows, so every consumer that sizes the column refuses the same model. + +import { describe, expect, test } from "bun:test"; +import { + MetaDataLoader, + InMemoryStringSource, + MetaModelError, + resolveEnumMaxLength, + type MetaField, + type MetaObject, + type MetaRoot, +} from "../src/index.js"; + +async function load(statusDecl: Record): Promise { + const doc = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Order", children: [ + { "source.rdb": {} }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", ...statusDecl } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }, + ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toEqual([]); + return root as MetaRoot; +} + +const status = (root: MetaRoot): MetaField => + (root.findObject("Order") as MetaObject).fields().find((f) => f.name === "status")!; + +const VALUES = ["DRAFT", "PUBLISHED", "ARCHIVED"]; + +describe("resolveEnumMaxLength", () => { + test("@maxLength is the column length", async () => { + expect(resolveEnumMaxLength(status(await load({ "@values": VALUES, "@maxLength": 20 })))).toBe(20); + }); + + test("no @maxLength and no project default: none", async () => { + expect(resolveEnumMaxLength(status(await load({ "@values": VALUES })))).toBeUndefined(); + }); + + test("the project default applies when the field declares none", async () => { + const root = await load({ "@values": VALUES }); + root.enumDefaults = { maxLength: 32 }; + expect(resolveEnumMaxLength(status(root))).toBe(32); + }); + + test("@maxLength beats the project default, either way round", async () => { + const root = await load({ "@values": VALUES, "@maxLength": 9 }); + root.enumDefaults = { maxLength: 32 }; + expect(resolveEnumMaxLength(status(root))).toBe(9); + }); + + test("an @intValueMap enum has no length, whatever the default", async () => { + const root = await load({ "@values": VALUES, "@intValueMap": { DRAFT: 0, PUBLISHED: 1, ARCHIVED: 2 } }); + root.enumDefaults = { maxLength: 4 }; + expect(resolveEnumMaxLength(status(root))).toBeUndefined(); + }); + + test("a member longer than the project default is refused, naming the field and the member", async () => { + const root = await load({ "@values": ["DRAFT", "AWAITING_REVIEW"] }); + root.enumDefaults = { maxLength: 9 }; + expect(() => resolveEnumMaxLength(status(root))).toThrow(MetaModelError); + expect(() => resolveEnumMaxLength(status(root))).toThrow(/"Order\.status".*"AWAITING_REVIEW".*enums\.maxLength 9/); + }); +}); diff --git a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts index ec214997b7..57c6c4c6e0 100644 --- a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts @@ -12,7 +12,7 @@ // decimal → @precision, @scale // object → @objectRef // currency → @currency -// enum → @values, @provided, @intValueMap +// enum → @values, @provided, @intValueMap, @maxLength // int/long/double/float/boolean/date/time/timestamp/uuid → none // - the "any attr" wildcard is gone; a misplaced attr is now ERR_UNKNOWN_ATTR. // @@ -104,6 +104,8 @@ const ENUM_CORE_EXTRA: Record = { values: { valueType: "string", required: true }, provided: { valueType: "boolean", required: false }, intValueMap: { valueType: "intMap", required: false }, + // The column length of a string-stored enum (refused beside @intValueMap at load). + maxLength: { valueType: "int", required: false }, }; /** Scoped concern attrs (db / prompt). */ diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 198c005b47..ba1dc951ba 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -61,6 +61,7 @@ import { DOC_ATTR_DESCRIPTION, applyColumnNamingStrategy, physicalNamingOf, resolveTableName, resolveColumnName, resolveFlattenedColumnPrefix, resolveTableSchema, resolveIndexName, + resolveEnumMaxLength, } from "@metaobjectsdev/metadata"; import type { SqlType } from "./sql-type.js"; import type { @@ -1436,7 +1437,14 @@ function subtypeToSqlType(field: MetaData): SqlType { // A string-backed field.enum is a text column with a membership CHECK; an // INT-BACKED one (@intValueMap, design D5) stores the mapped integer instead. // The TS/wire type is the member string either way — only the column differs. - case FIELD_SUBTYPE_ENUM: return isIntBackedEnum(field) ? { kind: "integer", bits: 32 } : { kind: "text" }; + // A string-backed one with a length (its @maxLength, else the project's + // enums.maxLength — core's resolveEnumMaxLength, which refuses a member that does not + // fit) is VARCHAR(n); with none it stays unbounded text. + case FIELD_SUBTYPE_ENUM: { + if (isIntBackedEnum(field)) return { kind: "integer", bits: 32 }; + const length = resolveEnumMaxLength(field); + return length === undefined ? { kind: "text" } : { kind: "text", maxLength: length }; + } default: return { kind: "text" }; // unknown → text fallback } } diff --git a/server/typescript/packages/migrate-ts/test/unit/enum-max-length.test.ts b/server/typescript/packages/migrate-ts/test/unit/enum-max-length.test.ts new file mode 100644 index 0000000000..df14b1c353 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/enum-max-length.test.ts @@ -0,0 +1,59 @@ +/** + * A string-stored field.enum's column is VARCHAR(n) when it has a length (its @maxLength, + * else the project's enums.maxLength, resolveEnumMaxLength), and unbounded text otherwise, + * as before. An @intValueMap enum stays an integer. A member longer than the project + * default refuses the build before any SQL is emitted. + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource, MetaModelError } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { emit } from "../../src/emit/index.js"; +import { diff } from "../../src/diff/index.js"; + +async function schema(enumDecls: Record[], maxLength?: number) { + const doc = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + ...enumDecls.map((d) => ({ "field.enum": d })), + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }, + ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toHaveLength(0); + if (maxLength !== undefined) root.enumDefaults = { maxLength }; + return () => buildExpectedSchema(root); +} + +const column = (s: ReturnType, name: string) => + s.tables.find((t) => t.name === "tickets")!.columns.find((c) => c.name === name)!; + +describe("a string-stored enum's column length", () => { + test("@maxLength → VARCHAR(n) in the CREATE TABLE", async () => { + const s = (await schema([{ name: "status", "@values": ["OPEN", "CLOSED"], "@maxLength": 16 }]))(); + expect(column(s, "status").sqlType).toEqual({ kind: "text", maxLength: 16 }); + const { changes } = await diff(s, { tables: [], views: [] } as never, { dialect: "postgres" }); + expect(emit(changes, { dialect: "postgres" }).up).toContain('"status" VARCHAR(16)'); + }); + + test("the project default sizes an enum with no @maxLength", async () => { + const s = (await schema([{ name: "status", "@values": ["OPEN", "CLOSED"] }], 32))(); + expect(column(s, "status").sqlType).toEqual({ kind: "text", maxLength: 32 }); + }); + + test("no length anywhere → unbounded text, as before", async () => { + const s = (await schema([{ name: "status", "@values": ["OPEN", "CLOSED"] }]))(); + expect(column(s, "status").sqlType).toEqual({ kind: "text" }); + }); + + test("an @intValueMap enum stays an integer under a project default", async () => { + const s = (await schema([{ name: "rank", "@values": ["A", "B"], "@intValueMap": { A: 1, B: 2 } }], 32))(); + expect(column(s, "rank").sqlType).toEqual({ kind: "integer", bits: 32 }); + }); + + test("a member longer than the project default refuses the build", async () => { + const build = await schema([{ name: "status", "@values": ["OPEN", "IN_PROGRESS"] }], 10); + expect(build).toThrow(MetaModelError); + expect(build).toThrow(/IN_PROGRESS/); + }); +}); diff --git a/server/typescript/packages/sdk/src/collection.ts b/server/typescript/packages/sdk/src/collection.ts index 50d118374a..4fad56b18f 100644 --- a/server/typescript/packages/sdk/src/collection.ts +++ b/server/typescript/packages/sdk/src/collection.ts @@ -22,8 +22,10 @@ import { type PhysicalNaming, type WireFormat, DEFAULT_WIRE_FORMAT, + type EnumDefaults, + DEFAULT_ENUM_DEFAULTS, } from "@metaobjectsdev/metadata"; -import { CONFIG_FILE, loadConfig, physicalNamingFromConfig, wireFormatFromConfig, type Config } from "./config.js"; +import { CONFIG_FILE, enumDefaultsFromConfig, loadConfig, physicalNamingFromConfig, wireFormatFromConfig, type Config } from "./config.js"; import { discoverCollectionRoot, exists, isDir } from "./discovery.js"; import { compileScope, matchesScope, type Scope } from "./scope.js"; import { DEFAULT_METADATA_DIR, DEFAULT_METAOBJECTS_DIR, isMetadataFile } from "./metadata-files.js"; @@ -85,6 +87,8 @@ export interface Collection { readonly physicalNaming: PhysicalNaming; /** The `wire` block of the project config (ADR-0019 Amendment 2), default when absent. */ readonly wireFormat: WireFormat; + /** The `enums` block of the project config (string-stored enum defaults), none when absent. */ + readonly enumDefaults: EnumDefaults; /** `migrate.conventions` of the project config — a schema-conventions preset name — when set. */ readonly schemaConventions: string | undefined; /** FR-023 — the `FileSource` id each file loads under, for the dependency @@ -274,6 +278,7 @@ export async function resolveCollection( let libraries: readonly string[] = []; let physicalNaming: PhysicalNaming = DEFAULT_PHYSICAL_NAMING; let wireFormat: WireFormat = DEFAULT_WIRE_FORMAT; + let enumDefaults: EnumDefaults = DEFAULT_ENUM_DEFAULTS; let schemaConventions: string | undefined; if (hasConfig) { @@ -291,6 +296,7 @@ export async function resolveCollection( libraries = cfg.libraries; physicalNaming = physicalNamingFromConfig(cfg); wireFormat = wireFormatFromConfig(cfg); + enumDefaults = enumDefaultsFromConfig(cfg); schemaConventions = cfg.migrate?.conventions; // An unknown token is a hard config error naming the valid ones, while // `librarySources` keeps skipping one silently for a programmatic caller. The two @@ -406,6 +412,7 @@ export async function resolveCollection( libraries, physicalNaming, wireFormat, + enumDefaults, schemaConventions, fileIds: new Map(dependencies.map((d) => [d.artifactPath, d.sourceId])), importedPackages: [...importedPackages].sort(), diff --git a/server/typescript/packages/sdk/src/config.ts b/server/typescript/packages/sdk/src/config.ts index 9d921302f7..fb67f5e028 100644 --- a/server/typescript/packages/sdk/src/config.ts +++ b/server/typescript/packages/sdk/src/config.ts @@ -8,6 +8,8 @@ import { DEFAULT_PHYSICAL_NAMING, TABLE_NAMING_RULES, DEFAULT_WIRE_FORMAT, + DEFAULT_ENUM_DEFAULTS, + type EnumDefaults, WIRE_DECIMALS, WIRE_NULL_MEMBERS, WIRE_KEY_DECIMALS, @@ -233,6 +235,17 @@ export const ConfigSchema = z.object({ : iss.code === "invalid_type" ? `"wire" must be an object` : undefined, }) .optional(), + /** + * How a string-stored `field.enum` is stored. `maxLength` is the column length (VARCHAR(n)) + * of an enum that declares no `@maxLength` of its own; every member must fit. Absent means + * no default: such an enum is an unbounded text column, as before. An `@intValueMap` enum is + * an integer column and takes no length. Read by every port's config reader. + */ + enums: z + .strictObject({ + maxLength: z.number().int().positive().optional(), + }) + .optional(), /** * C#-scoped settings. `outDir` is where `dotnet meta gen` writes and a bare `dotnet meta * verify` diffs, relative to the directory holding `.metaobjects/`; `namespace` is the C# @@ -255,6 +268,11 @@ export function physicalNamingFromConfig(cfg: Pick): PhysicalN }; } +/** The enum storage defaults a config declares (`enums`); none when absent. */ +export function enumDefaultsFromConfig(cfg: Pick): EnumDefaults { + return cfg.enums?.maxLength === undefined ? DEFAULT_ENUM_DEFAULTS : { maxLength: cfg.enums.maxLength }; +} + /** The wire format a config declares, each absent key at its default (ADR-0019 Amendment 2). */ export function wireFormatFromConfig(cfg: Pick): WireFormat { return { diff --git a/server/typescript/packages/sdk/src/index.ts b/server/typescript/packages/sdk/src/index.ts index 6a8373cd30..fdd0ea82cd 100644 --- a/server/typescript/packages/sdk/src/index.ts +++ b/server/typescript/packages/sdk/src/index.ts @@ -16,7 +16,7 @@ // shows `resolveCollection`, the documented single authority for locating a project. // Config -export { ConfigSchema, DEFAULT_CONFIG, loadConfig, setConfigWarningSink, splitUnknownTopLevelKeys, CONFIG_TOP_LEVEL_KEYS, saveConfig, AllowTokenEnum, physicalNamingFromConfig, wireFormatFromConfig } from "./config.js"; +export { ConfigSchema, DEFAULT_CONFIG, loadConfig, setConfigWarningSink, splitUnknownTopLevelKeys, CONFIG_TOP_LEVEL_KEYS, saveConfig, AllowTokenEnum, physicalNamingFromConfig, wireFormatFromConfig, enumDefaultsFromConfig } from "./config.js"; export type { Config } from "./config.js"; // Metadata dependencies (FR-023) — the `dependencies` config key's schema, diff --git a/server/typescript/packages/sdk/src/memory.ts b/server/typescript/packages/sdk/src/memory.ts index d7332d650a..793cd945f7 100644 --- a/server/typescript/packages/sdk/src/memory.ts +++ b/server/typescript/packages/sdk/src/memory.ts @@ -15,6 +15,7 @@ import { type MetaRoot, type PhysicalNaming, type WireFormat, + type EnumDefaults, } from "@metaobjectsdev/metadata"; import { FileSource } from "@metaobjectsdev/metadata/core"; // FR-043 — a node-only subpath (it reaches the filesystem), which is why it is imported @@ -114,6 +115,8 @@ export interface LoadMemoryOptions { physicalNaming?: PhysicalNaming; /** The project wire format; defaults to the collection's (`resolveCollection(...).wireFormat`) when `files` is not passed. */ wireFormat?: WireFormat; + /** The project's enum storage defaults; defaults to the collection's (`resolveCollection(...).enumDefaults`) when `files` is not passed. */ + enumDefaults?: EnumDefaults; /** * The schema conventions `meta migrate` names database-only objects with, set on the loaded * root: a preset name, or a conventions object the project supplies. Defaults to the @@ -175,7 +178,7 @@ export async function loadMemory( repoRoot: string, options?: LoadMemoryOptions, ): Promise { - const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, schemaConventions } = + const { result, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, schemaConventions } = await loadCollectionRaw(repoRoot, options, options?.strict === true); if (result.errors.length > 0) { @@ -196,6 +199,7 @@ export async function loadMemory( if (physicalNaming !== undefined) result.root.physicalNaming = physicalNaming; if (wireFormat !== undefined) result.root.wireFormat = wireFormat; + if (enumDefaults !== undefined) result.root.enumDefaults = enumDefaults; if (schemaConventions !== undefined) result.root.schemaConventions = schemaConventions; return result.root; } @@ -271,6 +275,7 @@ async function loadCollectionRaw( libraries: readonly string[] | undefined; physicalNaming: PhysicalNaming | undefined; wireFormat: WireFormat | undefined; + enumDefaults: EnumDefaults | undefined; schemaConventions: unknown; }> { const extra = options?.providers ?? []; @@ -300,6 +305,7 @@ async function loadCollectionRaw( let libraries: readonly string[] | undefined = options?.libraries; let physicalNaming: PhysicalNaming | undefined = options?.physicalNaming; let wireFormat: WireFormat | undefined = options?.wireFormat; + let enumDefaults: EnumDefaults | undefined = options?.enumDefaults; let schemaConventions: unknown = options?.schemaConventions; if (options?.files !== undefined) { paths = [...options.files]; @@ -321,6 +327,7 @@ async function loadCollectionRaw( libraries ??= collection.libraries; physicalNaming ??= collection.physicalNaming; wireFormat ??= collection.wireFormat; + enumDefaults ??= collection.enumDefaults; schemaConventions ??= collection.schemaConventions; } @@ -347,7 +354,7 @@ async function loadCollectionRaw( return id === undefined ? new FileSource(p) : new FileSource(p, { id }); }), ]); - return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, schemaConventions }; + return { result, registry, importedPackages, importedNodes, libraries, physicalNaming, wireFormat, enumDefaults, schemaConventions }; } /** Every source file that contributed to a node, across the envelope variants that diff --git a/server/typescript/packages/sdk/test/enum-length-conformance.test.ts b/server/typescript/packages/sdk/test/enum-length-conformance.test.ts new file mode 100644 index 0000000000..0e4886a713 --- /dev/null +++ b/server/typescript/packages/sdk/test/enum-length-conformance.test.ts @@ -0,0 +1,81 @@ +// The cross-port enum-length corpus, run through TypeScript's own config reader and +// resolver: the `enums` block parses with the schema `.metaobjects/config.json` is read with, +// the loaded root carries it, and every enum's column length resolves through +// resolveEnumMaxLength, the function `meta migrate` and the generated bindings call. + +import { describe, expect, test } from "bun:test"; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { FileSource } from "@metaobjectsdev/metadata/core"; +import { MetaDataLoader, MetaModelError, isMetaRoot, resolveEnumMaxLength, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; +import { ConfigSchema, enumDefaultsFromConfig } from "../src/config.js"; +import { loadMemory } from "../src/memory.js"; + +const CORPUS = resolve(import.meta.dir, "../../../../../fixtures/enum-length-conformance"); + +interface Case { name: string; enums: unknown; lengths: Record } +interface Overflow { name: string; enums: unknown; field: string; member: string } +const corpus = JSON.parse(readFileSync(join(CORPUS, "cases.json"), "utf8")) as { + cases: Case[]; + overflow: Overflow[]; + invalid: { name: string; enums: unknown }[]; +}; + +const configFor = (enums: unknown): Record => + enums === null ? { schema_version: 1 } : { schema_version: 1, enums }; + +async function loadCorpusModel(enums: unknown): Promise { + const result = await new MetaDataLoader().load([new FileSource(join(CORPUS, "meta.enums.json"))]); + expect(result.errors).toEqual([]); + if (!isMetaRoot(result.root)) throw new Error("not a root"); + result.root.enumDefaults = enumDefaultsFromConfig(ConfigSchema.parse(configFor(enums))); + return result.root; +} + +const ticketField = (root: MetaRoot, name: string) => + (root.findObject("Ticket") as MetaObject).fields().find((f) => f.name === name)!; + +describe("enum-length conformance", () => { + for (const c of corpus.cases) { + test(`${c.name}: every enum's column length`, async () => { + const root = await loadCorpusModel(c.enums); + const actual: Record = {}; + for (const name of Object.keys(c.lengths)) actual[name] = resolveEnumMaxLength(ticketField(root, name)) ?? null; + expect(actual).toEqual(c.lengths); + }); + } + + for (const o of corpus.overflow) { + test(`${o.name}: refused, naming the member`, async () => { + const root = await loadCorpusModel(o.enums); + let caught: unknown; + try { resolveEnumMaxLength(ticketField(root, o.field)); } catch (e) { caught = e; } + expect(caught).toBeInstanceOf(MetaModelError); + expect((caught as MetaModelError).code).toBe("ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH"); + expect((caught as Error).message).toContain(o.member); + }); + } + + for (const c of corpus.invalid) { + test(`${c.name}: the config is refused when read`, () => { + expect(ConfigSchema.safeParse(configFor(c.enums)).success).toBe(false); + }); + } + + test("the project-aware load sets the root from .metaobjects/config.json", async () => { + const withDefault = corpus.cases.find((c) => c.enums !== null && Object.keys(c.enums as object).length > 0)!; + const dir = mkdtempSync(join(tmpdir(), "mo-enums-")); + try { + mkdirSync(join(dir, ".metaobjects")); + mkdirSync(join(dir, "metaobjects")); + writeFileSync(join(dir, ".metaobjects", "config.json"), JSON.stringify(configFor(withDefault.enums))); + copyFileSync(join(CORPUS, "meta.enums.json"), join(dir, "metaobjects", "meta.enums.json")); + const root = await loadMemory(dir); + expect(root.enumDefaults).toEqual(withDefault.enums as object); + expect(resolveEnumMaxLength(ticketField(root, "status")) ?? null).toBe(withDefault.lengths.status ?? null); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/site-reference/providers.html b/site-reference/providers.html index 28f353c71a..7ff136f6e7 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -57,7 +57,7 @@

metaobjects-core-types

  • field.base: @default, @mutability, @required, @unique
  • field.currency: @currency
  • field.decimal: @precision, @scale
  • -
  • field.enum: @intValueMap, @provided, @values
  • +
  • field.enum: @intValueMap, @maxLength, @provided, @values
  • field.inet: @lenient
  • field.map: @objectRef, @valueType
  • field.object: @objectRef
  • diff --git a/site-reference/types/field.html b/site-reference/types/field.html index 6b7639c945..40045743ef 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -1114,6 +1114,15 @@

    field.enum

    + + + + + + + + + diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index b054bda765..847f0ea66e 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -151,6 +151,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, + { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } ] }, From 686c2bb9dc217c6fe3af647169b26beee24c1cfe Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 08:07:42 -0500 Subject: [PATCH 017/267] fix(enums): review fixes for the enum column length - C# `dotnet meta gen` and `verify --codegen` report a project-default overflow by name (MetaModelException joins the caught set) instead of crashing with a stack trace. - An array enum has no length in every port's core resolver (a text[] column whose elements carry none), so Drizzle no longer emits varchar(n)[] and an array enum's members are never checked against the default; pinned in the shared corpus. - TS `meta verify` refuses an overflow by name on its migrate.scope paths too (the scope check and the replay-snapshot scoping), not as an uncaught rejection. - Every config reader accepts a whole number however JSON spells it (32, 32.0, 1e2); pinned in the shared corpus. - Java reports every offending enum, not only the first; a new two-error conformance fixture pins it in every port. - An enum's @maxLength is not an input rule: the TS UI descriptor and the Python model no longer emit maxLength / max_length for it. - Patch-release compatibility: C# ErrorCode members are appended, never inserted (so no existing value shifts); ResolvedMetadata.Enums is an init property, not a positional parameter; the TS Collection's enumDefaults is optional. - docs: a duplicated sentence in field-types.md, fixture counts. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- docs/CONFORMANCE.md | 8 +-- docs/features/field-types.md | 2 +- examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 25 ++++++++ .../input/meta.enums.json | 18 ++++++ fixtures/enum-length-conformance/README.md | 4 +- fixtures/enum-length-conformance/cases.json | 18 ++++-- .../enum-length-conformance/meta.enums.json | 1 + .../EnumLengthCliTests.cs | 60 +++++++++++++++++++ .../csharp/MetaObjects.Codegen/CodegenCli.cs | 2 +- .../MetaObjects.Codegen/CodegenDrift.cs | 2 +- .../MetaObjects/Config/MetadataLocation.cs | 14 +++-- .../MetaObjects/Config/NeutralConfig.cs | 7 ++- server/csharp/MetaObjects/Errors.cs | 11 ++-- server/csharp/MetaObjects/Meta/EnumLength.cs | 5 +- .../com/metaobjects/database/EnumLength.java | 2 + .../metaobjects/loader/ValidationPhase.java | 17 +++--- .../codegen/generators/entity_model.py | 4 +- .../src/metaobjects/config/neutral_config.py | 4 ++ server/python/src/metaobjects/enum_length.py | 3 + .../codegen/test_enum_max_length_model.py | 31 ++++++++++ .../packages/cli/src/commands/verify.ts | 50 ++++++++++------ .../cli/src/lib/collection-load-options.ts | 3 +- .../cli/test/verify-schema-refusals.test.ts | 7 +++ .../packages/codegen-ts/src/column-mapper.ts | 5 +- .../src/templates/entity-ui-descriptor.ts | 6 +- .../test/drizzle-enum-max-length.test.ts | 8 +++ .../test/enum-max-length-ui.test.ts | 26 ++++++++ .../packages/metadata/src/enum-length.ts | 5 +- .../typescript/packages/sdk/src/collection.ts | 5 +- 31 files changed, 297 insertions(+), 60 deletions(-) create mode 100644 fixtures/conformance/error-enum-value-exceeds-max-length-every-field/expected-errors.json create mode 100644 fixtures/conformance/error-enum-value-exceeds-max-length-every-field/input/meta.enums.json create mode 100644 server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs create mode 100644 server/python/tests/codegen/test_enum_max_length_model.py create mode 100644 server/typescript/packages/codegen-ts/test/enum-max-length-ui.test.ts diff --git a/AGENTS.md b/AGENTS.md index 3a796bed17..61c13e1f1e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (426 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (427 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index ae9200511d..956ec04adb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 426 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 427 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -58,7 +58,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 26 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`) | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | -| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 3 cases + 1 overflow + 5 refusals | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | ✓ | +| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | ✓ | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (FR-044 — reporting vocabulary: what is lowered, what stays inert) | 1 model pair (`reporting/with` vs `reporting/without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | @@ -286,7 +286,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (426) +### `fixtures/conformance/` — metamodel loader + canonical serializer (427) | Fixture prefix | Feature doc | |---|---| @@ -612,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 426 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 427 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/field-types.md b/docs/features/field-types.md index ad81748789..030eb300f4 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -206,7 +206,7 @@ when the column is sized, both as `ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH`, with the int-backed enum's column is an integer. An array of enums stays a `text[]` column. Kotlin's Exposed binding keeps its 64-character width when the enum has no length. -**Int-backed storage:** `@intValueMap` switches the DB column from string to integer while**Int-backed storage:** `@intValueMap` switches the DB column from string to integer while +**Int-backed storage:** `@intValueMap` switches the DB column from string to integer while preserving the string wire format and generated enum type. Keys must match `@values` exactly; values must be unique integers. Display labels and native Postgres `ENUM` types remain deferred (see [enum-datatype-design.md](../superpowers/specs/2026-05-23-enum-datatype-design.md)). diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index eafa11982f..d2c7c68c66 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 426, + "fixtures": 427, "corpora": 36, "baseTypes": 17 }, diff --git a/fixtures/conformance/error-enum-value-exceeds-max-length-every-field/expected-errors.json b/fixtures/conformance/error-enum-value-exceeds-max-length-every-field/expected-errors.json new file mode 100644 index 0000000000..166e3a509e --- /dev/null +++ b/fixtures/conformance/error-enum-value-exceeds-max-length-every-field/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + }, + { + "code": "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-value-exceeds-max-length-every-field/input/meta.enums.json b/fixtures/conformance/error-enum-value-exceeds-max-length-every-field/input/meta.enums.json new file mode 100644 index 0000000000..6069a85876 --- /dev/null +++ b/fixtures/conformance/error-enum-value-exceeds-max-length-every-field/input/meta.enums.json @@ -0,0 +1,18 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Order", + "children": [ + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["DRAFT", "AWAITING_REVIEW"], "@maxLength": 9 } }, + { "field.enum": { "name": "channel", "@values": ["EMAIL", "TELEPHONE"], "@maxLength": 5 } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/enum-length-conformance/README.md b/fixtures/enum-length-conformance/README.md index a381562a1e..da80e553ed 100644 --- a/fixtures/enum-length-conformance/README.md +++ b/fixtures/enum-length-conformance/README.md @@ -10,7 +10,9 @@ the column refuses the same model. [`cases.json`](./cases.json) holds the `enums` blocks every port must accept, with the length each enum in [`meta.enums.json`](./meta.enums.json) resolves to under them, the overflow every -port must refuse, and the blocks every port must refuse when it reads the file. Each port runs +port must refuse, and the blocks every port must refuse when it reads the file. A whole +number is accepted however JSON spells it (`32`, `32.0`, `1e2`), because a JSON reader that +parses numbers as doubles cannot tell those apart. Each port runs it through its own config reader and core resolver: | Port | Test | diff --git a/fixtures/enum-length-conformance/cases.json b/fixtures/enum-length-conformance/cases.json index 4167935f62..203a457ce4 100644 --- a/fixtures/enum-length-conformance/cases.json +++ b/fixtures/enum-length-conformance/cases.json @@ -1,20 +1,30 @@ { - "_comment": "The column length of a string-stored field.enum, per port. Each case is the `enums` block of a project's .metaobjects/config.json (null: no block). Each port reads it with its own config reader, puts it on the loaded meta.enums.json root, and resolves every Ticket enum's length through its core resolver (resolveEnumMaxLength and its per-port equivalents). null in `lengths` means no length: an unbounded text column. `overflow` cases must be refused when the named field's length is resolved, with ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH. Each `invalid` block must be refused when the config is read.", + "_comment": "The column length of a string-stored field.enum, per port. Each case is the `enums` block of a project's .metaobjects/config.json (null: no block). Each port reads it with its own config reader, puts it on the loaded meta.enums.json root, and resolves every Ticket enum's length through its core resolver (resolveEnumMaxLength and its per-port equivalents). null in `lengths` means no length: an unbounded text column, or for an array enum a text[] column, whose elements carry no length (so an array enum's members are never checked against the default). `overflow` cases must be refused when the named field's length is resolved, with ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH. Each `invalid` block must be refused when the config is read.", "cases": [ { "name": "no enums block: only an explicit @maxLength sizes a column", "enums": null, - "lengths": { "status": null, "channel": 20, "priority": 8, "rank": null } + "lengths": { "status": null, "channel": 20, "priority": 8, "rank": null, "tags": null } }, { "name": "an empty block is the same as none", "enums": {}, - "lengths": { "status": null, "channel": 20, "priority": 8, "rank": null } + "lengths": { "status": null, "channel": 20, "priority": 8, "rank": null, "tags": null } }, { "name": "the project default sizes every enum without its own @maxLength", "enums": { "maxLength": 32 }, - "lengths": { "status": 32, "channel": 20, "priority": 8, "rank": null } + "lengths": { "status": 32, "channel": 20, "priority": 8, "rank": null, "tags": null } + }, + { + "name": "an integer written with a decimal point is that integer", + "enums": { "maxLength": 32.0 }, + "lengths": { "status": 32, "channel": 20, "priority": 8, "rank": null, "tags": null } + }, + { + "name": "an integer written with an exponent is that integer", + "enums": { "maxLength": 1e2 }, + "lengths": { "status": 100, "channel": 20, "priority": 8, "rank": null, "tags": null } } ], "overflow": [ diff --git a/fixtures/enum-length-conformance/meta.enums.json b/fixtures/enum-length-conformance/meta.enums.json index 717d319ab9..6df2d37984 100644 --- a/fixtures/enum-length-conformance/meta.enums.json +++ b/fixtures/enum-length-conformance/meta.enums.json @@ -20,6 +20,7 @@ { "field.enum": { "name": "channel", "@values": ["EMAIL", "PHONE"], "@maxLength": 20 } }, { "field.enum": { "name": "priority", "extends": "acme::enums::Priority" } }, { "field.enum": { "name": "rank", "@values": ["A", "B"], "@intValueMap": { "A": 1, "B": 2 } } }, + { "field.enum": { "name": "tags", "isArray": true, "@values": ["URGENT", "FOLLOW_UP_NEEDED"] } }, { "identity.primary": { "name": "pk", "@fields": "id" } } ] } diff --git a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs new file mode 100644 index 0000000000..0c51bf6f7f --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs @@ -0,0 +1,60 @@ +// A member longer than the project's enums.maxLength is a metadata/config defect: `dotnet meta +// gen` and `verify --codegen` report it by name and fail, the way TypeScript's `meta gen` does, +// never as an unhandled exception and a stack trace. +using MetaObjects.Codegen.Generators; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +[Collection("Console")] +public sealed class EnumLengthCliTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-enum-cli-" + Guid.NewGuid().ToString("N")); + private string Meta => Path.Combine(_root, "metaobjects"); + private string Out => Path.Combine(_root, "gen"); + + public EnumLengthCliTests() + { + Directory.CreateDirectory(Meta); + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + File.WriteAllText(Path.Combine(_root, ".metaobjects", "config.json"), """{ "schema_version": 1, "enums": { "maxLength": 4 } }"""); + File.WriteAllText(Path.Combine(Meta, "meta.acme.json"), """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["OPEN", "CLOSED"] } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """); + } + + public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } + + private (int Code, string Text) Run(params string[] args) + { + var (prevOut, prevErr) = (Console.Out, Console.Error); + var (o, e) = (new StringWriter(), new StringWriter()); + Console.SetOut(o); + Console.SetError(e); + try { return (CodegenCli.Run(args, [new DbContextGenerator()]), o + "\n" + e); } + finally { Console.SetOut(prevOut); Console.SetError(prevErr); } + } + + [Fact] + public void Gen_reports_the_member_by_name_and_fails() + { + var (code, text) = Run("gen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + Assert.NotEqual(0, code); + Assert.Contains("field.enum \"Ticket.status\" has the member \"CLOSED\"", text); + } + + [Fact] + public void Verify_codegen_reports_the_member_by_name_and_fails() + { + var (code, text) = Run("verify", "--codegen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + Assert.NotEqual(0, code); + Assert.Contains("field.enum \"Ticket.status\" has the member \"CLOSED\"", text); + } +} diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 89a3b9b1de..6261dd983c 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -269,7 +269,7 @@ public static GenOutcome RunGen( // A bad template ref / wrong --template-root surfaces as a clean error, not a stack trace. return new GenOutcome([$"{RenderFailedPrefix}{ex.Message}"], null); } - catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or MetaModelException) { // An output-pattern error or a duplicate output-path collision surfaces lazily // during the walk — a clean error, not a stack trace. diff --git a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs index 29711710e4..98b698ab07 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs @@ -98,7 +98,7 @@ public static Result Compute(GenConfig config, MetaRoot root, IReadOnlyList temps[roots.FindIndex(r => r.Committed == Path.GetFullPath(realRootFor(g)))]); } - catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or MetaModelException) { return new Result { Clean = false, Error = $"verify --codegen: {ex.Message}" }; } diff --git a/server/csharp/MetaObjects/Config/MetadataLocation.cs b/server/csharp/MetaObjects/Config/MetadataLocation.cs index 1455553ed0..727b53ae14 100644 --- a/server/csharp/MetaObjects/Config/MetadataLocation.cs +++ b/server/csharp/MetaObjects/Config/MetadataLocation.cs @@ -42,9 +42,13 @@ namespace MetaObjects.Config; /// public sealed record ResolvedMetadata( string Directory, IReadOnlyList? Files, IReadOnlyList Libraries, PhysicalNaming Naming, - WireFormat? Wire = null, string? OutDir = null, ImportScope? Imports = null, string? Namespace = null, - EnumDefaults? Enums = null) + WireFormat? Wire = null, string? OutDir = null, ImportScope? Imports = null, string? Namespace = null) { + /// The project's enum storage defaults (enums in config.json), set on the loaded + /// root by . An init property, not a positional parameter, so the record's + /// constructor and Deconstruct keep the signatures they had. + public EnumDefaults? Enums { get; init; } + /// Load this metadata, with the project's libraries, and set the loaded /// root's from (ADR-0058) and its /// from . @@ -119,7 +123,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) // No config found means no project to read a lock from: nothing is imported. var explicitImports = explicitCfg is null ? ImportScope.None : ImportScope.Resolve(explicitCfg.ConfigDir, explicitCfg); return new ResolvedMetadata( - metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace, explicitCfg?.Enums); + metadataDir, null, explicitLibs, explicitNaming, explicitCfg?.Wire, explicitCfg?.OutDir, explicitImports, explicitCfg?.Namespace) { Enums = explicitCfg?.Enums }; } var cfg = NeutralConfig.Read(cwd); @@ -134,7 +138,7 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) // No declared sources: resolve the DEFAULT directory through the same ladder // the shared conformance corpus gates (ERR_COLLECTION_NOT_FOUND when absent). var defaultFiles = SourceResolver.ResolveCollection(cwd); - return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, cfg?.Enums); + return new ResolvedMetadata(Path.Combine(cwd, NeutralConfig.DefaultMetadataDir), defaultFiles, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace) { Enums = cfg?.Enums }; } if (specs.Count > 1) @@ -164,6 +168,6 @@ public static ResolvedMetadata Resolve(string? metadataDir, string cwd) "\"sources\" at the file's containing directory."); } - return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace, cfg?.Enums); + return new ResolvedMetadata(resolved, files, libraries, naming, wire, cfg?.OutDir, imports, cfg?.Namespace) { Enums = cfg?.Enums }; } } diff --git a/server/csharp/MetaObjects/Config/NeutralConfig.cs b/server/csharp/MetaObjects/Config/NeutralConfig.cs index 6eee87a039..bddf9fc7b4 100644 --- a/server/csharp/MetaObjects/Config/NeutralConfig.cs +++ b/server/csharp/MetaObjects/Config/NeutralConfig.cs @@ -353,11 +353,14 @@ private static EnumDefaults ReadEnums(JsonElement root, string path) switch (p.Name) { case "maxLength": - if (p.Value.ValueKind != JsonValueKind.Number || !p.Value.TryGetInt64(out var n) || n <= 0) + // A whole number however JSON spells it (32, 32.0, 1e2): a reader that parses + // numbers as doubles (TypeScript's) cannot tell those apart. + if (p.Value.ValueKind != JsonValueKind.Number || !p.Value.TryGetDouble(out var d) + || d <= 0 || d != Math.Floor(d) || d > long.MaxValue) throw new MetaModelException( $"{path}: \"enums.maxLength\" must be a positive integer", ErrorCode.ERR_BAD_ATTR_VALUE); - maxLength = n; + maxLength = (long)d; break; default: throw new MetaModelException( diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index f11fa6ab62..55eaf0c7a0 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -140,10 +140,6 @@ public enum ErrorCode // physical @dbColumnType: jsonb escape hatch on field.string). ERR_OBJECT_FIELD_WITHOUT_OBJECT_REF, ERR_STORAGE_FLATTENED_ARRAY, - // @flattenedColumnPrefix on a field.object whose @storage is not "flattened" (absent is jsonb). - ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, - ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, - ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, ERR_INVALID_TEMPLATE, ERR_SOURCE_NO_PRIMARY, ERR_SOURCE_MULTIPLE_PRIMARY, @@ -307,6 +303,13 @@ public enum ErrorCode // default @normalize: strip; rename a member or set collapse / none. ERR_ENUM_NORMALIZE_COLLISION, ERR_UNKNOWN, + // Appended, never inserted: a member's integer value is its position, so adding one + // mid-enum would renumber every member after it in a patch release. + // @flattenedColumnPrefix on a field.object whose @storage is not "flattened" (absent is jsonb). + ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, + // field.enum @maxLength: a member longer than the column, or a length on an int-stored enum. + ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, + ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, } /// diff --git a/server/csharp/MetaObjects/Meta/EnumLength.cs b/server/csharp/MetaObjects/Meta/EnumLength.cs index eeaa7dfe45..9990ff980c 100644 --- a/server/csharp/MetaObjects/Meta/EnumLength.cs +++ b/server/csharp/MetaObjects/Meta/EnumLength.cs @@ -24,7 +24,8 @@ public static class EnumLength /// /// The column length of , a string-stored field.enum: its /// @maxLength (ADR-0039 — resolving), else the project default, else null. Null for an - /// @intValueMap enum, whose column is an integer, and for any other field. + /// @intValueMap enum, whose column is an integer, for an array enum (a text[] column whose + /// elements carry no length), and for any other field. /// The loader refuses an @maxLength a member does not fit; it does not see the /// project config, so a member longer than the project DEFAULT is refused here /// (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), by every consumer that sizes the column. @@ -32,6 +33,8 @@ public static class EnumLength public static long? ResolveMaxLength(MetaField field) { if (field.SubType != FIELD_SUBTYPE_ENUM || field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null) return null; + // An array enum is a text[] column, whose elements carry no length. + if (field.ResolvedIsArray()) return null; if (field.MaxLength is { } own) return own; if (EnumDefaults.Of(field).MaxLength is not { } fallback) return null; var longest = (field.EffectiveEnumValues ?? []) diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java index 195b6290cd..8867237376 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java @@ -32,6 +32,8 @@ private EnumLength() {} */ public static Long resolveMaxLength(MetaField field) { if (!(field instanceof EnumField) || field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null; + // An array enum is a text[] column, whose elements carry no length. + if (field.isArrayType()) return null; if (field.hasMetaAttr(EnumField.ATTR_MAX_LENGTH)) { Object own = field.getMetaAttr(EnumField.ATTR_MAX_LENGTH).getValue(); if (own instanceof Number n) return n.longValue(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 7d2f88af61..abccf9fa71 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -262,7 +262,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { // FR-024 B6 — derived-field providability (entity origin fields need a read source). pass(collected, () -> validateDerivedFieldProvidability(root)); pass(collected, () -> validateObjectFieldStorage(root)); - pass(collected, () -> validateEnumMaxLength(root)); + validateEnumMaxLength(root, collected); pass(collected, () -> validateFieldMap(root)); pass(collected, () -> validateIdentityFieldsAndGeneration(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). @@ -2380,16 +2380,17 @@ private static List junctionReferenceFkFields(MetaObject junction) { // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. // ========================================================================= - static void validateEnumMaxLength(MetaRoot root) { - walkEnumMaxLength(root); - } - - private static void walkEnumMaxLength(MetaData node) { + /** Every offending enum is reported, as the other ports do, not only the first. */ + static void validateEnumMaxLength(MetaData node, List out) { for (MetaData child : node.getChildren(MetaData.class, false)) { if (child instanceof EnumField) { - validateEnumMaxLengthNode((EnumField) child); + try { + validateEnumMaxLengthNode((EnumField) child); + } catch (MetaDataException e) { + out.add(e); + } } else if (!(child instanceof com.metaobjects.field.MetaField)) { - walkEnumMaxLength(child); + validateEnumMaxLength(child, out); } } } diff --git a/server/python/src/metaobjects/codegen/generators/entity_model.py b/server/python/src/metaobjects/codegen/generators/entity_model.py index e695ff2e28..6bea3aaa9f 100644 --- a/server/python/src/metaobjects/codegen/generators/entity_model.py +++ b/server/python/src/metaobjects/codegen/generators/entity_model.py @@ -160,7 +160,9 @@ def _validator_constraints(field: MetaField, *, wire: bool) -> dict[str, object] min_len = _first_attr(field, vc.VALIDATOR_SUBTYPE_LENGTH, vc.VALIDATOR_ATTR_MIN) max_len = _first_attr(field, vc.VALIDATOR_SUBTYPE_LENGTH, vc.VALIDATOR_ATTR_MAX) field_max = field.attrs().get(fc.FIELD_ATTR_MAX_LENGTH) - if _is_int(field_max): + # On a field.enum @maxLength is the column length, not an input rule: the Literal of its + # members is the rule, and every member fits. + if _is_int(field_max) and field.sub_type != fc.FIELD_SUBTYPE_ENUM: # FR-036 A3 — strictest-wins: when BOTH a validator.length @max and a field # @maxLength cap a string, the smaller bound governs (never the field attr # unconditionally, which could loosen a tighter validator). diff --git a/server/python/src/metaobjects/config/neutral_config.py b/server/python/src/metaobjects/config/neutral_config.py index 9f53a3f49e..320e36bc18 100644 --- a/server/python/src/metaobjects/config/neutral_config.py +++ b/server/python/src/metaobjects/config/neutral_config.py @@ -336,6 +336,10 @@ def _read_enums(raw: dict[str, object], path: Path) -> EnumDefaults: if "maxLength" not in enums: return EnumDefaults() value = enums["maxLength"] + # A whole number however JSON spells it (32, 32.0, 1e2): a reader that parses numbers as + # doubles (TypeScript's) cannot tell those apart, so every port accepts all three. + if isinstance(value, float) and value.is_integer(): + value = int(value) if isinstance(value, bool) or not isinstance(value, int) or value <= 0: raise ParseError( f"{path}: 'enums.maxLength' must be a positive integer, got {value!r}", diff --git a/server/python/src/metaobjects/enum_length.py b/server/python/src/metaobjects/enum_length.py index 1d3a85ab4e..23bf1241e0 100644 --- a/server/python/src/metaobjects/enum_length.py +++ b/server/python/src/metaobjects/enum_length.py @@ -48,6 +48,9 @@ def resolve_enum_max_length(field: "MetaData") -> int | None: """ if field.sub_type != FIELD_SUBTYPE_ENUM or field.get_meta_attr(FIELD_ATTR_INT_VALUE_MAP) is not None: return None + # An array enum is a text[] column, whose elements carry no length (ADR-0039: resolving). + if field.resolved_is_array(): + return None own = field.get_meta_attr(FIELD_ATTR_MAX_LENGTH) if isinstance(own, int) and not isinstance(own, bool): return own diff --git a/server/python/tests/codegen/test_enum_max_length_model.py b/server/python/tests/codegen/test_enum_max_length_model.py new file mode 100644 index 0000000000..420d16f72e --- /dev/null +++ b/server/python/tests/codegen/test_enum_max_length_model.py @@ -0,0 +1,31 @@ +"""An enum's @maxLength is its column length, not an input rule: the generated model puts no +``max_length`` on it (the ``Literal`` of its members is the rule, and every member fits), while +a string's @maxLength still becomes ``max_length``.""" +from __future__ import annotations + +import json + +import metaobjects.core_types # noqa: F401 — side-effect: registers attr classes + +from metaobjects import InMemoryStringSource, MetaDataFormat, MetaDataLoader +from metaobjects.codegen.generators.entity_model import _validator_constraints +from metaobjects.shared.base_types import TYPE_OBJECT + +_MODEL = {"metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "Ticket", "children": [ + {"source.rdb": {}}, + {"field.long": {"name": "id"}}, + {"field.enum": {"name": "status", "@values": ["OPEN", "CLOSED"], "@maxLength": 16}}, + {"field.string": {"name": "title", "@maxLength": 40}}, + {"identity.primary": {"name": "pk", "@fields": "id"}}, + ]}}, +]}} + + +def test_an_enum_column_length_is_not_a_model_constraint() -> None: + result = MetaDataLoader().load([InMemoryStringSource(json.dumps(_MODEL), format=MetaDataFormat.JSON)]) + assert not result.errors + ticket = next(c for c in result.root.children() if c.type == TYPE_OBJECT and c.name == "Ticket") + fields = {f.name: f for f in ticket.fields()} + assert "max_length" not in _validator_constraints(fields["status"], wire=False) + assert _validator_constraints(fields["title"], wire=False).get("max_length") == 40 diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 1cce63cf60..eb0cc31092 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -172,6 +172,13 @@ function attrAsStringArray(attr: unknown): string[] { return []; } +/** An enum member longer than the project's enums.maxLength: a metadata defect, reported by name. */ +function refuseEnumLength(err: Error): number { + log.error(`verify: ${err.message}`); + log.error(`verify: ${ENUM_LENGTH_HINT}`); + return 1; +} + export async function verifyCommand( args: string[], cwd: string, @@ -714,11 +721,16 @@ export async function verifyCommand( // passes no `governed` and gets the comparison exactly as it was. let governed: GovernedScope | undefined; if (schemaScope !== undefined) { - const built = buildExpectedSchemaWithProvenance(root, { - dialect, - views: buildProjectionViews(root, { dialect }), - }); - governed = scopeExpectedSchema(built, schemaScope, importedOption(collection)); + try { + const built = buildExpectedSchemaWithProvenance(root, { + dialect, + views: buildProjectionViews(root, { dialect }), + }); + governed = scopeExpectedSchema(built, schemaScope, importedOption(collection)); + } catch (err) { + if (isEnumLengthRefusal(err)) return refuseEnumLength(err); + throw err; + } } // `verifyReplay` calls `applyPending` itself. That is NOT a second replay: the @@ -1309,13 +1321,21 @@ export async function verifyCommand( // work at the top of `verifyCommand`, because `migrate.scope` governs only the // schema gate: a stale pattern must not fail a `--templates` run that never // consults it. - const scopeMismatch = migrateScopeMismatch(collection, () => { - const dialect: Dialect = usingD1 ? "d1" : (flags.dialect ?? inferDialect(flags.db as string)); - return buildExpectedSchemaWithProvenance(root, { - dialect, - views: buildProjectionViews(root, { dialect }), - }).provenance; - }); + let scopeMismatch: string | undefined; + try { + scopeMismatch = migrateScopeMismatch(collection, () => { + const dialect: Dialect = usingD1 ? "d1" : (flags.dialect ?? inferDialect(flags.db as string)); + return buildExpectedSchemaWithProvenance(root, { + dialect, + views: buildProjectionViews(root, { dialect }), + }).provenance; + }); + } catch (err) { + // Building the expected schema to check the scope raises the same metadata refusals + // the comparison below would; report them by name, not as an uncaught error. + if (isEnumLengthRefusal(err)) return refuseEnumLength(err); + throw err; + } if (scopeMismatch !== undefined) { log.error(`verify: ${scopeMismatch}`); return 2; @@ -1409,11 +1429,7 @@ export async function verifyCommand( log.error("verify: declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"); return 1; } - if (isEnumLengthRefusal(err)) { - log.error(`verify: ${err.message}`); - log.error(`verify: ${ENUM_LENGTH_HINT}`); - return 1; - } + if (isEnumLengthRefusal(err)) return refuseEnumLength(err); if (isUnknownSchemaConventionsError(err)) { log.error(`verify: ${err.message}`); return 2; diff --git a/server/typescript/packages/cli/src/lib/collection-load-options.ts b/server/typescript/packages/cli/src/lib/collection-load-options.ts index d645e7e465..9b2cb0e8eb 100644 --- a/server/typescript/packages/cli/src/lib/collection-load-options.ts +++ b/server/typescript/packages/cli/src/lib/collection-load-options.ts @@ -12,6 +12,7 @@ // `ERR_DEPENDENCY_PACKAGE_NOT_OWNED` refusal, so a node declared into a // dependency's package is silently excluded from that command's output instead // of being refused by name. +import { DEFAULT_ENUM_DEFAULTS } from "@metaobjectsdev/metadata"; import type { Collection, LoadMemoryOptions } from "@metaobjectsdev/sdk"; /** @@ -40,7 +41,7 @@ export function collectionLoadOptions( libraries: collection.libraries, physicalNaming: collection.physicalNaming, wireFormat: collection.wireFormat, - enumDefaults: collection.enumDefaults, + enumDefaults: collection.enumDefaults ?? DEFAULT_ENUM_DEFAULTS, ...(collection.schemaConventions !== undefined ? { schemaConventions: collection.schemaConventions } : {}), }; } diff --git a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts index c41716ac95..24e600b9ba 100644 --- a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts +++ b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts @@ -98,5 +98,12 @@ describe("meta verify — schema refusals", () => { expect(code).toBe(1); expect(out).toContain('field.enum "Ticket.status" has the member "IN_PROGRESS"'); expect(out).not.toContain("failed to introspect"); + + // The same refusal under migrate.scope, whose scope check builds the expected schema first. + await writeFile(join(root, ".metaobjects", "config.json"), + JSON.stringify({ schema_version: 1, enums: { maxLength: 10 }, migrate: { scope: ["acme::*"] } }), "utf8"); + const scoped = await capture(() => verifyCommand(["--db", `file:${join(root, "t.db")}`], root)); + expect(scoped.code).toBe(1); + expect(scoped.out).toContain('field.enum "Ticket.status" has the member "IN_PROGRESS"'); }); }); diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index 1fa2e4c2a6..fbc2dae73b 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -787,8 +787,9 @@ export function mapColumnType( fnName = enumIntCustomType?.fnConstName ?? "integer"; } else { // A length (core's resolveEnumMaxLength) is the VARCHAR(n) `meta migrate` - // creates; with none the column is unbounded text, as before. - const sized = resolveEnumMaxLength(field); + // creates; with none the column is unbounded text, as before. An array enum is + // a text[] column, whose elements carry no length (migrate's arrayElementSqlType). + const sized = isArray ? undefined : resolveEnumMaxLength(field); if (sized !== undefined) { fnName = "varchar"; fnOptions = { length: sized }; diff --git a/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts b/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts index 1d30363650..4fb4ced2e4 100644 --- a/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts +++ b/server/typescript/packages/codegen-ts/src/templates/entity-ui-descriptor.ts @@ -39,6 +39,7 @@ import { VIEW_SUBTYPE_HIDDEN, VIEW_SUBTYPE_DROPDOWN, VIEW_SUBTYPE_RADIO, + FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, VALIDATOR_SUBTYPE_REQUIRED, @@ -268,9 +269,10 @@ function buildFieldRules(field: MetaField): UiRule[] { rules.push({ kind: "required", message: `${humanize(field.name)} is required` }); } - // Field-level @maxLength attr (if not already covered). + // Field-level @maxLength attr (if not already covered). On a field.enum it is the column + // length, not an input rule: the member list is the rule, and every member fits. const maxLenAttr = field.attr(FIELD_ATTR_MAX_LENGTH); - if (!hasMaxLength && typeof maxLenAttr === "number") { + if (!hasMaxLength && typeof maxLenAttr === "number" && field.subType !== FIELD_SUBTYPE_ENUM) { rules.push({ kind: "maxLength", value: maxLenAttr, diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts index 03496dfc4a..c932d7bd6a 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-max-length.test.ts @@ -46,4 +46,12 @@ describe("Drizzle: a string-stored enum's column length", () => { test("MySQL: @maxLength beats the longest member", async () => { expect(await emit({ "@values": VALUES, "@maxLength": 16 }, "mysql")).toContain('varchar("status", { length: 16, enum:'); }); + + test("Postgres: an array enum stays text[] — migrate's column — whatever the length", async () => { + const own = await emit({ "@values": VALUES, "@maxLength": 16, isArray: true }, "postgres"); + expect(own).not.toContain("varchar("); + // A member longer than the project default does not refuse an array enum: it has no length. + const long = await emit({ "@values": ["A_VERY_LONG_MEMBER"], isArray: true }, "postgres", 4); + expect(long).not.toContain("varchar("); + }); }); diff --git a/server/typescript/packages/codegen-ts/test/enum-max-length-ui.test.ts b/server/typescript/packages/codegen-ts/test/enum-max-length-ui.test.ts new file mode 100644 index 0000000000..61184bc37d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/enum-max-length-ui.test.ts @@ -0,0 +1,26 @@ +// An enum's @maxLength is its column length, not an input rule: the UI descriptor emits no +// maxLength rule for it (the member list is the rule), while a string's @maxLength still is one. +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource, type MetaObject } from "@metaobjectsdev/metadata"; +import { buildUiFieldDescriptor } from "../src/templates/entity-ui-descriptor.js"; + +describe("UI descriptor — @maxLength", () => { + test("an enum's column length is not a form rule; a string's maxLength still is", async () => { + const json = JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": {} }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["OPEN", "CLOSED"], "@maxLength": 16 } }, + { "field.string": { name: "title", "@maxLength": 40 } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }, + ] } }); + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(errors).toEqual([]); + const ticket = root.findObject("Ticket") as MetaObject; + const rules = (name: string) => + JSON.stringify(buildUiFieldDescriptor(ticket.fields().find((f) => f.name === name)!, root)); + expect(rules("status")).not.toContain("maxLength"); + expect(rules("title")).toContain("maxLength"); + }); +}); diff --git a/server/typescript/packages/metadata/src/enum-length.ts b/server/typescript/packages/metadata/src/enum-length.ts index 568c077adb..af3d3e5a90 100644 --- a/server/typescript/packages/metadata/src/enum-length.ts +++ b/server/typescript/packages/metadata/src/enum-length.ts @@ -33,7 +33,8 @@ export function enumDefaultsOf(node: MetaData): EnumDefaults { /** * The column length of `field`, a string-stored `field.enum`: its @maxLength (ADR-0039 — * resolving, it may be inherited), else the project default, else undefined. Undefined for - * an @intValueMap enum, whose column is an integer, and for any other field. + * an @intValueMap enum, whose column is an integer, for an array enum, a text[] column whose + * elements carry no length, and for any other field. * * The loader refuses an @maxLength a member does not fit; it does not see the project * config, so a member longer than the project DEFAULT is refused here, by every consumer @@ -41,6 +42,8 @@ export function enumDefaultsOf(node: MetaData): EnumDefaults { */ export function resolveEnumMaxLength(field: MetaData): number | undefined { if (field.subType !== FIELD_SUBTYPE_ENUM || field.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined) return undefined; + // An array enum is a text[] column, whose elements carry no length (ADR-0039: resolving). + if ((field as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() === true) return undefined; const own = field.attr(FIELD_ATTR_MAX_LENGTH); if (typeof own === "number") return own; const fallback = enumDefaultsOf(field).maxLength; diff --git a/server/typescript/packages/sdk/src/collection.ts b/server/typescript/packages/sdk/src/collection.ts index 4fad56b18f..ae40583fa9 100644 --- a/server/typescript/packages/sdk/src/collection.ts +++ b/server/typescript/packages/sdk/src/collection.ts @@ -87,8 +87,9 @@ export interface Collection { readonly physicalNaming: PhysicalNaming; /** The `wire` block of the project config (ADR-0019 Amendment 2), default when absent. */ readonly wireFormat: WireFormat; - /** The `enums` block of the project config (string-stored enum defaults), none when absent. */ - readonly enumDefaults: EnumDefaults; + /** The `enums` block of the project config (string-stored enum defaults), none when absent. + * Optional so a hand-built Collection from before the block existed still type-checks. */ + readonly enumDefaults?: EnumDefaults | undefined; /** `migrate.conventions` of the project config — a schema-conventions preset name — when set. */ readonly schemaConventions: string | undefined; /** FR-023 — the `FileSource` id each file loads under, for the dependency From 0001ddd9462f508ecf1e3aa18024e46a71234c4f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 08:44:50 -0500 Subject: [PATCH 018/267] feat(identity): @sequenceStart and @sequenceName on an increment primary key An @generation "increment" key's sequence can be given its first value and its physical name, so a model can reproduce a table that keeps a low id range for seeded rows, or adopt a sequence that kept its name across a table rename. - Vocabulary (db provider, every port): @sequenceStart (long) and @sequenceName (string) on identity.primary; either one without @generation "increment" is refused at load (ERR_SEQUENCE_WITHOUT_INCREMENT), every offender reported. - meta migrate (Postgres): CREATE emits GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "..." START WITH n); introspection reads each auto-increment column's sequence (pg_depend + pg_sequence); a live sequence whose declared start or name differs is altered in place (alter-sequence: ALTER SEQUENCE ... START WITH / RENAME TO), with the down reversing it. Only what the model declares is compared, so existing databases see no new change. SQLite/D1: no-op. - Verified end to end on Postgres: fresh build, verify --db clean, a drifted live sequence reported and fixed by the generated migration. - Conformance: a passing and an error fixture in every port; registry and provider index regenerated; docs and CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 10 +++ docs/CONFORMANCE.md | 6 +- docs/features/entities.md | 4 + docs/features/migrations-and-drift.md | 26 ++++++ examples/showcase/site-payload.json | 2 +- fixtures/conformance/ERROR-CODES.json | 1 + .../expected-errors.json | 15 ++++ .../input/meta.seq.json | 32 +++++++ .../identity-primary-sequence/expected.json | 35 ++++++++ .../input/meta.seq.json | 25 ++++++ fixtures/metamodel-docs/expected/providers.md | 1 + .../metamodel-docs/expected/types/identity.md | 2 + .../expected-registry.json | 14 ++++ fixtures/registry-conformance/providers.json | 1 + scripts/check-doc-examples.ts | 1 + server/csharp/MetaObjects/Errors.cs | 2 + .../MetaObjects/Loader/MetaDataLoader.cs | 1 + .../MetaObjects/Loader/ValidationPasses.cs | 29 +++++++ .../MetaObjects/Persistence/Db/DbConstants.cs | 4 + .../MetaObjects/Persistence/Db/DbProvider.cs | 4 + .../MetaObjects/Persistence/Db/DbSchema.cs | 14 ++++ .../csharp/MetaObjects/SpecMetamodel/db.json | 8 ++ .../main/java/com/metaobjects/ErrorCode.java | 1 + .../metaobjects/identity/PrimaryIdentity.java | 10 +++ .../metaobjects/loader/ValidationPhase.java | 33 ++++++++ .../util/ErrorMessageConstants.java | 7 ++ server/python/src/metaobjects/errors.py | 1 + .../metaobjects/loader/validation_passes.py | 44 ++++++++++ .../meta/persistence/db/db_constants.py | 4 + .../meta/persistence/db/db_provider.py | 22 ++++- .../src/metaobjects/spec_metamodel/db.json | 8 ++ .../packages/cli/src/commands/verify.ts | 1 + .../typescript/packages/cli/src/lib/allow.ts | 5 ++ .../packages/metadata/src/errors.ts | 2 + .../metadata/src/loader/meta-data-loader.ts | 5 +- .../metadata/src/loader/validation-passes.ts | 30 ++++++- .../src/persistence/db/db-constants.ts | 4 + .../persistence/db/db-definition.embedded.ts | 22 +++++ .../packages/migrate-ts/src/diff/index.ts | 15 ++++ .../packages/migrate-ts/src/diff/status.ts | 4 + .../packages/migrate-ts/src/emit/postgres.ts | 29 ++++++- .../packages/migrate-ts/src/emit/sqlite.ts | 8 +- .../packages/migrate-ts/src/errors.ts | 1 + .../migrate-ts/src/expected-schema.ts | 22 ++++- .../migrate-ts/src/introspect/postgres.ts | 37 ++++++++ .../packages/migrate-ts/src/types.ts | 14 ++++ .../test/unit/identity-sequence.test.ts | 84 +++++++++++++++++++ site-reference/providers.html | 1 + site-reference/types/identity.html | 18 ++++ spec/metamodel/db.json | 8 ++ 51 files changed, 664 insertions(+), 15 deletions(-) create mode 100644 fixtures/conformance/error-identity-sequence-without-increment/expected-errors.json create mode 100644 fixtures/conformance/error-identity-sequence-without-increment/input/meta.seq.json create mode 100644 fixtures/conformance/identity-primary-sequence/expected.json create mode 100644 fixtures/conformance/identity-primary-sequence/input/meta.seq.json create mode 100644 server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts diff --git a/AGENTS.md b/AGENTS.md index 61c13e1f1e..1d92921c0d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (427 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (429 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index af1d6f7cfe..1a1da07cd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,16 @@ here.** that generated before still generates. In C# and Java, a names class no longer extends its base's when that would make a base constant that is not a column of its own table reachable through it (a flattened field redeclared as jsonb, say); it is emitted complete instead. +- **`@sequenceStart` and `@sequenceName` on `identity.primary`.** An `@generation: increment` + key's sequence can be given its first value and its physical name, so a model can reproduce a + table that keeps a low id range for seeded rows, or adopt a sequence that kept its name across + a table rename. On Postgres `meta migrate` creates + `GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "…" START WITH n)`, reads the live sequence + back from the catalog, and alters one whose declared start or name differs in place + (`ALTER SEQUENCE … START WITH` / `RENAME TO`); only what the model declares is compared, so + existing databases see no new change. Every port registers both attributes and refuses either + without `@generation: increment` (`ERR_SEQUENCE_WITHOUT_INCREMENT`). See + `docs/features/migrations-and-drift.md`. - **A string-stored enum's column length: `@maxLength` on `field.enum`, and `enums.maxLength`.** `@maxLength` on a `field.enum` makes its column `VARCHAR(n)`, and `"enums": { "maxLength": n }` in `.metaobjects/config.json` gives every enum without one a default; with neither, the column diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 956ec04adb..023d89bbc7 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 427 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 429 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -286,7 +286,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (427) +### `fixtures/conformance/` — metamodel loader + canonical serializer (429) | Fixture prefix | Feature doc | |---|---| @@ -612,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 427 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 429 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/entities.md b/docs/features/entities.md index 74f96a2a36..d05623d2d1 100644 --- a/docs/features/entities.md +++ b/docs/features/entities.md @@ -83,6 +83,10 @@ YAML is desugared to canonical JSON at load time. See > an `ERR_TOO_MANY_OCCURRENCES` load error. `identity.secondary` / `identity.reference` > are not singletons and DO require an explicit `name`. +An `@generation: increment` key's sequence can be given a start value (`@sequenceStart`) and +a physical name (`@sequenceName`); see +[migrations-and-drift.md](migrations-and-drift.md#an-increment-keys-sequence-sequencestart-and-sequencename). + ## `extends:` for shared abstract bases Common base fields (`id`, `createdAt`, `updatedAt`) live on an abstract entity that diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index d5282d43dc..624a5e0491 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -282,6 +282,32 @@ sequence, or pass `--allow drop-identity-default` if removing auto-increment is intentional. An identity that *does* declare `@generation: increment` never reaches this gate (its default diff is skipped), so only the undeclared case fires. +#### An increment key's sequence: `@sequenceStart` and `@sequenceName` + +An `@generation: increment` key draws from a sequence. Two attributes on the +`identity.primary` describe it, for a database the model must reproduce or adopt: + +```json +{ "identity.primary": { "@fields": "id", "@generation": "increment", + "@sequenceStart": 1000000000, "@sequenceName": "Ticket_Id_seq" } } +``` + +- `@sequenceStart` is the first value handed out. Absent: 1. Use it for a table that keeps a + low id range for rows it seeds itself. +- `@sequenceName` is the sequence's physical name. Absent: the database's own default + (`
    When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer).
    @flattenedColumnPrefixstringnometaobjects-dbOn a field.object with @storage "flattened": the text put before each member's column, verbatim ("" allowed, so the members keep their own column names). Absent: this field's resolved column name and "" (with @column "bill", the members are bill). A fact about the owning table, so it lives on the embedding field, never on the value object. Refused on any other storage (ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE).
    @formExclude boolean no
    Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language.
    @maxLengthintnometaobjects-core-typesColumn length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer.
    @mutability string no
    __seq` on Postgres). Use it for a sequence that kept its name when its + table was renamed. + +On Postgres `meta migrate` creates the column as +`GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "…" START WITH n)`, and `meta verify --db` +reads the live sequence back from the catalog. A live sequence whose start or name differs +from the declaration is altered in place (`ALTER SEQUENCE … START WITH n`, +`ALTER SEQUENCE … RENAME TO …`), never dropped, and the down migration reverses it. Only what +the model declares is compared: a database whose sequence kept an old name sees no change +until the model names it. SQLite and D1 have no sequences to name, so both attributes change +nothing there. Either attribute without `@generation: increment` is refused at load +(`ERR_SEQUENCE_WITHOUT_INCREMENT`). + ### Java Schema migrations for Java projects are owned by the **TypeScript toolchain** diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index d2c7c68c66..64d932cbb5 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 427, + "fixtures": 429, "corpora": 36, "baseTypes": 17 }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 13b6814ec5..344aa26335 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -53,6 +53,7 @@ "ERR_TEMPLATE_ENGINE_UNSUPPORTED": "Build-time verify and render (ADR-0061): a template body is written for an engine this port does not ship — a Jinja body (.jinja / .j2 / .jinja2) in the Java, Kotlin or C# port, which render Mustache only. path = the template ref.", "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate or object.report (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", + "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", diff --git a/fixtures/conformance/error-identity-sequence-without-increment/expected-errors.json b/fixtures/conformance/error-identity-sequence-without-increment/expected-errors.json new file mode 100644 index 0000000000..57289aed65 --- /dev/null +++ b/fixtures/conformance/error-identity-sequence-without-increment/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_SEQUENCE_WITHOUT_INCREMENT", + "source": { + "format": "json", + "files": [ + "meta.seq.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['identity.primary']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-identity-sequence-without-increment/input/meta.seq.json b/fixtures/conformance/error-identity-sequence-without-increment/input/meta.seq.json new file mode 100644 index 0000000000..53ce09e514 --- /dev/null +++ b/fixtures/conformance/error-identity-sequence-without-increment/input/meta.seq.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Ticket", + "children": [ + { + "source.rdb": { + "@table": "tickets" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "assigned", + "@sequenceStart": 1000000000 + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/identity-primary-sequence/expected.json b/fixtures/conformance/identity-primary-sequence/expected.json new file mode 100644 index 0000000000..2819942a8a --- /dev/null +++ b/fixtures/conformance/identity-primary-sequence/expected.json @@ -0,0 +1,35 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Ticket", + "children": [ + { + "source.rdb": { + "@table": "tickets" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ], + "@generation": "increment", + "@sequenceName": "Ticket_Id_seq", + "@sequenceStart": 1000000000 + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/identity-primary-sequence/input/meta.seq.json b/fixtures/conformance/identity-primary-sequence/input/meta.seq.json new file mode 100644 index 0000000000..86a6973911 --- /dev/null +++ b/fixtures/conformance/identity-primary-sequence/input/meta.seq.json @@ -0,0 +1,25 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Ticket", + "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "increment", + "@sequenceStart": 1000000000, + "@sequenceName": "Ticket_Id_seq" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 703a3723c5..3fe2e887ad 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -77,6 +77,7 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `field.timestamp`: `@autoSet`, `@column`, `@db.indexed`, `@dbColumnType`, `@localTime` - `field.uri`: `@column`, `@db.indexed`, `@dbColumnType` - `field.uuid`: `@column`, `@db.indexed`, `@dbColumnType` +- `identity.primary`: `@sequenceName`, `@sequenceStart` - `identity.reference`: `@constraintName`, `@onDelete`, `@onUpdate` - `identity.secondary`: `@expr`, `@orders`, `@using`, `@where` - `index.lookup`: `@expr`, `@orders`, `@using`, `@where` diff --git a/fixtures/metamodel-docs/expected/types/identity.md b/fixtures/metamodel-docs/expected/types/identity.md index 74456e20fb..4ca43a3722 100644 --- a/fixtures/metamodel-docs/expected/types/identity.md +++ b/fixtures/metamodel-docs/expected/types/identity.md @@ -24,6 +24,8 @@ The primary key — one per entity; @fields names its column(s), @generation the | --- | --- | --- | --- | --- | --- | --- | | `@fields` | string[] | yes | | | metaobjects-core-types | The field name(s) composing this identity. Single-element for a simple PK/index, multiple for a composite. | | `@generation` | string | no | | `increment`, `uuid`, `assigned` | metaobjects-core-types | Primary-key value generation strategy: 'increment' (auto-increment), 'uuid', or 'assigned' (caller-supplied). | +| `@sequenceName` | string | no | | | metaobjects-db | The physical name of an @generation "increment" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation "increment" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider. | +| `@sequenceStart` | long | no | | | metaobjects-db | The first value an @generation "increment" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation "increment" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider. | **Allowed children** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 498513646e..3fddf47555 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -2915,6 +2915,20 @@ "assigned" ], "description": "Primary-key value generation strategy: 'increment' (auto-increment), 'uuid', or 'assigned' (caller-supplied)." + }, + { + "name": "sequenceName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." + }, + { + "name": "sequenceStart", + "valueType": "long", + "isArray": false, + "required": false, + "description": "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." } ], "children": [] diff --git a/fixtures/registry-conformance/providers.json b/fixtures/registry-conformance/providers.json index 10930e07b4..ee86a2fdf8 100644 --- a/fixtures/registry-conformance/providers.json +++ b/fixtures/registry-conformance/providers.json @@ -26,6 +26,7 @@ "field.object", "field.time", "field.timestamp", + "identity.primary", "identity.reference", "identity.secondary", "index.lookup", diff --git a/scripts/check-doc-examples.ts b/scripts/check-doc-examples.ts index 9220502587..6f1a7e6c3d 100644 --- a/scripts/check-doc-examples.ts +++ b/scripts/check-doc-examples.ts @@ -157,6 +157,7 @@ const FAIL_CODES = new Set([ "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", + "ERR_SEQUENCE_WITHOUT_INCREMENT", "ERR_PHYSICAL_NAME_KIND_MISMATCH", "ERR_PHYSICAL_NAME_MULTIPLE", "ERR_SQL_BODY_ON_WRITABLE_KIND", diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 55eaf0c7a0..8855dccd38 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -310,6 +310,8 @@ public enum ErrorCode // field.enum @maxLength: a member longer than the column, or a length on an int-stored enum. ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, + // identity.primary @sequenceStart / @sequenceName without @generation "increment". + ERR_SEQUENCE_WITHOUT_INCREMENT, } /// diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 0ac515cfc7..b2ea908026 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -537,6 +537,7 @@ public LoadResult Load(IReadOnlyList sources) // and @valueType (when set) must name a known scalar subtype. errors.AddRange(ValidationPasses.ValidateFieldMap(root)); errors.AddRange(ValidationPasses.ValidateEnumMaxLength(root)); + errors.AddRange(ValidationPasses.ValidateIdentitySequence(root)); // Pass 9: template @payloadRef / @requiredSlots resolution errors.AddRange(ValidationPasses.ValidateTemplatePayloadRefs(root)); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 0135e02f6b..fd509af5b7 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2100,6 +2100,35 @@ private static void ValidateAttrSchemaNode( // enum that only inherits them is not reported twice. Every field.enum in the tree is // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. // --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation + // "increment" key draws from; on any other generation there is none, so either one is + // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the + // identity that declares one of them. Mirrors TS validateIdentitySequence. + // --------------------------------------------------------------------------- + public static IReadOnlyList ValidateIdentitySequence(MetaData root) + { + var errors = new List(); + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT)) + { + foreach (var id in obj.OwnChildren().Where(c => c.Type == TYPE_IDENTITY && c.SubType == IDENTITY_SUBTYPE_PRIMARY)) + { + var declared = new[] { MetaObjects.Persistence.Db.DbConstants.IDENTITY_ATTR_SEQUENCE_START, MetaObjects.Persistence.Db.DbConstants.IDENTITY_ATTR_SEQUENCE_NAME } + .Where(a => id.OwnAttr(a) is not null).ToList(); + var generation = id.Attr(IDENTITY_ATTR_GENERATION) as string; + if (declared.Count == 0 || generation == GENERATION_INCREMENT) continue; + var shown = generation is null ? "not set" : $"\"{generation}\""; + var names = string.Join(" and ", declared.Select(a => "@" + a)); + errors.Add(new MetaError( + $"identity.primary \"{obj.Name}.{id.Name}\" sets {names}, but its @generation is {shown}; " + + $"only an @generation \"increment\" key draws from a sequence. Set @generation \"increment\", or remove {names}.", + ErrorCode.ERR_SEQUENCE_WITHOUT_INCREMENT, + Envelope: id.Source)); + } + } + return errors; + } + public static IReadOnlyList ValidateEnumMaxLength(MetaData root) { var errors = new List(); diff --git a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs index 774a2b28c7..dc0f4ed6d7 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs @@ -49,6 +49,10 @@ public static class DbConstants public const string IDENTITY_ATTR_USING = "using"; /// identity.reference: physical FK constraint-name override. Absent => the auto-derived default. public const string IDENTITY_ATTR_CONSTRAINT_NAME = "constraintName"; + /// identity.primary (@generation "increment"): the sequence's first value. Absent → 1. + public const string IDENTITY_ATTR_SEQUENCE_START = "sequenceStart"; + /// identity.primary (@generation "increment"): the sequence's physical name. Absent → the database's default. + public const string IDENTITY_ATTR_SEQUENCE_NAME = "sequenceName"; /// identity.reference: referential action on parent delete — the explicit per-FK override (ADR-0047). public const string IDENTITY_ATTR_ON_DELETE = "onDelete"; /// identity.reference: referential action on key update — the explicit per-FK override (ADR-0047). diff --git a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs index 14d2327e00..fa00eca507 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs @@ -69,6 +69,10 @@ public void RegisterTypes(TypeRegistry registry) MetaObjects.Shared.BaseTypes.TYPE_IDENTITY, IdentityConstants.IDENTITY_SUBTYPE_SECONDARY, attributes: [DbSchema.OrdersSchema, DbSchema.WhereSchema, DbSchema.ExprSchema, DbSchema.UsingSchema]); + registry.Extend( + MetaObjects.Shared.BaseTypes.TYPE_IDENTITY, + IdentityConstants.IDENTITY_SUBTYPE_PRIMARY, + attributes: [DbSchema.SequenceStartSchema, DbSchema.SequenceNameSchema]); registry.Extend( MetaObjects.Shared.BaseTypes.TYPE_IDENTITY, IdentityConstants.IDENTITY_SUBTYPE_REFERENCE, diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index 2e9ad070a5..96be31247f 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -104,6 +104,20 @@ public static class DbSchema Required: false, Description: "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider."); + /// @sequenceStart — the first value of an increment key's sequence; on identity.primary. + public static readonly AttrSchema SequenceStartSchema = new AttrSchema( + Name: DbConstants.IDENTITY_ATTR_SEQUENCE_START, + ValueType: AttrConstants.ATTR_SUBTYPE_LONG, + Required: false, + Description: "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider."); + + /// @sequenceName — the physical name of an increment key's sequence; on identity.primary. + public static readonly AttrSchema SequenceNameSchema = new AttrSchema( + Name: DbConstants.IDENTITY_ATTR_SEQUENCE_NAME, + ValueType: AttrConstants.ATTR_SUBTYPE_STRING, + Required: false, + Description: "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider."); + /// @constraintName — physical FK constraint-name override; on identity.reference. public static readonly AttrSchema ConstraintNameSchema = new AttrSchema( Name: DbConstants.IDENTITY_ATTR_CONSTRAINT_NAME, diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index 50b3584845..79734985ba 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -59,6 +59,14 @@ { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } ] }, + { + "type": "identity", + "subType": "primary", + "children": [ + { "type": "attr", "subType": "long", "name": "sequenceStart", "min": 0, "max": 1, "description": "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "sequenceName", "min": 0, "max": 1, "description": "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." } + ] + }, { "type": "identity", "subType": "reference", diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 191d9ccc9a..9eb36dee52 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -297,6 +297,7 @@ public enum ErrorCode { ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE, ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, + ERR_SEQUENCE_WITHOUT_INCREMENT, /** @storage was set on a field that has no @objectRef. */ ERR_STORAGE_WITHOUT_OBJECT_REF, diff --git a/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java b/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java index 7707736146..e9575b3d6a 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java +++ b/server/java/metadata/src/main/java/com/metaobjects/identity/PrimaryIdentity.java @@ -18,6 +18,11 @@ */ public class PrimaryIdentity extends MetaIdentity { + /** The first value of an increment key's sequence. Absent: 1. */ + public static final String ATTR_SEQUENCE_START = "sequenceStart"; + /** The physical name of an increment key's sequence. Absent: the database's default. */ + public static final String ATTR_SEQUENCE_NAME = "sequenceName"; + private static final Logger log = LoggerFactory.getLogger(PrimaryIdentity.class); /** @@ -50,6 +55,11 @@ public static void registerTypes(MetaDataRegistry registry) { def.requiredAttributeWithConstraints(ATTR_FIELDS).ofType(StringAttribute.SUBTYPE_STRING).asArray(); def.optionalAttributeWithConstraints(ATTR_GENERATION).ofType(StringAttribute.SUBTYPE_STRING).withEnum(GENERATION_INCREMENT, GENERATION_UUID, GENERATION_ASSIGNED); def.optionalAttributeWithConstraints(ATTR_DESCRIPTION).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + // The sequence an @generation "increment" key draws from: its first value and its + // physical name (spec/metamodel/db.json). Refused on any other generation, post-load + // in ValidationPhase.validateIdentitySequence. + def.optionalAttributeWithConstraints(ATTR_SEQUENCE_START).ofType(com.metaobjects.attr.LongAttribute.SUBTYPE_LONG).asSingle(); + def.optionalAttributeWithConstraints(ATTR_SEQUENCE_NAME).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); // ACCEPTS ANY ATTRIBUTES (for extensibility from service providers) // ADR-0051: NO any-attr wildcard. An undeclared attribute is ERR_UNKNOWN_ATTR in diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index abccf9fa71..a1c0724343 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -263,6 +263,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { pass(collected, () -> validateDerivedFieldProvidability(root)); pass(collected, () -> validateObjectFieldStorage(root)); validateEnumMaxLength(root, collected); + validateIdentitySequence(root, collected); pass(collected, () -> validateFieldMap(root)); pass(collected, () -> validateIdentityFieldsAndGeneration(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). @@ -2380,6 +2381,38 @@ private static List junctionReferenceFkFields(MetaObject junction) { // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. // ========================================================================= + // ========================================================================= + // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation + // "increment" key draws from; on any other generation there is none, so either one is + // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the + // identity that declares one of them, every offender collected. Mirrors TS. + // ========================================================================= + + static void validateIdentitySequence(MetaRoot root, List out) { + for (MetaObject obj : root.getChildren(MetaObject.class, false)) { + for (com.metaobjects.identity.PrimaryIdentity id + : obj.getChildren(com.metaobjects.identity.PrimaryIdentity.class, false)) { + List declared = new java.util.ArrayList<>(); + for (String a : List.of(com.metaobjects.identity.PrimaryIdentity.ATTR_SEQUENCE_START, + com.metaobjects.identity.PrimaryIdentity.ATTR_SEQUENCE_NAME)) { + if (id.hasMetaAttr(a, false)) declared.add("@" + a); + } + String generation = id.hasMetaAttr(com.metaobjects.identity.MetaIdentity.ATTR_GENERATION) + ? id.getMetaAttr(com.metaobjects.identity.MetaIdentity.ATTR_GENERATION).getValueAsString() : null; + if (declared.isEmpty() + || com.metaobjects.identity.MetaIdentity.GENERATION_INCREMENT.equals(generation)) continue; + String shown = generation == null ? "not set" : "\"" + generation + "\""; + String names = String.join(" and ", declared); + out.add(new MetaDataException( + ErrorMessageConstants.ERR_SEQUENCE_WITHOUT_INCREMENT + + ": identity.primary \"" + obj.getShortName() + "." + id.getShortName() + "\" sets " + + names + ", but its @generation is " + shown + "; only an @generation \"increment\"" + + " key draws from a sequence. Set @generation \"increment\", or remove " + names + ".", + ErrorCode.ERR_SEQUENCE_WITHOUT_INCREMENT, id.getSource())); + } + } + } + /** Every offending enum is reported, as the other ports do, not only the first. */ static void validateEnumMaxLength(MetaData node, List out) { for (MetaData child : node.getChildren(MetaData.class, false)) { diff --git a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java index 87f7bda1de..624ec24607 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java +++ b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java @@ -191,6 +191,13 @@ private ErrorMessageConstants() { */ public static final String ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP"; + /** + * An {@code identity.primary} sets {@code @sequenceStart} or {@code @sequenceName} without + * {@code @generation "increment"}: only an increment key draws from a sequence. + * Cross-language contract: {@code ERR_SEQUENCE_WITHOUT_INCREMENT}. + */ + public static final String ERR_SEQUENCE_WITHOUT_INCREMENT = "ERR_SEQUENCE_WITHOUT_INCREMENT"; + /** * Error code emitted when {@code field.object @storage} is set on a field that * has no {@code @objectRef} — storage shape only applies to referenced objects. diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index b3300b564e..3a7c655dd1 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -207,6 +207,7 @@ class ErrorCode(str, Enum): ERR_STORAGE_FLATTENED_ARRAY = "ERR_STORAGE_FLATTENED_ARRAY" ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH = "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP" + ERR_SEQUENCE_WITHOUT_INCREMENT = "ERR_SEQUENCE_WITHOUT_INCREMENT" ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE = ( "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE" ) diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 024216fa1c..a88cb58f86 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -251,6 +251,8 @@ def run_validations( _validate_field_object_storage(root, errors) # field.enum @maxLength — every member fits; refused with @intValueMap. _validate_enum_max_length(root, errors) + # identity.primary @sequenceStart / @sequenceName need @generation "increment". + _validate_identity_sequence(root, errors) # field.map — exactly one of @valueType (scalar) or @objectRef (VO), and # @valueType (when set) must name a known scalar subtype. _validate_field_map(root, errors) @@ -3720,6 +3722,48 @@ def _validate_sortable_has_supported_subtype( # members columns of their own to prefix). +# identity.primary @sequenceStart / @sequenceName describe the sequence an @generation +# "increment" key draws from; on any other generation there is none, so either one is refused +# (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the identity that +# declares one of them. Mirrors TS validateIdentitySequence. +def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None: + from ..meta.core.identity.identity_constants import ( + GENERATION_INCREMENT, + IDENTITY_ATTR_GENERATION, + IDENTITY_SUBTYPE_PRIMARY, + ) + from ..meta.persistence.db.db_constants import ( + IDENTITY_PRIMARY_ATTR_SEQUENCE_NAME, + IDENTITY_PRIMARY_ATTR_SEQUENCE_START, + ) + + for obj in root.children(): + if obj.type != TYPE_OBJECT: + continue + for ident in obj.own_children(): + if ident.type != TYPE_IDENTITY or ident.sub_type != IDENTITY_SUBTYPE_PRIMARY: + continue + declared = [ + f"@{a}" + for a in (IDENTITY_PRIMARY_ATTR_SEQUENCE_START, IDENTITY_PRIMARY_ATTR_SEQUENCE_NAME) + if ident.attr(a) is not None + ] + generation = ident.get_meta_attr(IDENTITY_ATTR_GENERATION) + if not declared or generation == GENERATION_INCREMENT: + continue + shown = f'"{generation}"' if isinstance(generation, str) else "not set" + names = " and ".join(declared) + errors.append(MetaError( + code=ErrorCode.ERR_SEQUENCE_WITHOUT_INCREMENT, + message=( + f'identity.primary "{obj.name}.{ident.name}" sets {names}, but its @generation ' + f'is {shown}; only an @generation "increment" key draws from a sequence. Set ' + f'@generation "increment", or remove {names}.' + ), + envelope=ident.source, + )) + + # field.enum @maxLength — the column length of a string-stored enum: # 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the longest # offender named; diff --git a/server/python/src/metaobjects/meta/persistence/db/db_constants.py b/server/python/src/metaobjects/meta/persistence/db/db_constants.py index 968978fb64..6fc5ee76f2 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_constants.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_constants.py @@ -76,6 +76,10 @@ IDENTITY_SECONDARY_ATTR_USING = "using" # identity.reference: physical FK constraint-name override. IDENTITY_REFERENCE_ATTR_CONSTRAINT_NAME = "constraintName" +#: identity.primary (@generation "increment"): the sequence's first value. Absent → 1. +IDENTITY_PRIMARY_ATTR_SEQUENCE_START = "sequenceStart" +#: identity.primary (@generation "increment"): the sequence's physical name. Absent → the database's default. +IDENTITY_PRIMARY_ATTR_SEQUENCE_NAME = "sequenceName" # identity.reference: referential action on parent delete — the explicit per-FK override (ADR-0047). IDENTITY_REFERENCE_ATTR_ON_DELETE = "onDelete" # identity.reference: referential action on key update — the explicit per-FK override (ADR-0047). diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index 52196e43f3..644ba3a73d 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -16,9 +16,10 @@ """ from __future__ import annotations -from ...core.attr.attr_constants import ATTR_SUBTYPE_BOOLEAN, ATTR_SUBTYPE_STRING +from ...core.attr.attr_constants import ATTR_SUBTYPE_BOOLEAN, ATTR_SUBTYPE_LONG, ATTR_SUBTYPE_STRING from ...core.field import field_constants as fc from ...core.identity.identity_constants import ( + IDENTITY_SUBTYPE_PRIMARY, IDENTITY_SUBTYPE_REFERENCE, IDENTITY_SUBTYPE_SECONDARY, ) @@ -29,6 +30,8 @@ from .db_constants import ( FIELD_ATTR_DB_COLUMN_TYPE, FIELD_ATTR_LOCAL_TIME, + IDENTITY_PRIMARY_ATTR_SEQUENCE_NAME, + IDENTITY_PRIMARY_ATTR_SEQUENCE_START, IDENTITY_REFERENCE_ATTR_CONSTRAINT_NAME, IDENTITY_REFERENCE_ATTR_ON_DELETE, IDENTITY_REFERENCE_ATTR_ON_UPDATE, @@ -130,6 +133,18 @@ "expression. RDB-physical — contributed by the db provider." ), ) +_SEQUENCE_START_SCHEMA = AttrSchema( + name=IDENTITY_PRIMARY_ATTR_SEQUENCE_START, + value_type=ATTR_SUBTYPE_LONG, + required=False, + description='The first value an @generation "increment" key\'s sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation "increment" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider.', +) +_SEQUENCE_NAME_SCHEMA = AttrSchema( + name=IDENTITY_PRIMARY_ATTR_SEQUENCE_NAME, + value_type=ATTR_SUBTYPE_STRING, + required=False, + description='The physical name of an @generation "increment" key\'s sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database\'s own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation "increment" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider.', +) _CONSTRAINT_NAME_SCHEMA = AttrSchema( name=IDENTITY_REFERENCE_ATTR_CONSTRAINT_NAME, value_type=ATTR_SUBTYPE_STRING, @@ -196,6 +211,11 @@ def _register(registry: TypeRegistry) -> None: IDENTITY_SUBTYPE_SECONDARY, attributes=[_ORDERS_SCHEMA, _WHERE_SCHEMA, _EXPR_SCHEMA, _USING_SCHEMA], ) + registry.extend( + TYPE_IDENTITY, + IDENTITY_SUBTYPE_PRIMARY, + attributes=[_SEQUENCE_START_SCHEMA, _SEQUENCE_NAME_SCHEMA], + ) registry.extend( TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE, diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index 50b3584845..79734985ba 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -59,6 +59,14 @@ { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } ] }, + { + "type": "identity", + "subType": "primary", + "children": [ + { "type": "attr", "subType": "long", "name": "sequenceStart", "min": 0, "max": 1, "description": "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "sequenceName", "min": 0, "max": 1, "description": "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." } + ] + }, { "type": "identity", "subType": "reference", diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index eb0cc31092..46433d8169 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -1930,6 +1930,7 @@ const DRIFT_PRESENTATION: Record c.type === TYPE_OBJECT)) { + for (const id of obj.ownChildren()) { + if (id.type !== TYPE_IDENTITY || id.subType !== IDENTITY_SUBTYPE_PRIMARY) continue; + const declared = [IDENTITY_ATTR_SEQUENCE_START, IDENTITY_ATTR_SEQUENCE_NAME].filter((a) => id.ownAttr(a) !== undefined); + if (declared.length === 0 || id.attr(IDENTITY_ATTR_GENERATION) === GENERATION_INCREMENT) continue; + const generation = id.attr(IDENTITY_ATTR_GENERATION); + const shown = typeof generation === "string" ? `"${generation}"` : "not set"; + errors.push(new ParseError( + `identity.primary "${obj.name}.${id.name}" sets ${declared.map((a) => `@${a}`).join(" and ")}, but its @generation is ${shown}; ` + + `only an @generation "increment" key draws from a sequence. Set @generation "increment", or remove ${declared.map((a) => `@${a}`).join(" and ")}.`, + { code: "ERR_SEQUENCE_WITHOUT_INCREMENT", source: id.source }, + )); + } + } + return errors; +} + // --------------------------------------------------------------------------- // field.enum @maxLength — the column length of a string-stored enum: // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the diff --git a/server/typescript/packages/metadata/src/persistence/db/db-constants.ts b/server/typescript/packages/metadata/src/persistence/db/db-constants.ts index 8e3e26b0f1..3ec3dfcdf5 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-constants.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-constants.ts @@ -30,6 +30,10 @@ export const IDENTITY_ATTR_EXPR = "expr"; export const IDENTITY_ATTR_USING = "using"; /** identity.reference: physical FK constraint-name override. Absent → the auto-derived `
    __fk`. */ export const IDENTITY_ATTR_CONSTRAINT_NAME = "constraintName"; +/** identity.primary (@generation "increment"): the sequence's first value. Absent → 1. */ +export const IDENTITY_ATTR_SEQUENCE_START = "sequenceStart"; +/** identity.primary (@generation "increment"): the sequence's physical name. Absent → the database's default. */ +export const IDENTITY_ATTR_SEQUENCE_NAME = "sequenceName"; /** * R6 Plan 2b: `@dbColumnType` — physical DB column-type override on a field. diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index 60e388d1e0..54114bbe19 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -254,6 +254,28 @@ export const DB_DEFINITION: ProviderDefinition = { } ] }, + { + "type": "identity", + "subType": "primary", + "children": [ + { + "type": "attr", + "subType": "long", + "name": "sequenceStart", + "min": 0, + "max": 1, + "description": "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." + }, + { + "type": "attr", + "subType": "string", + "name": "sequenceName", + "min": 0, + "max": 1, + "description": "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default,
    __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." + } + ] + }, { "type": "identity", "subType": "reference", diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index d82dfe1f1e..b4280ef209 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -868,6 +868,21 @@ function diffTableColumns( }; changes.push(change); } + // The declared start and name of an increment key's sequence, against the live sequence + // (Postgres only: SQLite has none, and its introspection reports no `sequence`). Only what + // the model declares is compared, so an undeclared one never produces a change. + if (ec.identity === "increment" && ec.sequence !== undefined && ac.sequence?.name !== undefined) { + const startDiffers = ec.sequence.start !== undefined && ac.sequence.start !== undefined + && ec.sequence.start !== ac.sequence.start; + const nameDiffers = ec.sequence.name !== undefined && ec.sequence.name !== ac.sequence.name; + if (startDiffers || nameDiffers) { + changes.push({ + kind: "alter-sequence", table, ...sx, column: name, sequence: ac.sequence.name, status: ALLOWED, + ...(startDiffers ? { fromStart: ac.sequence.start!, toStart: ec.sequence.start! } : {}), + ...(nameDiffers ? { toName: ec.sequence.name! } : {}), + }); + } + } if (canon.catalog === true) { // Both sides read `increment` off a GENERATED identity (attidentity) or a legacy serial's // nextval default; a serial losing its sequence is the default change above, not this. diff --git a/server/typescript/packages/migrate-ts/src/diff/status.ts b/server/typescript/packages/migrate-ts/src/diff/status.ts index 41e19013b5..cd7e2fe672 100644 --- a/server/typescript/packages/migrate-ts/src/diff/status.ts +++ b/server/typescript/packages/migrate-ts/src/diff/status.ts @@ -170,6 +170,10 @@ function blockFor( + `the column starts failing). Declare @generation: increment on the identity to keep it, or pass ` + `--allow drop-identity-default if removing it is intentional`); + // Altering a sequence's start or name keeps every value it has handed out. + case "alter-sequence": + return null; + case "change-comment": if (c.from === undefined || c.to !== undefined) return null; return gate(allow, "dropComment", `${c.column !== undefined ? `column "${c.table}"."${c.column}"` : `table "${c.table}"`} ` diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index e9f37e08ef..e32eb44e10 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -46,6 +46,8 @@ const STAGE_ORDER: Record = { "add-column": 2, "drop-column": 2, "change-column-type": 2, "change-column-nullable": 2, "change-column-default": 2, "change-column-identity": 2, + // After column changes (the identity exists), before anything that could read the name. + "alter-sequence": 2.5, "rename-column": 3, "change-comment": 3.5, "add-index": 4, @@ -251,6 +253,7 @@ function renderUp(c: Change, recreated: ReadonlySet = new Set()): string ? `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} SET DEFAULT ${renderDefault(c.to)};` : `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} DROP DEFAULT;`; case "change-column-identity": return renderIdentity(c.table, c.schema, c.column, c.to); + case "alter-sequence": return renderAlterSequence(c.schema, c.sequence, c.toStart, c.toName); case "change-comment": return renderComment(c.table, c.schema, c.column, c.to); case "add-index": return renderCreateIndex(c.table, c.schema, c.index); // #285: an index OWNED by a UNIQUE / PRIMARY KEY / EXCLUDE constraint cannot be @@ -395,6 +398,13 @@ function renderDown(c: Change, recreated: ReadonlySet = new Set()): stri ? `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} SET DEFAULT ${renderDefault(c.from)};` : `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} DROP DEFAULT;`; case "change-column-identity": return renderIdentity(c.table, c.schema, c.column, c.from); + // The down addresses the sequence by the name the up gave it, and runs in reverse order: + // rename back first, then restore the start. + case "alter-sequence": + return [ + ...(c.toName !== undefined ? [`ALTER SEQUENCE ${quoteQualified(c.toName, c.schema)} RENAME TO ${quote(c.sequence)};`] : []), + ...(c.fromStart !== undefined ? [`ALTER SEQUENCE ${quoteQualified(c.sequence, c.schema)} START WITH ${c.fromStart};`] : []), + ].join("\n"); case "change-comment": return renderComment(c.table, c.schema, c.column, c.from); case "add-index": return isUniqueConstraint(c.index) @@ -477,6 +487,14 @@ function renderTableComments(t: TableDescriptor): string[] { return out; } +/** Start first, under the live name; then the rename. */ +function renderAlterSequence(schema: string | undefined, sequence: string, toStart: number | undefined, toName: string | undefined): string { + return [ + ...(toStart !== undefined ? [`ALTER SEQUENCE ${quoteQualified(sequence, schema)} START WITH ${toStart};`] : []), + ...(toName !== undefined ? [`ALTER SEQUENCE ${quoteQualified(sequence, schema)} RENAME TO ${quote(toName)};`] : []), + ].join("\n"); +} + function renderIdentity(table: string, schema: string | undefined, column: string, to: "increment" | undefined): string { const alter = `ALTER TABLE ${quoteQualified(table, schema)} ALTER COLUMN ${quote(column)}`; return to === "increment" ? `${alter} ADD GENERATED BY DEFAULT AS IDENTITY;` : `${alter} DROP IDENTITY IF EXISTS;`; @@ -524,7 +542,7 @@ function hazardComment(h: DataHazard): string { function renderColumn(c: ColumnDescriptor): string { let s = `${quote(c.name)} ${pgType(c.sqlType)}`; - if (c.identity === "increment") s += " GENERATED BY DEFAULT AS IDENTITY"; + if (c.identity === "increment") s += " GENERATED BY DEFAULT AS IDENTITY" + identityOptions(c); if (c.identity === "uuid") s += " DEFAULT gen_random_uuid()"; s += c.nullable ? "" : " NOT NULL"; if (c.default !== undefined && c.identity === undefined) { @@ -536,6 +554,15 @@ function renderColumn(c: ColumnDescriptor): string { return s; } +/** ` (SEQUENCE NAME "x" START WITH n)` for what the model declares, else nothing. */ +function identityOptions(c: ColumnDescriptor): string { + const opts = [ + ...(c.sequence?.name !== undefined ? [`SEQUENCE NAME ${quote(c.sequence.name)}`] : []), + ...(c.sequence?.start !== undefined ? [`START WITH ${c.sequence.start}`] : []), + ]; + return opts.length === 0 ? "" : ` (${opts.join(" ")})`; +} + export function pgType(t: SqlType): string { switch (t.kind) { case "text": return t.maxLength !== undefined ? `VARCHAR(${t.maxLength})` : "TEXT"; diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts index 9290fa2681..3ac4dbec95 100644 --- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts +++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts @@ -47,7 +47,7 @@ const STAGE_ORDER: Record = { "drop-index": 1.5, "add-column": 2, "drop-column": 2, "change-column-type": 2, "change-column-nullable": 2, "change-column-default": 2, - "change-column-identity": 2, "change-comment": 2, + "change-column-identity": 2, "change-comment": 2, "alter-sequence": 2, "rename-column": 3, "add-index": 4, "add-fk": 5, @@ -415,7 +415,8 @@ function renderUpNative(c: Change): string { throw new Error(`renderUpNative: ${c.kind} should have been handled by recreate bundler`); case "change-column-identity": case "change-comment": - // Planned only on the Postgres shadow path; SQLite has neither GENERATED identity nor COMMENT. + case "alter-sequence": + // Planned only on Postgres; SQLite has no GENERATED identity, COMMENT or sequence. throw new Error(`renderUpNative: ${c.kind} is a Postgres-only change`); // SQLite has no schema namespacing for views and no CREATE OR REPLACE VIEW; // a replace is DROP + CREATE. The view body lives in ViewDescriptor.sql. @@ -465,7 +466,8 @@ function renderDownNative(c: Change): string { throw new Error(`renderDownNative: ${c.kind} should have been handled by recreate bundler`); case "change-column-identity": case "change-comment": - // Planned only on the Postgres shadow path; SQLite has neither GENERATED identity nor COMMENT. + case "alter-sequence": + // Planned only on Postgres; SQLite has no GENERATED identity, COMMENT or sequence. throw new Error(`renderDownNative: ${c.kind} is a Postgres-only change`); case "create-view": return `DROP VIEW IF EXISTS ${quote(c.view.name)};`; // The view as the DB held it (`restore`) is a valid restore payload: a view dropped diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index ce1ca37afe..eb768ad76d 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -116,6 +116,7 @@ function changeLocator(c: Change): string { case "change-column-nullable": case "change-column-default": case "change-column-identity": + case "alter-sequence": return `${c.table}.${"column" in c ? c.column : c.from}`; case "change-comment": return c.column !== undefined ? `${c.table}.${c.column}` : c.table; diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index ba1dc951ba..86c5bc0c51 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -62,6 +62,8 @@ import { applyColumnNamingStrategy, physicalNamingOf, resolveTableName, resolveColumnName, resolveFlattenedColumnPrefix, resolveTableSchema, resolveIndexName, resolveEnumMaxLength, + IDENTITY_ATTR_SEQUENCE_NAME, + IDENTITY_ATTR_SEQUENCE_START, } from "@metaobjectsdev/metadata"; import type { SqlType } from "./sql-type.js"; import type { @@ -582,7 +584,9 @@ function buildTable( // The parent field.object itself does NOT produce its own column. columns.push(...flattenObjectField(field, strategy)); } else { - columns.push(buildColumn(field, isPk, isPk ? pkGeneration : undefined, strategy)); + const col = buildColumn(field, isPk, isPk ? pkGeneration : undefined, strategy); + if (isPk && pkGeneration === "increment" && pkIdentity !== undefined) applyDeclaredSequence(col, pkIdentity); + columns.push(col); } } @@ -1238,6 +1242,21 @@ const EXPR_DEFAULT_PATTERNS = [ /\(\)/, // anything function-like ]; +/** + * The declared start and name of an increment key's sequence (identity.primary + * @sequenceStart / @sequenceName; ADR-0039: resolving). Only what is declared is set, so only + * that is compared against a live sequence. + */ +function applyDeclaredSequence(col: ColumnDescriptor, pkIdentity: MetaData): void { + const start = pkIdentity.attr(IDENTITY_ATTR_SEQUENCE_START); + const name = pkIdentity.attr(IDENTITY_ATTR_SEQUENCE_NAME); + if (typeof start !== "number" && typeof name !== "string") return; + col.sequence = { + ...(typeof name === "string" ? { name } : {}), + ...(typeof start === "number" ? { start } : {}), + }; +} + function buildColumn( field: MetaData, isPk: boolean, @@ -1303,7 +1322,6 @@ function buildColumn( if (isPk && (pkGeneration === "increment" || pkGeneration === "uuid")) { col.identity = pkGeneration; } - const fieldDesc = readDescription(field); if (fieldDesc !== undefined) col.description = fieldDesc; diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index 0ff0c20d7d..2c4807eeef 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -52,6 +52,7 @@ export async function introspectPostgres(db: Kysely>): P const columns = await readColumns(k, schema, name); const { columns: primaryKey, name: primaryKeyName } = await readPrimaryKey(k, schema, name); const description = await readPgCatalogColumnFacts(k, schema, name, columns); + await readPgColumnSequences(k, schema, name, columns); tables.push({ name, schema, @@ -532,6 +533,42 @@ async function readPgCatalogColumnFacts( } } +/** + * The sequence behind each auto-increment column — a GENERATED identity's or a legacy + * serial's — found through `pg_depend` (the column OWNS it), with its name and start value + * from `pg_sequence`. Sets `sequence` on `columns` in place. Compared only against what the + * model declares (identity.primary @sequenceStart / @sequenceName). + */ +async function readPgColumnSequences( + k: RawKysely, schema: string, tableName: string, columns: ColumnDescriptor[], +): Promise { + // pg-mem gap: pg_depend / pg_sequence are not supported — the query throws and the + // columns carry no sequence, so nothing about one is compared. + try { + const rows = await sql<{ column_name: string; sequence_name: string; seqstart: string | number }>` + SELECT a.attname AS column_name, seq.relname AS sequence_name, ps.seqstart + FROM pg_class c + JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped + JOIN pg_depend d ON d.refobjid = c.oid AND d.refobjsubid = a.attnum + AND d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass + AND d.deptype IN ('a', 'i') + JOIN pg_class seq ON seq.oid = d.objid AND seq.relkind = 'S' + JOIN pg_sequence ps ON ps.seqrelid = seq.oid + WHERE n.nspname = ${schema} + AND c.relname = ${tableName} + `.execute(k); + const byName = new Map(columns.map((c) => [c.name, c] as const)); + for (const r of rows.rows) { + const col = byName.get(r.column_name); + if (col === undefined) continue; + col.sequence = { name: r.sequence_name, start: Number(r.seqstart) }; + } + } catch { + // see above + } +} + // Typed alias for raw Kysely — avoids per-call `as any` casts in the helpers below. // eslint-disable-next-line @typescript-eslint/no-explicit-any type RawKysely = Kysely; diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts index 36954922d7..96797a2e01 100644 --- a/server/typescript/packages/migrate-ts/src/types.ts +++ b/server/typescript/packages/migrate-ts/src/types.ts @@ -67,6 +67,13 @@ export interface ColumnDescriptor { udtName?: string; default?: ColumnDefault; identity?: "increment" | "uuid"; + /** + * The sequence an `increment` identity draws from. Expected side: only what the + * identity.primary DECLARES (`@sequenceStart` → `start`, `@sequenceName` → `name`), and only + * those are compared, so an undeclared start or name never produces a change. Postgres live + * side: the sequence's actual name and start. Absent on SQLite, which has no sequences. + */ + sequence?: { name?: string; start?: number }; /** * Human-readable description threaded from field `@description`. * Postgres: emitted as `COMMENT ON COLUMN … IS '…';` after CREATE TABLE or ADD COLUMN. @@ -303,6 +310,13 @@ export type Change = /** Postgres, shadow path only: an `increment` identity (`GENERATED BY DEFAULT AS IDENTITY`) added or dropped. */ | { kind: "change-column-identity"; table: string; schema?: string; column: string; from?: "increment"; to?: "increment"; status: ChangeStatus } + /** + * Postgres: an increment identity's sequence whose declared start or name differs from the + * live one, altered in place (`ALTER SEQUENCE … START WITH` / `RENAME TO`). `sequence` is the + * live name the change addresses; each pair is set only when it differs. + */ + | { kind: "alter-sequence"; table: string; schema?: string; column: string; sequence: string; + fromStart?: number; toStart?: number; toName?: string; status: ChangeStatus } /** * Postgres, shadow path only: a table comment (no `column`) or column comment set, changed or * cleared. Clearing one the model does not declare is gated behind `allow.dropComment`. diff --git a/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts b/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts new file mode 100644 index 0000000000..0660bca359 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts @@ -0,0 +1,84 @@ +/** + * identity.primary @sequenceStart / @sequenceName: the sequence an @generation "increment" + * key draws from. Postgres creates it with GENERATED BY DEFAULT AS IDENTITY + * (SEQUENCE NAME … START WITH …); a live sequence whose declared start or name differs is + * altered in place (ALTER SEQUENCE … START WITH / RENAME TO), never dropped. Only what the + * model DECLARES is compared, so a database whose sequence kept an old name after a table + * rename sees no new change until the model names it. SQLite has no sequences to name. + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { diff } from "../../src/diff/index.js"; +import { emit } from "../../src/emit/index.js"; +import type { SchemaSnapshot as DatabaseSchema } from "../../src/types.js"; + +async function schema(pk: Record) { + const doc = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": { "@table": "Ticket" } }, + { "field.int": { name: "id", "@column": "Id" } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment", ...pk } }, + ] } }, + ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toHaveLength(0); + return buildExpectedSchema(root); +} + +const EMPTY = { tables: [], views: [] } as unknown as DatabaseSchema; +const idColumn = (s: DatabaseSchema) => s.tables.find((t) => t.name === "Ticket")!.columns.find((c) => c.name === "Id")!; + +/** The live side: the same table, its sequence as Postgres reports it. */ +function live(expected: DatabaseSchema, sequence: { name: string; start: number }): DatabaseSchema { + const copy = structuredClone(expected); + idColumn(copy).sequence = sequence; + return copy; +} + +describe("identity.primary sequence start and name", () => { + test("the expected column carries only what the model declares", async () => { + expect(idColumn(await schema({ "@sequenceStart": 1000000000, "@sequenceName": "Old_Id_seq" })).sequence) + .toEqual({ start: 1000000000, name: "Old_Id_seq" }); + expect(idColumn(await schema({})).sequence).toBeUndefined(); + }); + + test("Postgres CREATE names the sequence and its start", async () => { + const s = await schema({ "@sequenceStart": 1000000000, "@sequenceName": "Old_Id_seq" }); + const { changes } = await diff(s, EMPTY, { dialect: "postgres" }); + expect(emit(changes, { dialect: "postgres" }).up) + .toContain('"Id" INTEGER GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "Old_Id_seq" START WITH 1000000000)'); + }); + + test("a live sequence with another start and name is altered in place, and the down reverses it", async () => { + const s = await schema({ "@sequenceStart": 1000000000, "@sequenceName": "Old_Id_seq" }); + const { changes } = await diff(s, live(s, { name: "Ticket_Id_seq", start: 1 }), { dialect: "postgres" }); + expect(changes.filter((c) => c.kind === "alter-sequence")).toHaveLength(1); + const { up, down } = emit(changes, { dialect: "postgres" }); + expect(up).toContain('ALTER SEQUENCE "Ticket_Id_seq" START WITH 1000000000;'); + expect(up).toContain('ALTER SEQUENCE "Ticket_Id_seq" RENAME TO "Old_Id_seq";'); + expect(down).toContain('ALTER SEQUENCE "Old_Id_seq" RENAME TO "Ticket_Id_seq";'); + expect(down).toContain('ALTER SEQUENCE "Ticket_Id_seq" START WITH 1;'); + expect(up).not.toMatch(/DROP|IDENTITY/); + }); + + test("a live sequence matching the declaration is no change", async () => { + const s = await schema({ "@sequenceStart": 1000000000, "@sequenceName": "Old_Id_seq" }); + const { changes } = await diff(s, live(s, { name: "Old_Id_seq", start: 1000000000 }), { dialect: "postgres" }); + expect(changes.filter((c) => c.kind === "alter-sequence")).toEqual([]); + }); + + test("undeclared start and name are not compared, whatever the live sequence says", async () => { + const s = await schema({}); + const { changes } = await diff(s, live(s, { name: "Renamed_Id_seq", start: 500 }), { dialect: "postgres" }); + expect(changes.filter((c) => c.kind === "alter-sequence")).toEqual([]); + }); + + test("SQLite has no sequence to name: no clause, no change", async () => { + const s = await schema({ "@sequenceStart": 1000000000, "@sequenceName": "Old_Id_seq" }); + const { changes } = await diff(s, EMPTY, { dialect: "sqlite" }); + const { up } = emit(changes, { dialect: "sqlite" }); + expect(up).not.toContain("SEQUENCE"); + expect(up).not.toContain("1000000000"); + }); +}); diff --git a/site-reference/providers.html b/site-reference/providers.html index 7ff136f6e7..325916464e 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -112,6 +112,7 @@

    metaobjects-db

  • field.timestamp: @autoSet, @column, @db.indexed, @dbColumnType, @localTime
  • field.uri: @column, @db.indexed, @dbColumnType
  • field.uuid: @column, @db.indexed, @dbColumnType
  • +
  • identity.primary: @sequenceName, @sequenceStart
  • identity.reference: @constraintName, @onDelete, @onUpdate
  • identity.secondary: @expr, @orders, @using, @where
  • index.lookup: @expr, @orders, @using, @where
  • diff --git a/site-reference/types/identity.html b/site-reference/types/identity.html index 7f0fd6698c..3c09433e84 100644 --- a/site-reference/types/identity.html +++ b/site-reference/types/identity.html @@ -85,6 +85,24 @@

    identity.primary

    + + + + + + + +
    metaobjects-core-types Primary-key value generation strategy: 'increment' (auto-increment), 'uuid', or 'assigned' (caller-supplied).
    @sequenceNamestringnometaobjects-dbThe physical name of an @generation "increment" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default, __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation "increment" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider. + + + + + + + + + +
    @sequenceStartlongnometaobjects-dbThe first value an @generation "increment" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation "increment" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider.

    Allowed children

    No structural children.

    diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index 50b3584845..79734985ba 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -59,6 +59,14 @@ { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } ] }, + { + "type": "identity", + "subType": "primary", + "children": [ + { "type": "attr", "subType": "long", "name": "sequenceStart", "min": 0, "max": 1, "description": "The first value an @generation \"increment\" key's sequence hands out (Postgres: GENERATED BY DEFAULT AS IDENTITY (START WITH n)). Absent: 1. Lets a model reproduce a table that keeps a low id range for seeded rows. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "string", "name": "sequenceName", "min": 0, "max": 1, "description": "The physical name of an @generation \"increment\" key's sequence (Postgres: GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME ...)). Absent: the database's own default, __seq on Postgres. Lets a model adopt a sequence that kept its name across a table rename. Refused without @generation \"increment\" (ERR_SEQUENCE_WITHOUT_INCREMENT). RDB-physical — contributed by the db provider." } + ] + }, { "type": "identity", "subType": "reference", From ca14f61d578967ee53bd6e0e1dec378703def23f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 09:28:59 -0500 Subject: [PATCH 019/267] fix(identity): sequences compare only what the model declares, on every path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for @sequenceStart / @sequenceName: - The live sequence is its own field (liveSequence), read only by the diff: never emitted, never written to a snapshot. The shadow path re-applies the model's declared sequence onto the shadow's read of each table and drops the shadow's own, so a model that declares nothing writes the same SQL, snapshots and verify results as before (a renamed table's sequence, a non-default start, a new table whose default name another relation holds) — proved on a real Postgres through the CLI. - A new start moves the counter: ALTER SEQUENCE ... START WITH n is followed by setval(..., n, false) when the counter has not reached n, never moving it down; the down restores the old start and leaves the counter. - The offline diff (committed snapshot) compares a changed declaration, addressing the sequence by what the snapshot recorded or Postgres's default name. - Adding an identity to an existing column carries the declared options. - Load: a @sequenceStart below 1 or past the key's range (2147483647 for field.int) is refused in every port (ERR_SEQUENCE_START_OUT_OF_RANGE); a declared name two tables generate is a duplicate database name (ERR_DUPLICATE_SQL_NAME), with advice. - Introspection records the sequence's own schema. - Docs, CHANGELOG, a new conformance fixture and an env-gated Postgres CLI test. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 13 +- docs/CONFORMANCE.md | 6 +- docs/features/migrations-and-drift.md | 29 ++-- examples/showcase/site-payload.json | 2 +- fixtures/conformance/ERROR-CODES.json | 1 + .../expected-errors.json | 25 ++++ .../input/meta.seq.json | 53 +++++++ scripts/check-doc-examples.ts | 1 + server/csharp/MetaObjects/Errors.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 29 +++- .../main/java/com/metaobjects/ErrorCode.java | 1 + .../metaobjects/loader/ValidationPhase.java | 30 +++- .../util/ErrorMessageConstants.java | 6 + server/python/src/metaobjects/errors.py | 1 + .../metaobjects/loader/validation_passes.py | 27 +++- .../integration/identity-sequence-pg.test.ts | 129 ++++++++++++++++++ .../packages/metadata/src/errors.ts | 2 + .../metadata/src/loader/validation-passes.ts | 24 +++- .../packages/migrate-ts/src/diff/index.ts | 36 +++-- .../packages/migrate-ts/src/emit/postgres.ts | 40 ++++-- .../packages/migrate-ts/src/errors.ts | 7 + .../migrate-ts/src/expected-schema.ts | 10 ++ .../migrate-ts/src/introspect/postgres.ts | 15 +- .../migrate-ts/src/shadow-expected.ts | 24 +++- .../migrate-ts/src/snapshot/serialize.ts | 19 ++- .../packages/migrate-ts/src/types.ts | 22 ++- .../test/unit/identity-sequence.test.ts | 73 +++++++++- 28 files changed, 570 insertions(+), 59 deletions(-) create mode 100644 fixtures/conformance/error-identity-sequence-start-out-of-range/expected-errors.json create mode 100644 fixtures/conformance/error-identity-sequence-start-out-of-range/input/meta.seq.json create mode 100644 server/typescript/packages/cli/test/integration/identity-sequence-pg.test.ts diff --git a/AGENTS.md b/AGENTS.md index 1d92921c0d..4a2a388fbc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (429 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (430 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a1da07cd7..20da900914 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,11 +47,14 @@ here.** table that keeps a low id range for seeded rows, or adopt a sequence that kept its name across a table rename. On Postgres `meta migrate` creates `GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "…" START WITH n)`, reads the live sequence - back from the catalog, and alters one whose declared start or name differs in place - (`ALTER SEQUENCE … START WITH` / `RENAME TO`); only what the model declares is compared, so - existing databases see no new change. Every port registers both attributes and refuses either - without `@generation: increment` (`ERR_SEQUENCE_WITHOUT_INCREMENT`). See - `docs/features/migrations-and-drift.md`. + back from the catalog, and alters one whose declared start or name differs in place: a new + start is set and the counter moved up to it (never down), a new name is a rename. Only what + the model declares is compared, on the live, shadow and snapshot paths alike, so a model that + declares neither sees no new change and writes the same SQL and snapshots. Every port + registers both attributes and refuses either without `@generation: increment` + (`ERR_SEQUENCE_WITHOUT_INCREMENT`) and a start below 1 or past the key's range + (`ERR_SEQUENCE_START_OUT_OF_RANGE`); a name two tables declare is refused as a duplicate + database name. See `docs/features/migrations-and-drift.md`. - **A string-stored enum's column length: `@maxLength` on `field.enum`, and `enums.maxLength`.** `@maxLength` on a `field.enum` makes its column `VARCHAR(n)`, and `"enums": { "maxLength": n }` in `.metaobjects/config.json` gives every enum without one a default; with neither, the column diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 023d89bbc7..022c7d60bd 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 429 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 430 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -286,7 +286,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (429) +### `fixtures/conformance/` — metamodel loader + canonical serializer (430) | Fixture prefix | Feature doc | |---|---| @@ -612,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 429 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 430 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 624a5e0491..91433bd7be 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -299,14 +299,27 @@ An `@generation: increment` key draws from a sequence. Two attributes on the table was renamed. On Postgres `meta migrate` creates the column as -`GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "…" START WITH n)`, and `meta verify --db` -reads the live sequence back from the catalog. A live sequence whose start or name differs -from the declaration is altered in place (`ALTER SEQUENCE … START WITH n`, -`ALTER SEQUENCE … RENAME TO …`), never dropped, and the down migration reverses it. Only what -the model declares is compared: a database whose sequence kept an old name sees no change -until the model names it. SQLite and D1 have no sequences to name, so both attributes change -nothing there. Either attribute without `@generation: increment` is refused at load -(`ERR_SEQUENCE_WITHOUT_INCREMENT`). +`GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "…" START WITH n)` (and adds an identity to an +existing column with the same options), and `meta verify --db` reads the live sequence back +from the catalog. A live sequence whose start or name differs from the declaration is altered +in place, never dropped: + +- a different start sets it (`ALTER SEQUENCE … START WITH n`) and moves the counter up to it + when it has not got there (`setval(…, n, false)`), so the next insert takes the declared + start. It never moves the counter down, which could hand out an id already in use; the down + migration restores the old start value and leaves the counter where it is. +- a different name renames it (`ALTER SEQUENCE … RENAME TO …`); the down renames it back. + +Only what the model declares is compared, on every path (a live database, a shadow database, +a committed snapshot): a database whose sequence kept an old name or a non-default start sees +no change until the model names it, and a model that declares neither writes the same SQL and +snapshots it always did. SQLite and D1 have no sequences to name, so both attributes change +nothing there. At load, either attribute without `@generation: increment` is refused +(`ERR_SEQUENCE_WITHOUT_INCREMENT`), and so is a `@sequenceStart` below 1 or past what the key +can hold, 2147483647 for a `field.int` (`ERR_SEQUENCE_START_OUT_OF_RANGE`). A declared name +shares the namespace of tables, views and indexes, so two tables declaring one (an abstract +base's identity extended twice, say) is refused when the schema is built +(`ERR_DUPLICATE_SQL_NAME`). ### Java diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 64d932cbb5..04ce69cce6 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 429, + "fixtures": 430, "corpora": 36, "baseTypes": 17 }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 344aa26335..bb6c1b99ee 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -53,6 +53,7 @@ "ERR_TEMPLATE_ENGINE_UNSUPPORTED": "Build-time verify and render (ADR-0061): a template body is written for an engine this port does not ship — a Jinja body (.jinja / .j2 / .jinja2) in the Java, Kotlin or C# port, which render Mustache only. path = the template ref.", "ERR_BAD_ATTR_FILTER": "An attr.filter references a field that is not addressable in that context or uses a disallowed op: a dataGrid @filter over a non-filterable field or an op disallowed for the field's subtype, or a projection row-scope @filter over a non-declared (dangling) or aggregate-derived field (#207). FR-044: a segment / measure.aggregate / object.report @filter names a field its entity (or @from) lacks or an op illegal for the field (S1); a relative-date value { \"now\": \"\" } appears outside the @filter of a segment, measure.aggregate or object.report (F1); or a relative-date value sits on a field that is not field.date/field.timestamp, under an op other than gt/gte/lt/lte, carries a value that is not an ISO-8601 duration, or has a startOf other than day, week or month, or a key besides now and startOf (F2).", "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", + "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", diff --git a/fixtures/conformance/error-identity-sequence-start-out-of-range/expected-errors.json b/fixtures/conformance/error-identity-sequence-start-out-of-range/expected-errors.json new file mode 100644 index 0000000000..6479c9d69c --- /dev/null +++ b/fixtures/conformance/error-identity-sequence-start-out-of-range/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_SEQUENCE_START_OUT_OF_RANGE", + "source": { + "format": "json", + "files": [ + "meta.seq.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['identity.primary']" + } + }, + { + "code": "ERR_SEQUENCE_START_OUT_OF_RANGE", + "source": { + "format": "json", + "files": [ + "meta.seq.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[2]['identity.primary']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-identity-sequence-start-out-of-range/input/meta.seq.json b/fixtures/conformance/error-identity-sequence-start-out-of-range/input/meta.seq.json new file mode 100644 index 0000000000..276ebac20b --- /dev/null +++ b/fixtures/conformance/error-identity-sequence-start-out-of-range/input/meta.seq.json @@ -0,0 +1,53 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Small", + "children": [ + { + "source.rdb": {} + }, + { + "field.int": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "increment", + "@sequenceStart": 3000000000 + } + } + ] + } + }, + { + "object.entity": { + "name": "Zero", + "children": [ + { + "source.rdb": {} + }, + { + "field.long": { + "name": "id" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "increment", + "@sequenceStart": 0 + } + } + ] + } + } + ] + } +} diff --git a/scripts/check-doc-examples.ts b/scripts/check-doc-examples.ts index 6f1a7e6c3d..16abb99a40 100644 --- a/scripts/check-doc-examples.ts +++ b/scripts/check-doc-examples.ts @@ -158,6 +158,7 @@ const FAIL_CODES = new Set([ "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", "ERR_SEQUENCE_WITHOUT_INCREMENT", + "ERR_SEQUENCE_START_OUT_OF_RANGE", "ERR_PHYSICAL_NAME_KIND_MISMATCH", "ERR_PHYSICAL_NAME_MULTIPLE", "ERR_SQL_BODY_ON_WRITABLE_KIND", diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 8855dccd38..57d361fc28 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -312,6 +312,8 @@ public enum ErrorCode ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, // identity.primary @sequenceStart / @sequenceName without @generation "increment". ERR_SEQUENCE_WITHOUT_INCREMENT, + // identity.primary @sequenceStart below 1, or past what its key field can hold. + ERR_SEQUENCE_START_OUT_OF_RANGE, } /// diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index fd509af5b7..51a575382c 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2116,7 +2116,34 @@ public static IReadOnlyList ValidateIdentitySequence(MetaData root) var declared = new[] { MetaObjects.Persistence.Db.DbConstants.IDENTITY_ATTR_SEQUENCE_START, MetaObjects.Persistence.Db.DbConstants.IDENTITY_ATTR_SEQUENCE_NAME } .Where(a => id.OwnAttr(a) is not null).ToList(); var generation = id.Attr(IDENTITY_ATTR_GENERATION) as string; - if (declared.Count == 0 || generation == GENERATION_INCREMENT) continue; + if (declared.Count == 0) continue; + if (generation == GENERATION_INCREMENT) + { + // The key field's own range bounds the start (Postgres refuses the sequence + // otherwise, at apply time): 1 to the largest value of a field.int / field.long. + if (id.Attr(MetaObjects.Persistence.Db.DbConstants.IDENTITY_ATTR_SEQUENCE_START) is long start) + { + var keyName = id.Attr(IDENTITY_ATTR_FIELDS) switch + { + string s => s, + IReadOnlyList ss => ss.FirstOrDefault(), + IReadOnlyList os => os.FirstOrDefault() as string, + _ => null, + }; + var key = (obj as MetaObject)?.Fields().FirstOrDefault(f => f.Name == keyName); + long? max = key?.SubType == FIELD_SUBTYPE_INT ? int.MaxValue : null; + if (start < 1 || (max is { } m && start > m)) + { + errors.Add(new MetaError( + $"identity.primary \"{obj.Name}.{id.Name}\" @sequenceStart {start} is out of range for its key " + + $"\"{keyName}\"{(key is not null ? $" (field.{key.SubType})" : "")}: it must be at least 1" + + $"{(max is { } mx ? $" and at most {mx}" : "")}.", + ErrorCode.ERR_SEQUENCE_START_OUT_OF_RANGE, + Envelope: id.Source)); + } + } + continue; + } var shown = generation is null ? "not set" : $"\"{generation}\""; var names = string.Join(" and ", declared.Select(a => "@" + a)); errors.Add(new MetaError( diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 9eb36dee52..1e446cf04a 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -298,6 +298,7 @@ public enum ErrorCode { ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, ERR_SEQUENCE_WITHOUT_INCREMENT, + ERR_SEQUENCE_START_OUT_OF_RANGE, /** @storage was set on a field that has no @objectRef. */ ERR_STORAGE_WITHOUT_OBJECT_REF, diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index a1c0724343..fe9f80fa28 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -2399,8 +2399,34 @@ static void validateIdentitySequence(MetaRoot root, List out) } String generation = id.hasMetaAttr(com.metaobjects.identity.MetaIdentity.ATTR_GENERATION) ? id.getMetaAttr(com.metaobjects.identity.MetaIdentity.ATTR_GENERATION).getValueAsString() : null; - if (declared.isEmpty() - || com.metaobjects.identity.MetaIdentity.GENERATION_INCREMENT.equals(generation)) continue; + if (declared.isEmpty()) continue; + if (com.metaobjects.identity.MetaIdentity.GENERATION_INCREMENT.equals(generation)) { + // The key field's own range bounds the start (Postgres refuses the sequence + // otherwise, at apply time): 1 to the largest value of a field.int / field.long. + if (id.hasMetaAttr(com.metaobjects.identity.PrimaryIdentity.ATTR_SEQUENCE_START)) { + Object raw = id.getMetaAttr(com.metaobjects.identity.PrimaryIdentity.ATTR_SEQUENCE_START).getValue(); + if (raw instanceof Number n) { + long start = n.longValue(); + List keys = id.getFields(); + String keyName = keys.isEmpty() ? null : keys.get(0); + com.metaobjects.field.MetaField key = null; + for (com.metaobjects.field.MetaField f : obj.getMetaFields()) { + if (f.getShortName().equals(keyName)) { key = f; break; } + } + Long max = key instanceof com.metaobjects.field.IntegerField ? (long) Integer.MAX_VALUE : null; + if (start < 1 || (max != null && start > max)) { + out.add(new MetaDataException( + ErrorMessageConstants.ERR_SEQUENCE_START_OUT_OF_RANGE + + ": identity.primary \"" + obj.getShortName() + "." + id.getShortName() + + "\" @sequenceStart " + start + " is out of range for its key \"" + keyName + "\"" + + (key != null ? " (field." + key.getSubType() + ")" : "") + + ": it must be at least 1" + (max != null ? " and at most " + max : "") + ".", + ErrorCode.ERR_SEQUENCE_START_OUT_OF_RANGE, id.getSource())); + } + } + } + continue; + } String shown = generation == null ? "not set" : "\"" + generation + "\""; String names = String.join(" and ", declared); out.add(new MetaDataException( diff --git a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java index 624ec24607..ca76773a5a 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java +++ b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java @@ -198,6 +198,12 @@ private ErrorMessageConstants() { */ public static final String ERR_SEQUENCE_WITHOUT_INCREMENT = "ERR_SEQUENCE_WITHOUT_INCREMENT"; + /** + * An {@code identity.primary} {@code @sequenceStart} is below 1, or past the largest value its + * key field can hold. Cross-language contract: {@code ERR_SEQUENCE_START_OUT_OF_RANGE}. + */ + public static final String ERR_SEQUENCE_START_OUT_OF_RANGE = "ERR_SEQUENCE_START_OUT_OF_RANGE"; + /** * Error code emitted when {@code field.object @storage} is set on a field that * has no {@code @objectRef} — storage shape only applies to referenced objects. diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index 3a7c655dd1..c14d77e0aa 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -208,6 +208,7 @@ class ErrorCode(str, Enum): ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH = "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP" ERR_SEQUENCE_WITHOUT_INCREMENT = "ERR_SEQUENCE_WITHOUT_INCREMENT" + ERR_SEQUENCE_START_OUT_OF_RANGE = "ERR_SEQUENCE_START_OUT_OF_RANGE" ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE = ( "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE" ) diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index a88cb58f86..3353d3d429 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -3726,6 +3726,10 @@ def _validate_sortable_has_supported_subtype( # "increment" key draws from; on any other generation there is none, so either one is refused # (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the identity that # declares one of them. Mirrors TS validateIdentitySequence. +#: The largest value a field.int key (a 32-bit integer column) can hold. +_SEQUENCE_INT_MAX = 2147483647 + + def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None: from ..meta.core.identity.identity_constants import ( GENERATION_INCREMENT, @@ -3749,7 +3753,28 @@ def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None if ident.attr(a) is not None ] generation = ident.get_meta_attr(IDENTITY_ATTR_GENERATION) - if not declared or generation == GENERATION_INCREMENT: + if not declared: + continue + if generation == GENERATION_INCREMENT: + # The key field's own range bounds the start (Postgres refuses the sequence + # otherwise, at apply time): 1 to the largest value of a field.int / field.long. + start = ident.get_meta_attr(IDENTITY_PRIMARY_ATTR_SEQUENCE_START) + if isinstance(start, int) and not isinstance(start, bool): + fields = ident.get_meta_attr(IDENTITY_ATTR_FIELDS) + key_name = fields[0] if isinstance(fields, list) and fields else fields + key = next((f for f in obj.fields() if f.name == key_name), None) + maximum = _SEQUENCE_INT_MAX if key is not None and key.sub_type == FIELD_SUBTYPE_INT else None + if start < 1 or (maximum is not None and start > maximum): + kind = f" (field.{key.sub_type})" if key is not None else "" + upper = f" and at most {maximum}" if maximum is not None else "" + errors.append(MetaError( + code=ErrorCode.ERR_SEQUENCE_START_OUT_OF_RANGE, + message=( + f'identity.primary "{obj.name}.{ident.name}" @sequenceStart {start} is out ' + f'of range for its key "{key_name}"{kind}: it must be at least 1{upper}.' + ), + envelope=ident.source, + )) continue shown = f'"{generation}"' if isinstance(generation, str) else "not set" names = " and ".join(declared) diff --git a/server/typescript/packages/cli/test/integration/identity-sequence-pg.test.ts b/server/typescript/packages/cli/test/integration/identity-sequence-pg.test.ts new file mode 100644 index 0000000000..2ac6839e20 --- /dev/null +++ b/server/typescript/packages/cli/test/integration/identity-sequence-pg.test.ts @@ -0,0 +1,129 @@ +/** + * identity.primary @sequenceStart / @sequenceName through the CLI against a real Postgres, on + * the shadow path `meta verify --db` and `meta migrate --from-db` take by default (env-gated on + * MIGRATE_TS_PG_URL; a throwaway database per test). + * + * - A model that declares NO sequence sees no change from one: a live sequence left behind by + * a table rename, with a non-default start, verifies clean and plans nothing, and a fresh + * CREATE stays plain `GENERATED BY DEFAULT AS IDENTITY`. + * - A declared start and name that differ from the live sequence are altered in place, and the + * counter really moves: the next insert takes the declared start. + */ +import { describe, test, expect } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import pg from "pg"; +import { run } from "../../src/index.js"; + +const PG_URL = process.env.MIGRATE_TS_PG_URL; + +function model(pk: Record): string { + return JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": { "@table": "Ticket" } }, + { "field.int": { name: "id", "@column": "Id" } }, + { "field.string": { name: "label", "@column": "Label" } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment", ...pk } }, + ] } }, + ] } }); +} + +async function withDatabase(fn: (url: string, client: pg.Client) => Promise): Promise { + const admin = new pg.Client({ connectionString: PG_URL }); + await admin.connect(); + const db = `mt_seq_${Date.now()}_${Math.floor(Math.random() * 1e6)}`; + await admin.query(`CREATE DATABASE ${db}`); + const url = new URL(PG_URL!); + url.pathname = `/${db}`; + const client = new pg.Client({ connectionString: url.toString() }); + await client.connect(); + try { + await fn(url.toString(), client); + } finally { + await client.end(); + await admin.query(`DROP DATABASE IF EXISTS ${db} WITH (FORCE)`); + await admin.end(); + } +} + +function project(pk: Record): string { + const root = mkdtempSync(join(tmpdir(), "identity-sequence-pg-")); + mkdirSync(join(root, "metaobjects"), { recursive: true }); + mkdirSync(join(root, ".metaobjects", "migrations"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.acme.json"), model(pk), "utf8"); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, migrate: { dialect: "postgres" } }), "utf8"); + return root; +} + +async function captured(argv: string[]): Promise<{ exit: number; out: string }> { + const lines: string[] = []; + const keep = (...a: unknown[]): void => { lines.push(a.map(String).join(" ")); }; + const orig = [console.log, console.error, console.warn] as const; + console.log = keep; console.error = keep; console.warn = keep; + try { + return { exit: await run(argv), out: lines.join("\n") }; + } finally { + [console.log, console.error, console.warn] = orig; + } +} + +describe("identity.primary sequence on a real Postgres (env-gated)", () => { + if (PG_URL === undefined || PG_URL.length === 0) { + test.skip("skipped — MIGRATE_TS_PG_URL not set", () => {}); + return; + } + + test("a model that declares no sequence: a renamed table's live sequence verifies clean and plans nothing", async () => { + await withDatabase(async (url, client) => { + await client.query(`CREATE TABLE "OldTicket" ("Id" integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1000) PRIMARY KEY, "Label" text)`); + await client.query(`ALTER TABLE "OldTicket" RENAME TO "Ticket"`); + const root = project({}); + try { + const verify = await captured(["verify", "--cwd", root, "--db", url]); + expect(verify.out).not.toContain("alter-sequence"); + expect(verify.exit).toBe(0); + const plan = await captured(["migrate", "--cwd", root, "--db", url, "--from-db", "--dry-run"]); + expect(plan.out).not.toContain("SEQUENCE"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + }); + + test("a model that declares no sequence: a fresh CREATE is plain IDENTITY", async () => { + await withDatabase(async (url) => { + const root = project({}); + try { + const plan = await captured(["migrate", "--cwd", root, "--db", url, "--from-db", "--dry-run"]); + expect(plan.out).toContain("GENERATED BY DEFAULT AS IDENTITY"); + expect(plan.out).not.toContain("SEQUENCE NAME"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + }); + + test("a declared start and name that differ are altered in place, and the next insert takes the start", async () => { + await withDatabase(async (url, client) => { + await client.query(`CREATE TABLE "Ticket" ("Id" integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "Label" text)`); + await client.query(`INSERT INTO "Ticket" ("Label") VALUES ('seeded')`); + const root = project({ "@sequenceStart": 1000000000, "@sequenceName": "Legacy_Id_seq" }); + try { + const drift = await captured(["verify", "--cwd", root, "--db", url]); + expect(drift.exit).toBe(1); + expect(drift.out).toContain("alter-sequence"); + const applied = await captured(["migrate", "--cwd", root, "--db", url, "--from-db", "--slug", "seq", "--apply"]); + expect(applied.exit).toBe(0); + const { rows } = await client.query(`INSERT INTO "Ticket" ("Label") VALUES ('next') RETURNING "Id"`); + expect(Number(rows[0].Id)).toBe(1000000000); + const seq = await client.query(`SELECT pg_get_serial_sequence('"Ticket"', 'Id') AS s`); + expect(seq.rows[0].s).toBe('public."Legacy_Id_seq"'); + const clean = await captured(["verify", "--cwd", root, "--db", url]); + expect(clean.exit).toBe(0); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + }); +}); diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index dd7e708c39..448fb320f0 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -156,6 +156,8 @@ export const ERROR_CODES = [ "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP", // identity.primary @sequenceStart / @sequenceName without @generation "increment". "ERR_SEQUENCE_WITHOUT_INCREMENT", + // identity.primary @sequenceStart below 1, or past what its key field can hold. + "ERR_SEQUENCE_START_OUT_OF_RANGE", "ERR_STORAGE_WITHOUT_OBJECT_REF", // ADR-0013 — a field.object REQUIRES @objectRef (open/untyped JSON uses // the physical @dbColumnType: jsonb escape hatch on field.string instead). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 348b1f511d..5b79984360 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1686,13 +1686,35 @@ export function validateDerivedFieldProvidability(root: MetaData): ParseError[] // (ADR-0039), reported on the identity that declares one of them. // --------------------------------------------------------------------------- +/** The largest value a field.int key (a 32-bit integer column) can hold. */ +const SEQUENCE_INT_MAX = 2147483647; + export function validateIdentitySequence(root: MetaData): ParseError[] { const errors: ParseError[] = []; for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { for (const id of obj.ownChildren()) { if (id.type !== TYPE_IDENTITY || id.subType !== IDENTITY_SUBTYPE_PRIMARY) continue; const declared = [IDENTITY_ATTR_SEQUENCE_START, IDENTITY_ATTR_SEQUENCE_NAME].filter((a) => id.ownAttr(a) !== undefined); - if (declared.length === 0 || id.attr(IDENTITY_ATTR_GENERATION) === GENERATION_INCREMENT) continue; + if (declared.length === 0) continue; + if (id.attr(IDENTITY_ATTR_GENERATION) === GENERATION_INCREMENT) { + const start = id.attr(IDENTITY_ATTR_SEQUENCE_START); + if (typeof start === "number") { + // The key field's own range bounds the start (Postgres refuses the sequence + // otherwise, at apply time): 1 to the largest value of a field.int / field.long. + const keyName = [id.attr(IDENTITY_ATTR_FIELDS)].flat()[0]; + const key = (obj as MetaObject).fields().find((f) => f.name === keyName); + const max = key?.subType === FIELD_SUBTYPE_INT ? SEQUENCE_INT_MAX : undefined; + if (start < 1 || (max !== undefined && start > max)) { + errors.push(new ParseError( + `identity.primary "${obj.name}.${id.name}" @sequenceStart ${start} is out of range for its key ` + + `"${String(keyName)}"${key !== undefined ? ` (field.${key.subType})` : ""}: it must be at least 1` + + `${max !== undefined ? ` and at most ${max}` : ""}.`, + { code: "ERR_SEQUENCE_START_OUT_OF_RANGE", source: id.source }, + )); + } + } + continue; + } const generation = id.attr(IDENTITY_ATTR_GENERATION); const shown = typeof generation === "string" ? `"${generation}"` : "not set"; errors.push(new ParseError( diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index b4280ef209..bfa876b3c5 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -786,6 +786,16 @@ function sqlTypeEqualsForDialect(a: SqlType, b: SqlType, dialect: Dialect | unde return sqlTypeEquals(canonTypeForDialect(a, dialect), canonTypeForDialect(b, dialect)); } +/** + * The name Postgres gives an identity or serial column's sequence when none is declared: + * `
    __seq`. Undefined past the 63-byte identifier limit, where Postgres + * truncates by its own rule; such a name is then never compared offline. + */ +function defaultSequenceName(table: string, column: string): string | undefined { + const name = `${table}_${column}_seq`; + return Buffer.byteLength(name, "utf8") <= 63 ? name : undefined; +} + function diffTableColumns( expected: TableDescriptor, actual: TableDescriptor, @@ -868,17 +878,22 @@ function diffTableColumns( }; changes.push(change); } - // The declared start and name of an increment key's sequence, against the live sequence - // (Postgres only: SQLite has none, and its introspection reports no `sequence`). Only what - // the model declares is compared, so an undeclared one never produces a change. - if (ec.identity === "increment" && ec.sequence !== undefined && ac.sequence?.name !== undefined) { - const startDiffers = ec.sequence.start !== undefined && ac.sequence.start !== undefined - && ec.sequence.start !== ac.sequence.start; - const nameDiffers = ec.sequence.name !== undefined && ec.sequence.name !== ac.sequence.name; - if (startDiffers || nameDiffers) { + // The declared start and name of an increment key's sequence (Postgres only; SQLite has + // none). Only what the model DECLARES is compared, so an undeclared one never produces a + // change. The other side is the live sequence when introspected (`liveSequence`), else — + // a committed snapshot — what the previous model declared, with Postgres's defaults (start + // 1, `
    __seq`) for what it left undeclared. + if (dialect === "postgres" && ec.identity === "increment" && ac.identity === "increment" && ec.sequence !== undefined) { + const live = ac.liveSequence; + const actualName = live?.name ?? ac.sequence?.name ?? defaultSequenceName(table, name); + const actualStart = live?.start ?? ac.sequence?.start ?? 1; + const startDiffers = ec.sequence.start !== undefined && ec.sequence.start !== actualStart; + const nameDiffers = ec.sequence.name !== undefined && actualName !== undefined && ec.sequence.name !== actualName; + if ((startDiffers || nameDiffers) && actualName !== undefined) { changes.push({ - kind: "alter-sequence", table, ...sx, column: name, sequence: ac.sequence.name, status: ALLOWED, - ...(startDiffers ? { fromStart: ac.sequence.start!, toStart: ec.sequence.start! } : {}), + kind: "alter-sequence", table, ...sx, column: name, sequence: actualName, status: ALLOWED, + ...(live?.schema !== undefined ? { sequenceSchema: live.schema } : {}), + ...(startDiffers ? { fromStart: actualStart, toStart: ec.sequence.start! } : {}), ...(nameDiffers ? { toName: ec.sequence.name! } : {}), }); } @@ -892,6 +907,7 @@ function diffTableColumns( changes.push({ kind: "change-column-identity", table, ...sx, column: name, status: ALLOWED, ...(from !== undefined ? { from } : {}), ...(to !== undefined ? { to } : {}), + ...(to !== undefined && ec.sequence !== undefined ? { sequence: ec.sequence } : {}), }); } if (ec.description !== ac.description) { diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index e32eb44e10..4449c188bf 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -252,8 +252,8 @@ function renderUp(c: Change, recreated: ReadonlySet = new Set()): string return c.to !== undefined ? `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} SET DEFAULT ${renderDefault(c.to)};` : `ALTER TABLE ${quoteQualified(c.table, c.schema)} ALTER COLUMN ${quote(c.column)} DROP DEFAULT;`; - case "change-column-identity": return renderIdentity(c.table, c.schema, c.column, c.to); - case "alter-sequence": return renderAlterSequence(c.schema, c.sequence, c.toStart, c.toName); + case "change-column-identity": return renderIdentity(c.table, c.schema, c.column, c.to, c.sequence); + case "alter-sequence": return renderAlterSequence(c.sequenceSchema ?? c.schema, c.sequence, c.toStart, c.toName); case "change-comment": return renderComment(c.table, c.schema, c.column, c.to); case "add-index": return renderCreateIndex(c.table, c.schema, c.index); // #285: an index OWNED by a UNIQUE / PRIMARY KEY / EXCLUDE constraint cannot be @@ -401,9 +401,10 @@ function renderDown(c: Change, recreated: ReadonlySet = new Set()): stri // The down addresses the sequence by the name the up gave it, and runs in reverse order: // rename back first, then restore the start. case "alter-sequence": + // The counter is not moved back: values it has handed out stay handed out. return [ - ...(c.toName !== undefined ? [`ALTER SEQUENCE ${quoteQualified(c.toName, c.schema)} RENAME TO ${quote(c.sequence)};`] : []), - ...(c.fromStart !== undefined ? [`ALTER SEQUENCE ${quoteQualified(c.sequence, c.schema)} START WITH ${c.fromStart};`] : []), + ...(c.toName !== undefined ? [`ALTER SEQUENCE ${quoteQualified(c.toName, c.sequenceSchema ?? c.schema)} RENAME TO ${quote(c.sequence)};`] : []), + ...(c.fromStart !== undefined ? [`ALTER SEQUENCE ${quoteQualified(c.sequence, c.sequenceSchema ?? c.schema)} START WITH ${c.fromStart};`] : []), ].join("\n"); case "change-comment": return renderComment(c.table, c.schema, c.column, c.from); case "add-index": @@ -487,17 +488,36 @@ function renderTableComments(t: TableDescriptor): string[] { return out; } -/** Start first, under the live name; then the rename. */ +/** + * Start first, under the live name; then the rename. `START WITH` alone only records the + * restart point, so the counter is moved up to the new start — never down, which could hand + * out an id already in use — by `setval(..., false)` when it has not reached it. + */ function renderAlterSequence(schema: string | undefined, sequence: string, toStart: number | undefined, toName: string | undefined): string { + const seq = quoteQualified(sequence, schema); + const regclass = `'${seq.replace(/'/g, "''")}'`; return [ - ...(toStart !== undefined ? [`ALTER SEQUENCE ${quoteQualified(sequence, schema)} START WITH ${toStart};`] : []), - ...(toName !== undefined ? [`ALTER SEQUENCE ${quoteQualified(sequence, schema)} RENAME TO ${quote(toName)};`] : []), + ...(toStart !== undefined + ? [ + `ALTER SEQUENCE ${seq} START WITH ${toStart};`, + `SELECT setval(${regclass}, ${toStart}, false) FROM ${seq} WHERE last_value < ${toStart};`, + ] + : []), + ...(toName !== undefined ? [`ALTER SEQUENCE ${seq} RENAME TO ${quote(toName)};`] : []), ].join("\n"); } -function renderIdentity(table: string, schema: string | undefined, column: string, to: "increment" | undefined): string { +function renderIdentity( + table: string, + schema: string | undefined, + column: string, + to: "increment" | undefined, + sequence?: { name?: string; start?: number }, +): string { const alter = `ALTER TABLE ${quoteQualified(table, schema)} ALTER COLUMN ${quote(column)}`; - return to === "increment" ? `${alter} ADD GENERATED BY DEFAULT AS IDENTITY;` : `${alter} DROP IDENTITY IF EXISTS;`; + return to === "increment" + ? `${alter} ADD GENERATED BY DEFAULT AS IDENTITY${identityOptions(sequence !== undefined ? { sequence } : {})};` + : `${alter} DROP IDENTITY IF EXISTS;`; } function renderComment(table: string, schema: string | undefined, column: string | undefined, to: string | undefined): string { @@ -555,7 +575,7 @@ function renderColumn(c: ColumnDescriptor): string { } /** ` (SEQUENCE NAME "x" START WITH n)` for what the model declares, else nothing. */ -function identityOptions(c: ColumnDescriptor): string { +function identityOptions(c: Pick): string { const opts = [ ...(c.sequence?.name !== undefined ? [`SEQUENCE NAME ${quote(c.sequence.name)}`] : []), ...(c.sequence?.start !== undefined ? [`START WITH ${c.sequence.start}`] : []), diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index eb768ad76d..9dc1d1047c 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -287,6 +287,13 @@ export class DuplicateSqlNameError extends Error { "(e.g. `ownersByEmail`).", ); } + if (collisions.some((c) => c.owners.some((o) => o.includes("@sequenceName")))) { + fixes.push( + "A declared sequence name (identity.primary @sequenceName) is a relation in the same namespace: give each " + + "table's sequence its own name. An @sequenceName on an abstract base's identity is inherited by every " + + "entity that extends it, so declare it on each concrete entity instead.", + ); + } if (anyOther) { fixes.push("Rename one of the tables/views (entity source `@table`, projection `@kind view @view`)."); } diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 86c5bc0c51..b762832276 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -429,6 +429,16 @@ export function buildExpectedSchemaWithProvenance( addOwner(t.schema, idx.name, label); } } + // A declared sequence name is a relation too (Postgres `pg_class`, per schema): two tables + // declaring one, or one naming a table, view or index, would fail at apply time — an + // identity.primary @sequenceName on an abstract base is inherited by every entity extending it. + for (const t of tables) { + for (const col of t.columns) { + if (col.sequence?.name !== undefined) { + addOwner(t.schema, col.sequence.name, `identity.primary @sequenceName "${col.sequence.name}" on table "${t.name}"`); + } + } + } const collisions = [...sqlNameOwners.entries()] .filter(([, owners]) => owners.length > 1) .map(([key, owners]) => ({ diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index 2c4807eeef..38a86cc72e 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -536,8 +536,8 @@ async function readPgCatalogColumnFacts( /** * The sequence behind each auto-increment column — a GENERATED identity's or a legacy * serial's — found through `pg_depend` (the column OWNS it), with its name and start value - * from `pg_sequence`. Sets `sequence` on `columns` in place. Compared only against what the - * model declares (identity.primary @sequenceStart / @sequenceName). + * from `pg_sequence`. Sets `liveSequence` on `columns` in place (never `sequence`, which is + * the model's declaration). Compared only against what the model declares. */ async function readPgColumnSequences( k: RawKysely, schema: string, tableName: string, columns: ColumnDescriptor[], @@ -545,8 +545,8 @@ async function readPgColumnSequences( // pg-mem gap: pg_depend / pg_sequence are not supported — the query throws and the // columns carry no sequence, so nothing about one is compared. try { - const rows = await sql<{ column_name: string; sequence_name: string; seqstart: string | number }>` - SELECT a.attname AS column_name, seq.relname AS sequence_name, ps.seqstart + const rows = await sql<{ column_name: string; sequence_schema: string; sequence_name: string; seqstart: string | number }>` + SELECT a.attname AS column_name, sn.nspname AS sequence_schema, seq.relname AS sequence_name, ps.seqstart FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped @@ -554,6 +554,7 @@ async function readPgColumnSequences( AND d.classid = 'pg_class'::regclass AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i') JOIN pg_class seq ON seq.oid = d.objid AND seq.relkind = 'S' + JOIN pg_namespace sn ON sn.oid = seq.relnamespace JOIN pg_sequence ps ON ps.seqrelid = seq.oid WHERE n.nspname = ${schema} AND c.relname = ${tableName} @@ -562,7 +563,11 @@ async function readPgColumnSequences( for (const r of rows.rows) { const col = byName.get(r.column_name); if (col === undefined) continue; - col.sequence = { name: r.sequence_name, start: Number(r.seqstart) }; + col.liveSequence = { + ...(r.sequence_schema !== schema ? { schema: r.sequence_schema } : {}), + name: r.sequence_name, + start: Number(r.seqstart), + }; } } catch { // see above diff --git a/server/typescript/packages/migrate-ts/src/shadow-expected.ts b/server/typescript/packages/migrate-ts/src/shadow-expected.ts index b08ad3f746..2b0bb0a3cd 100644 --- a/server/typescript/packages/migrate-ts/src/shadow-expected.ts +++ b/server/typescript/packages/migrate-ts/src/shadow-expected.ts @@ -21,10 +21,30 @@ export type ShadowCatalog = { catalog: SchemaSnapshot } | { unavailable: string /** Applies `expected` to a scratch database and reads it back (see shadow-canon.ts). */ export type ShadowSchemaSource = (expected: SchemaSnapshot) => Promise; -/** `expected` re-read from `shadow`: each model table replaced by the shadow's table of the same name. */ +/** + * `expected` re-read from `shadow`: each model table replaced by the shadow's table of the same + * name. A column's DECLARED sequence (`sequence`) is the model's, carried across, and the + * shadow's own read of it (`liveSequence`) is dropped: the shadow database names every + * sequence, declared or not, and only what the model declares may be compared or emitted. + */ export function expectedFromShadow(shadow: SchemaSnapshot, expected: SchemaSnapshot): SchemaSnapshot { const byId = new Map(shadow.tables.map((t) => [qualifiedDbName(t), t] as const)); - return { ...expected, tables: expected.tables.map((model) => byId.get(qualifiedDbName(model)) ?? model) }; + return { + ...expected, + tables: expected.tables.map((model) => { + const read = byId.get(qualifiedDbName(model)); + if (read === undefined) return model; + const declared = new Map(model.columns.map((c) => [c.name, c.sequence] as const)); + return { + ...read, + columns: read.columns.map((c) => { + const { liveSequence: _live, sequence: _read, ...rest } = c; + const seq = declared.get(c.name); + return seq === undefined ? rest : { ...rest, sequence: seq }; + }), + }; + }), + }; } /** diff --git a/server/typescript/packages/migrate-ts/src/snapshot/serialize.ts b/server/typescript/packages/migrate-ts/src/snapshot/serialize.ts index 74acfedd65..c84d48ff8e 100644 --- a/server/typescript/packages/migrate-ts/src/snapshot/serialize.ts +++ b/server/typescript/packages/migrate-ts/src/snapshot/serialize.ts @@ -83,10 +83,27 @@ function stableStringify(value: unknown): string { ); } +/** + * A snapshot records what the model declares, never what introspection read: a live + * sequence's name and start (`liveSequence`) is dropped, so a `baseline --from-db` writes the + * same bytes it wrote before sequences were read. The format version does not move: the + * declared `sequence` is written only when a model declares one, and a reader that does not + * know it finds it absent, which it treats as undeclared. + */ +function withoutLiveSequences(snapshot: SchemaSnapshot): SchemaSnapshot { + return { + ...snapshot, + tables: snapshot.tables.map((t) => ({ + ...t, + columns: t.columns.map(({ liveSequence: _live, ...c }) => c), + })), + }; +} + export function serializeSnapshot(snapshot: SchemaSnapshot): string { const file: SnapshotFile = { formatVersion: SNAPSHOT_FORMAT_VERSION, - snapshot: canonicalize(snapshot), + snapshot: canonicalize(withoutLiveSequences(snapshot)), }; return stableStringify(file) + "\n"; } diff --git a/server/typescript/packages/migrate-ts/src/types.ts b/server/typescript/packages/migrate-ts/src/types.ts index 96797a2e01..2a4a1f775b 100644 --- a/server/typescript/packages/migrate-ts/src/types.ts +++ b/server/typescript/packages/migrate-ts/src/types.ts @@ -68,12 +68,19 @@ export interface ColumnDescriptor { default?: ColumnDefault; identity?: "increment" | "uuid"; /** - * The sequence an `increment` identity draws from. Expected side: only what the - * identity.primary DECLARES (`@sequenceStart` → `start`, `@sequenceName` → `name`), and only - * those are compared, so an undeclared start or name never produces a change. Postgres live - * side: the sequence's actual name and start. Absent on SQLite, which has no sequences. + * The sequence an `increment` identity draws from, as the MODEL declares it: only what the + * identity.primary declares (`@sequenceStart` → `start`, `@sequenceName` → `name`). The only + * sequence fact the emitter renders and a snapshot records, and the only one compared, so an + * undeclared start or name never produces a change or a different byte of SQL. */ sequence?: { name?: string; start?: number }; + /** + * Postgres introspection only: the sequence the live column actually owns (`pg_depend`), its + * schema, name and start (`pg_sequence`). Read by the diff to compare against `sequence` and + * to address an `alter-sequence`; never emitted, never written to a snapshot, so it changes + * nothing for a model that declares no sequence. + */ + liveSequence?: { schema?: string; name: string; start: number }; /** * Human-readable description threaded from field `@description`. * Postgres: emitted as `COMMENT ON COLUMN … IS '…';` after CREATE TABLE or ADD COLUMN. @@ -309,14 +316,17 @@ export type Change = from?: ColumnDefault; to?: ColumnDefault; status: ChangeStatus } /** Postgres, shadow path only: an `increment` identity (`GENERATED BY DEFAULT AS IDENTITY`) added or dropped. */ | { kind: "change-column-identity"; table: string; schema?: string; column: string; - from?: "increment"; to?: "increment"; status: ChangeStatus } + from?: "increment"; to?: "increment"; + /** The model's declared sequence for an identity being ADDED (rendered as its options). */ + sequence?: { name?: string; start?: number }; + status: ChangeStatus } /** * Postgres: an increment identity's sequence whose declared start or name differs from the * live one, altered in place (`ALTER SEQUENCE … START WITH` / `RENAME TO`). `sequence` is the * live name the change addresses; each pair is set only when it differs. */ | { kind: "alter-sequence"; table: string; schema?: string; column: string; sequence: string; - fromStart?: number; toStart?: number; toName?: string; status: ChangeStatus } + sequenceSchema?: string; fromStart?: number; toStart?: number; toName?: string; status: ChangeStatus } /** * Postgres, shadow path only: a table comment (no `column`) or column comment set, changed or * cleared. Clearing one the model does not declare is gated behind `allow.dropComment`. diff --git a/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts b/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts index 0660bca359..c79d5e5696 100644 --- a/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/identity-sequence.test.ts @@ -12,6 +12,9 @@ import { buildExpectedSchema } from "../../src/expected-schema.js"; import { diff } from "../../src/diff/index.js"; import { emit } from "../../src/emit/index.js"; import type { SchemaSnapshot as DatabaseSchema } from "../../src/types.js"; +import { expectedFromShadow } from "../../src/shadow-expected.js"; +import { serializeSnapshot } from "../../src/snapshot/serialize.js"; +import { DuplicateSqlNameError } from "../../src/errors.js"; async function schema(pk: Record) { const doc = { "metadata.root": { package: "acme", children: [ @@ -29,10 +32,11 @@ async function schema(pk: Record) { const EMPTY = { tables: [], views: [] } as unknown as DatabaseSchema; const idColumn = (s: DatabaseSchema) => s.tables.find((t) => t.name === "Ticket")!.columns.find((c) => c.name === "Id")!; -/** The live side: the same table, its sequence as Postgres reports it. */ +/** The live side: the same table, its sequence as Postgres reports it (introspection only). */ function live(expected: DatabaseSchema, sequence: { name: string; start: number }): DatabaseSchema { const copy = structuredClone(expected); - idColumn(copy).sequence = sequence; + delete idColumn(copy).sequence; + idColumn(copy).liveSequence = sequence; return copy; } @@ -56,6 +60,8 @@ describe("identity.primary sequence start and name", () => { expect(changes.filter((c) => c.kind === "alter-sequence")).toHaveLength(1); const { up, down } = emit(changes, { dialect: "postgres" }); expect(up).toContain('ALTER SEQUENCE "Ticket_Id_seq" START WITH 1000000000;'); + // START WITH alone only records a restart point: the counter is moved up to it, never down. + expect(up).toContain(`SELECT setval('"Ticket_Id_seq"', 1000000000, false) FROM "Ticket_Id_seq" WHERE last_value < 1000000000;`); expect(up).toContain('ALTER SEQUENCE "Ticket_Id_seq" RENAME TO "Old_Id_seq";'); expect(down).toContain('ALTER SEQUENCE "Old_Id_seq" RENAME TO "Ticket_Id_seq";'); expect(down).toContain('ALTER SEQUENCE "Ticket_Id_seq" START WITH 1;'); @@ -81,4 +87,67 @@ describe("identity.primary sequence start and name", () => { expect(up).not.toContain("SEQUENCE"); expect(up).not.toContain("1000000000"); }); + + test("shadow path: a model that declares nothing gets no sequence clause and no change", async () => { + const model = await schema({}); + // The shadow database's own read of the model's tables: introspection fills liveSequence. + const shadow = live(model, { name: "Ticket_Id_seq", start: 1 }); + const expected = expectedFromShadow(shadow, model); + expect(idColumn(expected).sequence).toBeUndefined(); + // A live sequence left behind by a table rename, with a non-default start: not compared. + const { changes } = await diff(expected, live(model, { name: "OldTicket_Id_seq", start: 1000 }), { dialect: "postgres" }); + expect(changes.filter((c) => c.kind === "alter-sequence")).toEqual([]); + // CREATE from the shadow-read expected side: plain IDENTITY, as before. + const created = await diff(expected, EMPTY, { dialect: "postgres" }); + expect(emit(created.changes, { dialect: "postgres" }).up).not.toContain("SEQUENCE NAME"); + }); + + test("shadow path: what the model declares survives the shadow read", async () => { + const model = await schema({ "@sequenceStart": 1000000000, "@sequenceName": "Old_Id_seq" }); + const expected = expectedFromShadow(live(model, { name: "Old_Id_seq", start: 1000000000 }), model); + expect(idColumn(expected).sequence).toEqual({ start: 1000000000, name: "Old_Id_seq" }); + }); + + test("offline (committed snapshot): a changed declared start is a change, addressed by the default name", async () => { + const before = await schema({ "@sequenceStart": 1000 }); + const after = await schema({ "@sequenceStart": 2000 }); + const { changes } = await diff(after, before, { dialect: "postgres" }); + const alter = changes.filter((c) => c.kind === "alter-sequence"); + expect(alter).toHaveLength(1); + expect(emit(changes, { dialect: "postgres" }).up).toContain('ALTER SEQUENCE "Ticket_Id_seq" START WITH 2000;'); + }); + + test("adding the identity to an existing column carries the declared options", () => { + const { up } = emit([{ + kind: "change-column-identity", table: "Ticket", column: "Id", to: "increment", + sequence: { name: "Old_Id_seq", start: 1000000000 }, status: "allowed", + } as never], { dialect: "postgres" }); + expect(up).toContain('ALTER TABLE "Ticket" ALTER COLUMN "Id" ADD GENERATED BY DEFAULT AS IDENTITY (SEQUENCE NAME "Old_Id_seq" START WITH 1000000000);'); + }); + + test("a dropped table's down rebuilds it as before: the live sequence is never emitted", async () => { + const s = await schema({}); + const { changes } = await diff(EMPTY, live(s, { name: "OldTicket_Id_seq", start: 1000 }), { dialect: "postgres", allow: { dropTable: true } } as never); + expect(emit(changes, { dialect: "postgres" }).down).not.toContain("SEQUENCE NAME"); + }); + + test("a snapshot never records the live sequence", async () => { + const s = await schema({}); + const text = serializeSnapshot(live(s, { name: "OldTicket_Id_seq", start: 1000 })); + expect(text).not.toContain("OldTicket_Id_seq"); + expect(text).not.toContain("liveSequence"); + }); + + test("two tables declaring one sequence name are refused before any SQL is emitted", async () => { + const doc = { "metadata.root": { package: "acme", children: ["A", "B"].map((n) => ( + { "object.entity": { name: n, children: [ + { "source.rdb": { "@table": n } }, + { "field.int": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment", "@sequenceName": "shared_seq" } }, + ] } })) } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toHaveLength(0); + expect(() => buildExpectedSchema(root)).toThrow(DuplicateSqlNameError); + expect(() => buildExpectedSchema(root)).toThrow(/shared_seq/); + }); }); From cf82092d5818f98d24cb76a1442fd385b2053dea Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 13:05:04 -0500 Subject: [PATCH 020/267] feat(migrate): CHECKs on existing tables are NOT VALID + VALIDATE; efcore skips redundant CHECKs - Postgres: a CHECK added to an existing table is ADD CONSTRAINT ... NOT VALID, then ALTER TABLE ... VALIDATE CONSTRAINT: the same end state as a plain ADD, under a lighter lock while adding, with a violating row failing at the step that names the constraint. A CHECK inside CREATE TABLE is unchanged. - SchemaConventions gains an optional skipRedundantChecks (on in the efcore preset): a validator.length maximum the column's VARCHAR(n) enforces, and a minimum of 0, emit no CHECK. Default conventions, and conventions objects that do not set it, emit every CHECK as before. The per-kind CHECK on/off policy from the issue draft is not built: no adopter needs it yet. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++ docs/features/migrations-and-drift.md | 10 +++ .../packages/migrate-ts/src/emit/postgres.ts | 7 +- .../migrate-ts/src/expected-schema.ts | 27 +++++-- .../migrate-ts/src/schema-conventions.ts | 8 ++ .../test/check-evolution/e2e.test.ts | 5 +- .../test/check/emit-postgres-check.test.ts | 5 +- .../check-redundant-and-not-valid.test.ts | 79 +++++++++++++++++++ 8 files changed, 139 insertions(+), 11 deletions(-) create mode 100644 server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 20da900914..100d9da7d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,15 @@ here.** ### Changed +- **`meta migrate` adds a CHECK to an existing Postgres table as `NOT VALID`, then `VALIDATE + CONSTRAINT`.** The same end state as the plain `ADD CONSTRAINT` it wrote before, under a lighter + lock while adding, and a row that violates the check fails at the validation step that names + the constraint. A CHECK in a `CREATE TABLE` is unchanged. +- **The `efcore` schema conventions leave out CHECKs the column type already guarantees** + (`skipRedundantChecks`): a `validator.length` maximum the column's `VARCHAR(n)` enforces, and a + minimum of 0. An EF Core database has none of them. The default conventions, and a conventions + object that does not set it, emit them as before. + - **Added vocabulary no longer moves `metamodelVersion`.** The metamodel spec version now moves only when metadata that loaded may stop loading or change meaning. A new type, subtype, optional attribute or enum member leaves it unchanged, and its CHANGELOG entry names it; the diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 91433bd7be..e5e30b6706 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -425,6 +425,7 @@ come from the project's **schema conventions**, selected in `.metaobjects/config | Foreign-key constraint name | `
    __fk` | `FK_
    __` | | Index on a foreign key | none | `IX_
    _`, unless the primary key or another index (a partial one included) already starts with the FK's columns; an FK index another FK index covers is dropped, so FK order does not matter | | Unique key (`identity.secondary`, a `@unique` field) | a unique index | a UNIQUE constraint when a foreign key references it, else a unique index | +| A CHECK the column type already guarantees (`skipRedundantChecks`) | emitted | left out: a `validator.length` maximum the column's `VARCHAR(n)` enforces, and a minimum of 0 | `efcore` follows EF Core's own conventions on PostgreSQL (Npgsql), including its truncation of a name longer than 63 characters to 62 characters and `~`. A database first built by EF Core @@ -461,6 +462,15 @@ definition is unchanged and whose name differs is renamed in place (`RENAME CONS and whether a unique key is a constraint or an index are not compared by the diff, so they only shape what migrate creates. SQLite cannot rename a constraint and rebuilds the table instead. +## Adding a CHECK to a table that already holds rows + +On Postgres a CHECK added to an existing table (a new validator, a new enum member list) is +written as two statements: `ALTER TABLE … ADD CONSTRAINT … CHECK (…) NOT VALID`, which checks +new writes at once under a light lock, then `ALTER TABLE … VALIDATE CONSTRAINT …`, which checks +the rows already there. The end state is the same as a plain `ADD CONSTRAINT`; a row that +violates the check fails the migration at the `VALIDATE` step, which names the constraint, so +fix that row and apply again. A CHECK on a new table stays inside its `CREATE TABLE`. + ## How CHECK constraints and expression indexes are compared Postgres rewrites an expression before it stores it (`"k" IN ('x')` becomes `k = 'x'::text`, diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index 4449c188bf..902d357ca9 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -292,7 +292,12 @@ function renderUp(c: Change, recreated: ReadonlySet = new Set()): string // folds into a table recreate that rebuilds from the EXPECTED descriptor and never // references the dropped constraint. SQLite is already replay-safe by construction; // guarding Postgres makes the two dialects agree. - case "add-check": return `ALTER TABLE ${quoteQualified(c.table, c.schema)} ADD CONSTRAINT ${quote(c.check.name)} CHECK (${c.check.expression});`; + // On a table that already holds rows: NOT VALID adds the CHECK for new writes under a light + // lock, and VALIDATE then checks the existing rows — the same end state as a plain ADD, with + // a violating row failing at a step that names the constraint. + case "add-check": + return `ALTER TABLE ${quoteQualified(c.table, c.schema)} ADD CONSTRAINT ${quote(c.check.name)} CHECK (${c.check.expression}) NOT VALID;\n` + + `ALTER TABLE ${quoteQualified(c.table, c.schema)} VALIDATE CONSTRAINT ${quote(c.check.name)};`; // Same `ALTER TABLE IF EXISTS` gap as `drop-fk` above. case "drop-check": return `ALTER TABLE IF EXISTS ${quoteQualified(c.table, c.schema)} DROP CONSTRAINT IF EXISTS ${quote(c.check)};`; case "create-view": { diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index b762832276..744421813e 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -645,7 +645,7 @@ function buildTable( columns, indexes: buildSecondaryIndexes(entity, tableName, strategy), foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, fkCtx, onConflict), - checks: buildChecks(entity, tableName, strategy, dialect), + checks: buildChecks(entity, tableName, strategy, dialect, fkCtx.conventions.skipRedundantChecks === true), primaryKey, }; const entityDesc = readDescription(entity); @@ -793,7 +793,13 @@ function buildSecondaryIndexes( * column name verbatim (matching the enum-check convention). */ function validatorCheck( - v: MetaValidator, qcol: string, tableName: string, col: string, dialect: Dialect | undefined, + v: MetaValidator, + qcol: string, + tableName: string, + col: string, + dialect: Dialect | undefined, + skipRedundant = false, + enforcedMax?: number, ): CheckDescriptor | null { switch (v.subType) { case VALIDATOR_SUBTYPE_NUMERIC: { @@ -805,8 +811,10 @@ function validatorCheck( } case VALIDATOR_SUBTYPE_LENGTH: { const parts: string[] = []; - if (v.min !== undefined) parts.push(`length(${qcol}) >= ${v.min}`); - if (v.max !== undefined) parts.push(`length(${qcol}) <= ${v.max}`); + // Under skipRedundant, a minimum of 0 is always true and a maximum the column's + // VARCHAR(n) already enforces (n <= max) adds nothing. + if (v.min !== undefined && !(skipRedundant && v.min <= 0)) parts.push(`length(${qcol}) >= ${v.min}`); + if (v.max !== undefined && !(enforcedMax !== undefined && enforcedMax <= v.max)) parts.push(`length(${qcol}) <= ${v.max}`); if (parts.length === 0) return null; return { name: `${tableName}_${col}_length_chk`, expression: parts.join(" AND ") }; } @@ -840,7 +848,11 @@ function quoteCheckCol(col: string): string { } function buildChecks( - entity: MetaObject, tableName: string, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, + entity: MetaObject, + tableName: string, + strategy: ColumnNamingStrategy, + dialect: Dialect | undefined, + skipRedundant: boolean, ): CheckDescriptor[] { const checks: CheckDescriptor[] = []; for (const field of entity.fields()) { @@ -887,8 +899,11 @@ function buildChecks( } } // Validator-derived checks. + // The VARCHAR(n) the column already is, when the conventions skip what it enforces. + const columnType = subtypeToSqlType(field); + const enforcedMax = skipRedundant && columnType.kind === "text" ? columnType.maxLength : undefined; for (const v of field.validators()) { - const check = validatorCheck(v, qcol, tableName, col, dialect); + const check = validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); if (check) checks.push(check); } } diff --git a/server/typescript/packages/migrate-ts/src/schema-conventions.ts b/server/typescript/packages/migrate-ts/src/schema-conventions.ts index c711f8597d..e752df4338 100644 --- a/server/typescript/packages/migrate-ts/src/schema-conventions.ts +++ b/server/typescript/packages/migrate-ts/src/schema-conventions.ts @@ -51,6 +51,12 @@ export interface SchemaConventions { foreignKeyIndexes(table: TableKeys): { name: string; columns: string[] }[]; /** How a unique key (`identity.secondary`) is created. A partial or expression key is always an index. */ uniqueKeyKind(key: KeyContext & { referencedByForeignKey: boolean }): "index" | "constraint"; + /** + * Leave out a CHECK the schema already guarantees: a `validator.length` maximum the column's + * VARCHAR(n) enforces, and a minimum of 0. Optional, so a conventions object written before it + * keeps emitting every CHECK, as the default conventions do. + */ + readonly skipRedundantChecks?: boolean; } /** Postgres's identifier limit (NAMEDATALEN - 1). */ @@ -98,6 +104,8 @@ export const efcoreConventions: SchemaConventions = { }, // An alternate key (one an FK references) is a UNIQUE constraint; any other unique key is an index. uniqueKeyKind: ({ referencedByForeignKey }) => (referencedByForeignKey ? "constraint" : "index"), + // An EF Core database carries none of the CHECKs its column types already enforce. + skipRedundantChecks: true, }; const PRESETS: Readonly> = { diff --git a/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts b/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts index 26b27a7ba9..e976e2f3d7 100644 --- a/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts +++ b/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts @@ -11,10 +11,11 @@ function tbl(checks: CheckDescriptor[]): TableDescriptor { const snap = (checks: CheckDescriptor[]): SchemaSnapshot => ({ tables: [tbl(checks)], views: [] }); describe("e2e: existing-table CHECK evolution (postgres)", () => { - test("adding a check on an existing table emits ALTER TABLE ADD CONSTRAINT", async () => { + test("adding a check on an existing table emits ALTER TABLE ADD CONSTRAINT … NOT VALID, then VALIDATE", async () => { const r = await diff({ expected: snap([CHK("orders_qty_chk", "qty >= 1")]), actual: snap([]), dialect: "postgres" }); const { up } = emit(r.changes, { dialect: "postgres" }); - expect(up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_qty_chk" CHECK (qty >= 1);`); + expect(up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_qty_chk" CHECK (qty >= 1) NOT VALID;`); + expect(up).toContain(`ALTER TABLE "orders" VALIDATE CONSTRAINT "orders_qty_chk";`); }); test("create-table on empty actual inlines the check (no separate ADD CONSTRAINT)", async () => { // a brand-new table carries its checks inline in CREATE TABLE; diffTableChecks diff --git a/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts b/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts index db3b0c7148..df397c12b3 100644 --- a/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts +++ b/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts @@ -15,9 +15,10 @@ describe("emit postgres — checks", () => { const r = emit([{ kind: "create-table", table, status: ALLOWED } as unknown as Change], { dialect: "postgres" }); expect(r.up).toContain(`CONSTRAINT "orders_status_chk" CHECK (status IN ('OPEN','CLOSED'))`); }); - test("add-check → ALTER TABLE ADD CONSTRAINT; down drops it", () => { + test("add-check → ALTER TABLE ADD CONSTRAINT … NOT VALID, then VALIDATE; down drops it", () => { const r = emit([{ kind: "add-check", table: "orders", check: CHK, status: ALLOWED } as unknown as Change], { dialect: "postgres" }); - expect(r.up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_status_chk" CHECK (status IN ('OPEN','CLOSED'));`); + expect(r.up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_status_chk" CHECK (status IN ('OPEN','CLOSED')) NOT VALID;`); + expect(r.up).toContain(`ALTER TABLE "orders" VALIDATE CONSTRAINT "orders_status_chk";`); expect(r.down).toContain(`ALTER TABLE "orders" DROP CONSTRAINT "orders_status_chk";`); }); test("drop-check → ALTER TABLE DROP CONSTRAINT", () => { diff --git a/server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts b/server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts new file mode 100644 index 0000000000..0406d63c73 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts @@ -0,0 +1,79 @@ +/** + * CHECK constraints the schema already guarantees, and CHECKs added to a table that holds rows. + * + * - `skipRedundantChecks` on the schema conventions (on in the efcore preset, off by default so + * nothing changes for an existing project): a `validator.length` bound the column's + * VARCHAR(n) already enforces, and a minimum of 0 (always true), emit nothing; the rest of + * the check stands. + * - Postgres: a CHECK added to an EXISTING table is `ADD CONSTRAINT … NOT VALID` then + * `VALIDATE CONSTRAINT` — the same end state, a lighter lock while adding, and a violating + * row fails at a named validation step. A CHECK inside a CREATE TABLE is unchanged. + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { defaultConventions, efcoreConventions } from "../../src/schema-conventions.js"; +import { diff } from "../../src/diff/index.js"; +import { emit } from "../../src/emit/index.js"; + +async function root(lengthValidator: Record, maxLength?: number) { + const doc = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Ticket", children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code", ...(maxLength !== undefined ? { "@maxLength": maxLength } : {}), children: [ + { "validator.length": { name: "len", ...lengthValidator } }, + ] } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, + ] } }, + ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toHaveLength(0); + return root; +} + +const checksOf = (s: ReturnType) => + s.tables.find((t) => t.name === "tickets")!.checks.map((c) => c.expression); + +describe("redundant CHECKs", () => { + test("default conventions: unchanged — the length check is emitted whole", async () => { + const r = await root({ "@min": 0, "@max": 3 }, 3); + expect(checksOf(buildExpectedSchema(r, { conventions: defaultConventions }))).toEqual(['length("code") >= 0 AND length("code") <= 3']); + }); + + test("efcore: a max the VARCHAR(n) enforces and a min of 0 emit no check", async () => { + const r = await root({ "@min": 0, "@max": 3 }, 3); + expect(checksOf(buildExpectedSchema(r, { conventions: efcoreConventions }))).toEqual([]); + }); + + test("efcore: a max looser than the VARCHAR(n) is redundant too; a real min stays", async () => { + const r = await root({ "@min": 2, "@max": 10 }, 3); + expect(checksOf(buildExpectedSchema(r, { conventions: efcoreConventions }))).toEqual(['length("code") >= 2']); + }); + + test("efcore: a max tighter than the column, or on an unbounded column, stays", async () => { + expect(checksOf(buildExpectedSchema(await root({ "@max": 2 }, 3), { conventions: efcoreConventions }))) + .toEqual(['length("code") <= 2']); + expect(checksOf(buildExpectedSchema(await root({ "@max": 2 }), { conventions: efcoreConventions }))) + .toEqual(['length("code") <= 2']); + }); +}); + +describe("a CHECK added to an existing table", () => { + test("Postgres: NOT VALID, then VALIDATE CONSTRAINT; the down drops it", async () => { + const withCheck = buildExpectedSchema(await root({ "@max": 2 }, 3)); + const before = structuredClone(withCheck); + before.tables[0]!.checks = []; + const { changes } = await diff(withCheck, before, { dialect: "postgres" }); + const { up, down } = emit(changes, { dialect: "postgres" }); + expect(up).toContain('ALTER TABLE "tickets" ADD CONSTRAINT "tickets_code_length_chk" CHECK (length("code") <= 2) NOT VALID;'); + expect(up).toContain('ALTER TABLE "tickets" VALIDATE CONSTRAINT "tickets_code_length_chk";'); + expect(down).toContain('ALTER TABLE "tickets" DROP CONSTRAINT "tickets_code_length_chk";'); + }); + + test("Postgres: a CHECK inside CREATE TABLE is unchanged (no NOT VALID)", async () => { + const s = buildExpectedSchema(await root({ "@max": 2 }, 3)); + const { changes } = await diff(s, { tables: [], views: [] } as never, { dialect: "postgres" }); + expect(emit(changes, { dialect: "postgres" }).up).not.toContain("NOT VALID"); + }); +}); From a90e65fcefcf1fde95acb99c81ecd9e3008e3aa7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 13:16:30 -0500 Subject: [PATCH 021/267] fix(migrate): drop the NOT VALID add-check; keep redundant length CHECKs on SQLite Review fixes for 418d723cd: - Revert add-check to a plain ADD CONSTRAINT. The NOT VALID + VALIDATE pair bought nothing: migrate's runner applies a migration in one transaction, Postgres takes the same AccessExclusiveLock for both forms and holds it through VALIDATE, and a plain ADD already names the violated constraint. Outside the runner, statement by statement, it could also leave an unvalidated constraint nothing reports. - skipRedundantChecks no longer drops a length maximum on SQLite / D1: they accept a declared VARCHAR(n) and store longer values, so the CHECK is the only enforcement. - The efcore note moves into the (unreleased) efcore entry in CHANGELOG "Added". Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 +++------ docs/features/migrations-and-drift.md | 11 +------ .../packages/migrate-ts/src/emit/postgres.ts | 7 +---- .../migrate-ts/src/expected-schema.ts | 6 ++-- .../test/check-evolution/e2e.test.ts | 5 ++-- .../test/check/emit-postgres-check.test.ts | 5 ++-- ...-valid.test.ts => check-redundant.test.ts} | 30 +++++-------------- 7 files changed, 21 insertions(+), 57 deletions(-) rename server/typescript/packages/migrate-ts/test/unit/{check-redundant-and-not-valid.test.ts => check-redundant.test.ts} (63%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 100d9da7d8..a38579d6e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,7 +78,10 @@ here.** is a constraint or an index. `default` is what migrate has always emitted, so nothing changes unless you set it. `efcore` reproduces EF Core's conventions (`PK_`, `FK_`, `IX_`, its 63-character `~` truncation, alternate keys as constraints), so a database built by EF Core - migrations and one built by `meta migrate` match. A project can supply its own conventions + migrations and one built by `meta migrate` match. It also leaves out the CHECKs a column type + already guarantees (`skipRedundantChecks`): a `validator.length` maximum the column's + `VARCHAR(n)` enforces (not on SQLite or D1, which do not enforce one), and a minimum of 0 or + less; an EF Core database has none of them. A project can supply its own conventions object from `metaobjects.config.ts`; an unknown preset name, or an object missing a member, is refused by name. The PK name is now introspected too, so a `baseline --from-db` snapshot of a database whose primary keys are not named `
    _pkey` records their names (not compared; @@ -97,15 +100,6 @@ here.** ### Changed -- **`meta migrate` adds a CHECK to an existing Postgres table as `NOT VALID`, then `VALIDATE - CONSTRAINT`.** The same end state as the plain `ADD CONSTRAINT` it wrote before, under a lighter - lock while adding, and a row that violates the check fails at the validation step that names - the constraint. A CHECK in a `CREATE TABLE` is unchanged. -- **The `efcore` schema conventions leave out CHECKs the column type already guarantees** - (`skipRedundantChecks`): a `validator.length` maximum the column's `VARCHAR(n)` enforces, and a - minimum of 0. An EF Core database has none of them. The default conventions, and a conventions - object that does not set it, emit them as before. - - **Added vocabulary no longer moves `metamodelVersion`.** The metamodel spec version now moves only when metadata that loaded may stop loading or change meaning. A new type, subtype, optional attribute or enum member leaves it unchanged, and its CHANGELOG entry names it; the diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index e5e30b6706..656b53d030 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -425,7 +425,7 @@ come from the project's **schema conventions**, selected in `.metaobjects/config | Foreign-key constraint name | `
    __fk` | `FK_
    __` | | Index on a foreign key | none | `IX_
    _`, unless the primary key or another index (a partial one included) already starts with the FK's columns; an FK index another FK index covers is dropped, so FK order does not matter | | Unique key (`identity.secondary`, a `@unique` field) | a unique index | a UNIQUE constraint when a foreign key references it, else a unique index | -| A CHECK the column type already guarantees (`skipRedundantChecks`) | emitted | left out: a `validator.length` maximum the column's `VARCHAR(n)` enforces, and a minimum of 0 | +| A CHECK the column type already guarantees (`skipRedundantChecks`) | emitted | left out: a `validator.length` maximum the column's `VARCHAR(n)` enforces (not on SQLite or D1, which do not enforce a declared length), and a minimum of 0 or less | `efcore` follows EF Core's own conventions on PostgreSQL (Npgsql), including its truncation of a name longer than 63 characters to 62 characters and `~`. A database first built by EF Core @@ -462,15 +462,6 @@ definition is unchanged and whose name differs is renamed in place (`RENAME CONS and whether a unique key is a constraint or an index are not compared by the diff, so they only shape what migrate creates. SQLite cannot rename a constraint and rebuilds the table instead. -## Adding a CHECK to a table that already holds rows - -On Postgres a CHECK added to an existing table (a new validator, a new enum member list) is -written as two statements: `ALTER TABLE … ADD CONSTRAINT … CHECK (…) NOT VALID`, which checks -new writes at once under a light lock, then `ALTER TABLE … VALIDATE CONSTRAINT …`, which checks -the rows already there. The end state is the same as a plain `ADD CONSTRAINT`; a row that -violates the check fails the migration at the `VALIDATE` step, which names the constraint, so -fix that row and apply again. A CHECK on a new table stays inside its `CREATE TABLE`. - ## How CHECK constraints and expression indexes are compared Postgres rewrites an expression before it stores it (`"k" IN ('x')` becomes `k = 'x'::text`, diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index 902d357ca9..4449c188bf 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -292,12 +292,7 @@ function renderUp(c: Change, recreated: ReadonlySet = new Set()): string // folds into a table recreate that rebuilds from the EXPECTED descriptor and never // references the dropped constraint. SQLite is already replay-safe by construction; // guarding Postgres makes the two dialects agree. - // On a table that already holds rows: NOT VALID adds the CHECK for new writes under a light - // lock, and VALIDATE then checks the existing rows — the same end state as a plain ADD, with - // a violating row failing at a step that names the constraint. - case "add-check": - return `ALTER TABLE ${quoteQualified(c.table, c.schema)} ADD CONSTRAINT ${quote(c.check.name)} CHECK (${c.check.expression}) NOT VALID;\n` - + `ALTER TABLE ${quoteQualified(c.table, c.schema)} VALIDATE CONSTRAINT ${quote(c.check.name)};`; + case "add-check": return `ALTER TABLE ${quoteQualified(c.table, c.schema)} ADD CONSTRAINT ${quote(c.check.name)} CHECK (${c.check.expression});`; // Same `ALTER TABLE IF EXISTS` gap as `drop-fk` above. case "drop-check": return `ALTER TABLE IF EXISTS ${quoteQualified(c.table, c.schema)} DROP CONSTRAINT IF EXISTS ${quote(c.check)};`; case "create-view": { diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 744421813e..84393e8e03 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -899,9 +899,11 @@ function buildChecks( } } // Validator-derived checks. - // The VARCHAR(n) the column already is, when the conventions skip what it enforces. + // The VARCHAR(n) the column already is, when the conventions skip what it enforces. Not on + // SQLite / D1: they accept a declared length and store longer values anyway. const columnType = subtypeToSqlType(field); - const enforcedMax = skipRedundant && columnType.kind === "text" ? columnType.maxLength : undefined; + const enforcesLength = dialect !== "sqlite" && dialect !== "d1"; + const enforcedMax = skipRedundant && enforcesLength && columnType.kind === "text" ? columnType.maxLength : undefined; for (const v of field.validators()) { const check = validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); if (check) checks.push(check); diff --git a/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts b/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts index e976e2f3d7..26b27a7ba9 100644 --- a/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts +++ b/server/typescript/packages/migrate-ts/test/check-evolution/e2e.test.ts @@ -11,11 +11,10 @@ function tbl(checks: CheckDescriptor[]): TableDescriptor { const snap = (checks: CheckDescriptor[]): SchemaSnapshot => ({ tables: [tbl(checks)], views: [] }); describe("e2e: existing-table CHECK evolution (postgres)", () => { - test("adding a check on an existing table emits ALTER TABLE ADD CONSTRAINT … NOT VALID, then VALIDATE", async () => { + test("adding a check on an existing table emits ALTER TABLE ADD CONSTRAINT", async () => { const r = await diff({ expected: snap([CHK("orders_qty_chk", "qty >= 1")]), actual: snap([]), dialect: "postgres" }); const { up } = emit(r.changes, { dialect: "postgres" }); - expect(up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_qty_chk" CHECK (qty >= 1) NOT VALID;`); - expect(up).toContain(`ALTER TABLE "orders" VALIDATE CONSTRAINT "orders_qty_chk";`); + expect(up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_qty_chk" CHECK (qty >= 1);`); }); test("create-table on empty actual inlines the check (no separate ADD CONSTRAINT)", async () => { // a brand-new table carries its checks inline in CREATE TABLE; diffTableChecks diff --git a/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts b/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts index df397c12b3..db3b0c7148 100644 --- a/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts +++ b/server/typescript/packages/migrate-ts/test/check/emit-postgres-check.test.ts @@ -15,10 +15,9 @@ describe("emit postgres — checks", () => { const r = emit([{ kind: "create-table", table, status: ALLOWED } as unknown as Change], { dialect: "postgres" }); expect(r.up).toContain(`CONSTRAINT "orders_status_chk" CHECK (status IN ('OPEN','CLOSED'))`); }); - test("add-check → ALTER TABLE ADD CONSTRAINT … NOT VALID, then VALIDATE; down drops it", () => { + test("add-check → ALTER TABLE ADD CONSTRAINT; down drops it", () => { const r = emit([{ kind: "add-check", table: "orders", check: CHK, status: ALLOWED } as unknown as Change], { dialect: "postgres" }); - expect(r.up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_status_chk" CHECK (status IN ('OPEN','CLOSED')) NOT VALID;`); - expect(r.up).toContain(`ALTER TABLE "orders" VALIDATE CONSTRAINT "orders_status_chk";`); + expect(r.up).toContain(`ALTER TABLE "orders" ADD CONSTRAINT "orders_status_chk" CHECK (status IN ('OPEN','CLOSED'));`); expect(r.down).toContain(`ALTER TABLE "orders" DROP CONSTRAINT "orders_status_chk";`); }); test("drop-check → ALTER TABLE DROP CONSTRAINT", () => { diff --git a/server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts b/server/typescript/packages/migrate-ts/test/unit/check-redundant.test.ts similarity index 63% rename from server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts rename to server/typescript/packages/migrate-ts/test/unit/check-redundant.test.ts index 0406d63c73..047bc1436d 100644 --- a/server/typescript/packages/migrate-ts/test/unit/check-redundant-and-not-valid.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/check-redundant.test.ts @@ -1,20 +1,17 @@ /** - * CHECK constraints the schema already guarantees, and CHECKs added to a table that holds rows. + * CHECK constraints the schema already guarantees. * * - `skipRedundantChecks` on the schema conventions (on in the efcore preset, off by default so * nothing changes for an existing project): a `validator.length` bound the column's * VARCHAR(n) already enforces, and a minimum of 0 (always true), emit nothing; the rest of * the check stands. - * - Postgres: a CHECK added to an EXISTING table is `ADD CONSTRAINT … NOT VALID` then - * `VALIDATE CONSTRAINT` — the same end state, a lighter lock while adding, and a violating - * row fails at a named validation step. A CHECK inside a CREATE TABLE is unchanged. + * - Not on SQLite / D1, which accept a declared length and store longer values anyway: there + * the length CHECK is the only thing enforcing it. */ import { describe, test, expect } from "bun:test"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildExpectedSchema } from "../../src/expected-schema.js"; import { defaultConventions, efcoreConventions } from "../../src/schema-conventions.js"; -import { diff } from "../../src/diff/index.js"; -import { emit } from "../../src/emit/index.js"; async function root(lengthValidator: Record, maxLength?: number) { const doc = { "metadata.root": { package: "acme", children: [ @@ -57,23 +54,10 @@ describe("redundant CHECKs", () => { expect(checksOf(buildExpectedSchema(await root({ "@max": 2 }), { conventions: efcoreConventions }))) .toEqual(['length("code") <= 2']); }); -}); - -describe("a CHECK added to an existing table", () => { - test("Postgres: NOT VALID, then VALIDATE CONSTRAINT; the down drops it", async () => { - const withCheck = buildExpectedSchema(await root({ "@max": 2 }, 3)); - const before = structuredClone(withCheck); - before.tables[0]!.checks = []; - const { changes } = await diff(withCheck, before, { dialect: "postgres" }); - const { up, down } = emit(changes, { dialect: "postgres" }); - expect(up).toContain('ALTER TABLE "tickets" ADD CONSTRAINT "tickets_code_length_chk" CHECK (length("code") <= 2) NOT VALID;'); - expect(up).toContain('ALTER TABLE "tickets" VALIDATE CONSTRAINT "tickets_code_length_chk";'); - expect(down).toContain('ALTER TABLE "tickets" DROP CONSTRAINT "tickets_code_length_chk";'); - }); - test("Postgres: a CHECK inside CREATE TABLE is unchanged (no NOT VALID)", async () => { - const s = buildExpectedSchema(await root({ "@max": 2 }, 3)); - const { changes } = await diff(s, { tables: [], views: [] } as never, { dialect: "postgres" }); - expect(emit(changes, { dialect: "postgres" }).up).not.toContain("NOT VALID"); + test("efcore on SQLite: the length check stays, since SQLite does not enforce VARCHAR(n)", async () => { + const r = await root({ "@min": 0, "@max": 3 }, 3); + expect(checksOf(buildExpectedSchema(r, { conventions: efcoreConventions, dialect: "sqlite" }))) + .toEqual(['length("code") <= 3']); }); }); From a488c9342c36672a833ce3f6f76f812879b7a358 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 14:30:08 -0500 Subject: [PATCH 022/267] fix(prerelease): in-place edits that work on macOS sed The NuGet, Python and Maven repins ran `sed -i -E`. BSD sed (macOS) takes the -E as -i's backup suffix, so it left `-E` copies behind and ran the expression as a basic regex whose groups do not capture: on a Mac, `link` failed outright. They now go through `sed_inplace`, which uses the attached `-i.suffix` form GNU and BSD sed both accept and removes the backup. prerelease.mjs's Java version bump is done in JS instead of `sed -i`. The test gains a check that no backup files are left, and its trailing- newline precondition no longer trips over BSD `wc -l`'s padded output. On macOS the old script fails the test; the new one passes all 95 checks. Co-Authored-By: Claude Opus 5.5 --- scripts/prerelease.mjs | 6 +++++- tools/prerelease/prerelease-link.sh | 16 ++++++++++++---- tools/prerelease/test-prerelease-link.sh | 4 +++- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/scripts/prerelease.mjs b/scripts/prerelease.mjs index ea129bfe49..db5c71a18f 100644 --- a/scripts/prerelease.mjs +++ b/scripts/prerelease.mjs @@ -395,7 +395,11 @@ if (wants("java")) { "examples/showcase/jvm/pom.xml", ]; touch(...poms); - await run(`sed -i 's/${javaReleased.replace(/\./g, "\\.")}/${V.maven}/g' ${poms.map((f) => `'${f}'`).join(" ")}`); + // In JS rather than `sed -i`, whose in-place flag GNU and BSD (macOS) sed spell differently. + for (const f of poms) { + const path = join(ROOT, f); + writeFileSync(path, readFileSync(path, "utf8").replaceAll(javaReleased, V.maven)); + } await run("scripts/check-pom-versions.sh"); ok(`java poms → ${V.maven}`); const settings = join(scratch("m2"), "settings.xml"); diff --git a/tools/prerelease/prerelease-link.sh b/tools/prerelease/prerelease-link.sh index 9e19558d37..dae092745a 100755 --- a/tools/prerelease/prerelease-link.sh +++ b/tools/prerelease/prerelease-link.sh @@ -180,10 +180,18 @@ had_newline() { ends_in_newline "$1" && echo 1 || echo 0; } # awk's `print` unconditionally terminates the last line with a newline, even when the file # being rewritten had none — so a no-op "link, then unlink" round trip left every pom.xml that # lacked a trailing newline with one, which `git status` then reported as modified. sed -# does not have this problem (verified: `sed -i` preserves a missing trailing newline whether +# does not have this problem (verified: `sed_inplace` below preserves a missing trailing newline whether # or not anything matched), so only the awk call sites route through this. is # `had_newline` captured on immediately before the awk call that produced ; a # caller that already knows nothing needs preserving can pass "1", which is a no-op here. +# In-place extended-regex sed that works on GNU and BSD (macOS) sed alike. Both accept the +# backup suffix only ATTACHED to -i (-i.suffix); a bare `-i -E` makes BSD sed take "-E" as the +# suffix, leaving -E behind and running the expression as a basic regex, whose ( ) groups +# do not capture. Neither sed adds a missing trailing newline here (verified on both). +sed_inplace() { # sed_inplace + sed -E -i.mo-sed-bak "$1" "$2" && rm -f "$2.mo-sed-bak" +} + finish_rewrite() { # finish_rewrite local f="$1" tmp="$2" had="$3" mv "$tmp" "$f" @@ -443,7 +451,7 @@ repin_py() { # repin_py while IFS= read -r root; do for f in "$root/pyproject.toml" "$root"/requirements*.txt "$root"/constraints*.txt; do [ -f "$f" ] || continue - sed -i -E "s/(${PY_DIST}[[:space:]]*)(==|>=|~=)[[:space:]]*[0-9][^\"',[:space:]]*/\\1==${pv}/g" "$f" + sed_inplace "s/(${PY_DIST}[[:space:]]*)(==|>=|~=)[[:space:]]*[0-9][^\"',[:space:]]*/\\1==${pv}/g" "$f" done done < <( { echo "$PROJECT"; py_roots; } | sort -u) say "repinned $PY_DIST to $pv" @@ -452,7 +460,7 @@ repin_py() { # repin_py repin_nuget() { # repin_nuget local v="$1"; [ -n "$v" ] || return 0 while IFS= read -r f; do - sed -i -E "s|(]*Include=\"${NUGET_PREFIX}[^\"]*\"[^>]*Version=\")[^\"]*(\")|\\1${v}\\2|g" "$f" + sed_inplace "s|(]*Include=\"${NUGET_PREFIX}[^\"]*\"[^>]*Version=\")[^\"]*(\")|\\1${v}\\2|g" "$f" done < <(project_find \( -name '*.csproj' -o -name '*.fsproj' -o -name 'Directory.Packages.props' \) \ -not -path '*/obj/*' -not -path '*/bin/*') say "repinned ${NUGET_PREFIX}* package references to $v" @@ -486,7 +494,7 @@ repin_pom() { # repin_pom if grep -q '' "$pom"; then local before after before="$(cat "$pom")" - sed -i -E "s|()[^<]*()|\\1${mv}\\2|g" "$pom" + sed_inplace "s|()[^<]*()|\\1${mv}\\2|g" "$pom" after="$(cat "$pom")" # Only when the property's value actually changed — a second `link` at the same version # (or a pom already pinned to $mv) must not claim a repin that did not happen. diff --git a/tools/prerelease/test-prerelease-link.sh b/tools/prerelease/test-prerelease-link.sh index 040b5dbfbc..c0578b6cc0 100755 --- a/tools/prerelease/test-prerelease-link.sh +++ b/tools/prerelease/test-prerelease-link.sh @@ -329,6 +329,8 @@ check "a literal dependency version is repinned" 'grep -q "8.1.0-rc.90.61.0" "$poly/ports/kotlin/pom.xml" && grep -q "2.0.21" "$poly/ports/kotlin/pom.xml"' check "every metaobjects version in the pom is repinned, a plugin's after its configuration included" '[ "$(grep -c "8.1.0-rc.9" "$poly/ports/kotlin/pom.xml")" = 3 ] && ! grep -q "8.0.9" "$poly/ports/kotlin/pom.xml"' check "the package reference is repinned" 'grep -q "Version=\"1.1.0-rc.9\"" "$poly/ports/csharp/App.csproj"' +check "the in-place repins leave no sed backup files (BSD sed reads a bare -i -E as suffix -E)" \ + '[ -z "$(find "$poly" \( -name "*-E" -o -name "*.mo-sed-bak" \) -print)" ]' check "the local tool manifest is repinned" 'grep -q "\"metaobjects.cli\": { \"version\": \"1.1.0-rc.9\"" "$poly/.config/dotnet-tools.json"' check "another tool in the manifest is left alone" 'grep -q "\"dotnet-ef\": { \"version\": \"8.0.0\"" "$poly/.config/dotnet-tools.json"' # R3: a second `link` at the same version changes no pom, so it reports no repin, a pom pinned @@ -372,7 +374,7 @@ printf '%s' ' ' > "$mvnproj/app/pom.xml" check "the fixture poms have no trailing newline" \ - '[ "$(tail -c1 "$mvnproj/pom.xml" | wc -l)" = 0 ] && [ "$(tail -c1 "$mvnproj/app/pom.xml" | wc -l)" = 0 ]' + '[ "$(tail -c1 "$mvnproj/pom.xml" | wc -l | tr -d " ")" = 0 ] && [ "$(tail -c1 "$mvnproj/app/pom.xml" | wc -l | tr -d " ")" = 0 ]' git init -q "$mvnproj" git -C "$mvnproj" add -A && git -C "$mvnproj" commit -q -m init cp "$mvnproj/pom.xml" "$WORK/pom.xml.orig" From 1a0d3ba8dbd402fabfe5d5f2ec94f0aafcb5d069 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Mon, 2 Nov 2026 21:19:21 -0500 Subject: [PATCH 023/267] feat(schema): CHECK names, conditions and "exactly one" from validators The CHECK-generating validators (numeric, length, regex, comparison, requiredWhen, presentIff, atLeastOne) and field.enum take an optional db-provider @constraintName that names their CHECK. The cross-field validators take an optional @condition expression that guards the CHECK, and atLeastOne takes @max, so @max 1 is "exactly one". An unknown field in @condition and an atLeastOne @max below 1 or above its field count are load errors in every port. All additions are optional: a model that sets none of them generates the CHECKs it did before. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 9 ++ docs/CONFORMANCE.md | 6 +- docs/features/migrations-and-drift.md | 35 +++++ examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 15 ++ .../input/meta.checks.json | 48 +++++++ .../expected-errors.json | 15 ++ .../input/meta.checks.json | 53 +++++++ .../expected.json | 133 ++++++++++++++++++ .../input/meta.checks.json | 131 +++++++++++++++++ fixtures/metamodel-docs/expected/providers.md | 17 ++- .../metamodel-docs/expected/types/field.md | 1 + .../expected/types/validator.md | 12 ++ .../registry-conformance/coverage-report.json | 15 +- .../expected-registry.json | 91 ++++++++++++ fixtures/registry-conformance/providers.json | 10 +- .../Core/Attr/ExpressionGrammar.cs | 17 +++ .../Core/Validator/ValidatorConstants.cs | 13 ++ .../Core/Validator/ValidatorSchema.cs | 11 ++ .../MetaObjects/Loader/MetaDataLoader.cs | 1 + .../MetaObjects/Loader/ValidationPasses.cs | 56 ++++++++ .../MetaObjects/Persistence/Db/DbProvider.cs | 14 ++ .../MetaObjects/Persistence/Db/DbSchema.cs | 14 ++ .../csharp/MetaObjects/SpecMetamodel/db.json | 14 ++ .../MetaObjects/SpecMetamodel/validator.json | 13 +- .../database/CoreDBMetaDataProvider.java | 20 ++- .../metaobjects/loader/ValidationPhase.java | 58 ++++++++ .../validator/AtLeastOneValidator.java | 2 + .../validator/ComparisonValidator.java | 2 + .../metaobjects/validator/MetaValidator.java | 6 + .../validator/PresentIffValidator.java | 2 + .../validator/RequiredWhenValidator.java | 2 + server/python/src/metaobjects/core_types.py | 7 + .../metaobjects/loader/validation_passes.py | 64 +++++++++ .../core/validator/validator_constants.py | 11 ++ .../meta/persistence/db/db_provider.py | 37 ++++- .../src/metaobjects/spec_metamodel/db.json | 14 ++ .../metaobjects/spec_metamodel/validator.json | 13 +- .../src/core/validator/validator-constants.ts | 12 ++ .../validator-definition.embedded.ts | 40 ++++++ .../typescript/packages/metadata/src/index.ts | 1 + .../metadata/src/loader/meta-data-loader.ts | 5 +- .../metadata/src/loader/validation-passes.ts | 61 ++++++++ .../persistence/db/db-definition.embedded.ts | 36 +++++ .../field-definition-completeness.test.ts | 7 +- .../validator-definition-completeness.test.ts | 5 + .../migrate-ts/src/check-expression.ts | 90 ++++++++++++ .../migrate-ts/src/expected-schema.ts | 52 ++++++- .../unit/cross-field-check-extensions.test.ts | 73 ++++++++++ site-reference/providers.html | 17 ++- site-reference/types/field.html | 9 ++ site-reference/types/validator.html | 108 ++++++++++++++ spec/metamodel/db.json | 14 ++ spec/metamodel/validator.json | 13 +- 55 files changed, 1480 insertions(+), 49 deletions(-) create mode 100644 fixtures/conformance/error-validator-at-least-one-max/expected-errors.json create mode 100644 fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json create mode 100644 fixtures/conformance/error-validator-condition-unknown-field/expected-errors.json create mode 100644 fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json create mode 100644 fixtures/conformance/validator-constraint-name-condition-max/expected.json create mode 100644 fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json create mode 100644 server/typescript/packages/migrate-ts/src/check-expression.ts create mode 100644 server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts diff --git a/AGENTS.md b/AGENTS.md index 4a2a388fbc..02dec857e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (430 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (433 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index a38579d6e4..0e085f0094 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,15 @@ here.** ### Added +- **CHECK names, conditions and "exactly one" from validators.** `@constraintName` on any + `validator.*` node, and on a `field.enum` for its membership CHECK, names the CHECK `meta migrate` + generates, for a database whose CHECKs were named by hand. A cross-field validator + (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) takes `@condition`, an expression over + the entity's fields, so the rule holds only where it does. `validator.atLeastOne` takes `@max`; + `@max: 1` is exactly one of its `@fields`. All three are database-only and optional; a model + without them generates what it did. A `@condition` naming a field the entity does not have, or a + `@max` outside 1 to the number of `@fields`, is refused at load (`ERR_BAD_ATTR_VALUE`) in every + port. See `docs/features/migrations-and-drift.md`, "CHECKs from validators". - **Contract emitters: JSON Schema and OpenAPI generators (FR-022).** `jsonSchemaFile()` (`contract-schema`) writes JSON Schema 2020-12 for each object's read, create and update shapes, and a strict structured-output subset with `profile: "strict"`. `openApiFile()` (`openapi`) writes one diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 022c7d60bd..2bd138db15 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 430 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 433 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -286,7 +286,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (430) +### `fixtures/conformance/` — metamodel loader + canonical serializer (433) | Fixture prefix | Feature doc | |---|---| @@ -612,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 430 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 433 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 656b53d030..cad515937e 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -409,6 +409,41 @@ opened by an older SQLite (Python 3.10's stdlib, Ubuntu 22.04's `sqlite3`). The behind `--allow drop-check` and raises no data hazard, because the rule is the same — and the re-diff is empty afterwards. Postgres keeps `IS [NOT] DISTINCT FROM`. +### CHECKs from validators: names, conditions, how many + +A `validator.*` node and a `field.enum`'s member list each become a CHECK constraint. Three +attributes shape it, all database-only (no generated code reads them): + +- **`@constraintName`** names the CHECK, for a database whose CHECKs were named by hand. On any + `validator.*` node, and on a `field.enum` for its membership CHECK. Absent, the name is derived + (`
    ___chk`, `
    __chk` for an enum), as before. +- **`@condition`** on a cross-field validator (`comparison`, `requiredWhen`, `presentIff`, + `atLeastOne`) is an expression, in the grammar `origin.computed` uses, over the entity's fields. + The rule holds only where the condition does: the CHECK is `(NOT condition) OR (rule)`, with + the negation folded in (`kind = 'Clinic'` becomes `kind <> 'Clinic'`). A field the condition + names that is not a field of the entity is refused at load (`ERR_BAD_ATTR_VALUE`). +- **`@max`** on `validator.atLeastOne` caps how many of its `@fields` may be present. `@max: 1` + is "exactly one": `num_nonnulls(a, b) = 1` on Postgres, a sum of `IS NOT NULL` tests on SQLite. + It must be between 1 and the number of `@fields` (`ERR_BAD_ATTR_VALUE`). + +```json +{ "object.entity": { "name": "Note", "children": [ + { "source.rdb": { "@table": "Notes" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["Owned", "Shared"], "@constraintName": "CK_Notes_Kind" } }, + { "field.long": { "name": "patientId" } }, + { "field.long": { "name": "caseId" } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } }, + { "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1, + "@constraintName": "CK_Notes_Owner", + "@condition": { "op": "eq", "left": { "field": "kind" }, "right": { "value": "Owned" } } } } +] } } +``` + +On Postgres the last one is `CK_Notes_Owner CHECK (("kind" <> 'Owned') OR (num_nonnulls("patient_id", "case_id") = 1))`. + +Renaming a CHECK this way is a drop and an add of the same rule, under `--allow drop-check`. + ## Schema conventions: names for objects no code addresses Some database objects have names that no program ever reads: a primary-key constraint, most diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 04ce69cce6..e38fa75291 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 430, + "fixtures": 433, "corpora": 36, "baseTypes": 17 }, diff --git a/fixtures/conformance/error-validator-at-least-one-max/expected-errors.json b/fixtures/conformance/error-validator-at-least-one-max/expected-errors.json new file mode 100644 index 0000000000..a9b446bf90 --- /dev/null +++ b/fixtures/conformance/error-validator-at-least-one-max/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json b/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json new file mode 100644 index 0000000000..973d719d09 --- /dev/null +++ b/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json @@ -0,0 +1,48 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { + "source.rdb": {} + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id" + } + }, + { + "validator.atLeastOne": { + "name": "oneSource", + "@fields": [ + "patientId", + "caregiverId" + ], + "@max": 3 + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-validator-condition-unknown-field/expected-errors.json b/fixtures/conformance/error-validator-condition-unknown-field/expected-errors.json new file mode 100644 index 0000000000..a9b446bf90 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-unknown-field/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[5]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json b/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json new file mode 100644 index 0000000000..7b1c87b8db --- /dev/null +++ b/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json @@ -0,0 +1,53 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { + "source.rdb": {} + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id" + } + }, + { + "validator.atLeastOne": { + "name": "oneSource", + "@fields": [ + "patientId", + "caregiverId" + ], + "@condition": { + "op": "isNotNull", + "arg": { + "field": "nosuch" + } + } + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/validator-constraint-name-condition-max/expected.json b/fixtures/conformance/validator-constraint-name-condition-max/expected.json new file mode 100644 index 0000000000..bce39ccc29 --- /dev/null +++ b/fixtures/conformance/validator-constraint-name-condition-max/expected.json @@ -0,0 +1,133 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "OfficeHours", + "children": [ + { + "source.rdb": { + "@table": "OfficeHours" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "kind", + "@constraintName": "CK_OfficeHours_Kind", + "@values": [ + "Clinic", + "Phone" + ] + } + }, + { + "field.int": { + "name": "startDay", + "children": [ + { + "validator.numeric": { + "name": "weekday", + "@constraintName": "CK_OfficeHours_StartDay", + "@max": 6, + "@min": 0 + } + } + ] + } + }, + { + "field.int": { + "name": "endDay" + } + }, + { + "field.time": { + "name": "startTime" + } + }, + { + "field.time": { + "name": "endTime" + } + }, + { + "field.string": { + "name": "code", + "children": [ + { + "validator.length": { + "name": "len", + "@constraintName": "CK_OfficeHours_Code", + "@max": 8 + } + }, + { + "validator.regex": { + "name": "shape", + "@constraintName": "CK_OfficeHours_CodeShape", + "@pattern": "^[A-Z0-9]+$" + } + } + ] + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ], + "@generation": "increment" + } + }, + { + "validator.comparison": { + "name": "sameDayTimes", + "@condition": { + "op": "eq", + "left": { + "field": "startDay" + }, + "right": { + "field": "endDay" + } + }, + "@constraintName": "CK_OfficeHours_SameDayValidation", + "@left": "endTime", + "@op": "gt", + "@right": "startTime" + } + }, + { + "validator.atLeastOne": { + "name": "oneSource", + "@constraintName": "CK_OfficeHours_ExactlyOneSource", + "@fields": [ + "patientId", + "caregiverId" + ], + "@max": 1 + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json b/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json new file mode 100644 index 0000000000..89e4161635 --- /dev/null +++ b/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json @@ -0,0 +1,131 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "OfficeHours", + "children": [ + { + "source.rdb": { + "@table": "OfficeHours" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "kind", + "@values": [ + "Clinic", + "Phone" + ], + "@constraintName": "CK_OfficeHours_Kind" + } + }, + { + "field.int": { + "name": "startDay", + "children": [ + { + "validator.numeric": { + "name": "weekday", + "@min": 0, + "@max": 6, + "@constraintName": "CK_OfficeHours_StartDay" + } + } + ] + } + }, + { + "field.int": { + "name": "endDay" + } + }, + { + "field.time": { + "name": "startTime" + } + }, + { + "field.time": { + "name": "endTime" + } + }, + { + "field.string": { + "name": "code", + "children": [ + { + "validator.length": { + "name": "len", + "@max": 8, + "@constraintName": "CK_OfficeHours_Code" + } + }, + { + "validator.regex": { + "name": "shape", + "@pattern": "^[A-Z0-9]+$", + "@constraintName": "CK_OfficeHours_CodeShape" + } + } + ] + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id", + "@generation": "increment" + } + }, + { + "validator.comparison": { + "name": "sameDayTimes", + "@left": "endTime", + "@op": "gt", + "@right": "startTime", + "@constraintName": "CK_OfficeHours_SameDayValidation", + "@condition": { + "op": "eq", + "left": { + "field": "startDay" + }, + "right": { + "field": "endDay" + } + } + } + }, + { + "validator.atLeastOne": { + "name": "oneSource", + "@fields": [ + "patientId", + "caregiverId" + ], + "@max": 1, + "@constraintName": "CK_OfficeHours_ExactlyOneSource" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 3fe2e887ad..a3d721d3c1 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -44,14 +44,14 @@ Core metaobjects metamodel types and subtypes. - `template.prompt`: `@format`, `@maxChars`, `@maxTokens`, `@model`, `@owner`, `@payloadRef`, `@promptStyle`, `@requiredSlots`, `@requiredTags`, `@responseFormat`, `@responseRef`, `@since`, `@textRef` - `template.toolcall`: `@maxTokens`, `@owner`, `@payloadRef`, `@since`, `@toolName` - `validator.array`: `@max`, `@min` -- `validator.atLeastOne`: `@fields` +- `validator.atLeastOne`: `@condition`, `@fields`, `@max` - `validator.base`: `@max`, `@min` -- `validator.comparison`: `@left`, `@op`, `@right` +- `validator.comparison`: `@condition`, `@left`, `@op`, `@right` - `validator.length`: `@max`, `@min` - `validator.numeric`: `@max`, `@min` -- `validator.presentIff`: `@equals`, `@field`, `@when` +- `validator.presentIff`: `@condition`, `@equals`, `@field`, `@when` - `validator.regex`: `@max`, `@min`, `@pattern` -- `validator.requiredWhen`: `@equals`, `@field`, `@when` +- `validator.requiredWhen`: `@condition`, `@equals`, `@field`, `@when` ## metaobjects-db @@ -65,7 +65,7 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `field.date`: `@autoSet`, `@column`, `@db.indexed`, `@dbColumnType` - `field.decimal`: `@column`, `@db.indexed`, `@dbColumnType` - `field.double`: `@column`, `@db.indexed`, `@dbColumnType` -- `field.enum`: `@column`, `@db.indexed`, `@dbColumnType` +- `field.enum`: `@column`, `@constraintName`, `@db.indexed`, `@dbColumnType` - `field.float`: `@column`, `@db.indexed`, `@dbColumnType` - `field.inet`: `@column`, `@db.indexed`, `@dbColumnType` - `field.int`: `@column`, `@db.indexed`, `@dbColumnType` @@ -82,6 +82,13 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `identity.secondary`: `@expr`, `@orders`, `@using`, `@where` - `index.lookup`: `@expr`, `@orders`, `@using`, `@where` - `source.rdb`: `@function`, `@kind`, `@materializedView`, `@parameterRef`, `@proc`, `@role`, `@schema`, `@sql`, `@table`, `@unmanaged`, `@view` +- `validator.atLeastOne`: `@constraintName` +- `validator.comparison`: `@constraintName` +- `validator.length`: `@constraintName` +- `validator.numeric`: `@constraintName` +- `validator.presentIff`: `@constraintName` +- `validator.regex`: `@constraintName` +- `validator.requiredWhen`: `@constraintName` ## metaobjects-documentation diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index 45618552ec..a6181d7fde 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -230,6 +230,7 @@ String-backed enumeration constrained to a closed set of member symbols (@values | --- | --- | --- | --- | --- | --- | --- | | `@coerceDefault` | string | no | | | metaobjects-prompt | Fallback enum member used by tolerant extract when a present value cannot be coerced; must be one of the field's @values. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | | `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | diff --git a/fixtures/metamodel-docs/expected/types/validator.md b/fixtures/metamodel-docs/expected/types/validator.md index 22dfddab1c..3a2e9ce293 100644 --- a/fixtures/metamodel-docs/expected/types/validator.md +++ b/fixtures/metamodel-docs/expected/types/validator.md @@ -43,7 +43,10 @@ Cardinality of presence: at least one of the named fields (@fields) must be pres | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@fields` | string[] | yes | | | metaobjects-core-types | Names of the candidate fields; at least one must be present. | +| `@max` | int | no | | | metaobjects-core-types | The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE). | **Allowed children** @@ -80,6 +83,8 @@ Cross-field ordering: requires two sibling fields of the owning entity stand in | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@left` | string | yes | | | metaobjects-core-types | Name of the left-hand field of the owning entity. | | `@op` | string | yes | | `gt`, `gte`, `lt`, `lte`, `ne`, `eq` | metaobjects-core-types | Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=). | | `@right` | string | yes | | | metaobjects-core-types | Name of the right-hand field of the owning entity. | @@ -100,6 +105,7 @@ Bounds string length / collection size via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -119,6 +125,7 @@ Bounds a numeric value's magnitude via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -140,6 +147,8 @@ Biconditional presence: the target field (@field) is present (NOT NULL) if and o | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; @field is present exactly when @when equals this. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field whose presence is governed by the condition. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field. | @@ -160,6 +169,7 @@ Requires the value match a regular expression (@pattern). | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@pattern` | string | no | | | metaobjects-core-types | Regular expression the value must match. | @@ -198,6 +208,8 @@ One-directional conditional presence: when the gating field (@when) equals @equa | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | +| `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | +| `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; when @when equals this, @field must be present. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field that becomes required when the condition holds. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field whose value triggers the requirement. | diff --git a/fixtures/registry-conformance/coverage-report.json b/fixtures/registry-conformance/coverage-report.json index 631dfcee54..cfc33e9c8c 100644 --- a/fixtures/registry-conformance/coverage-report.json +++ b/fixtures/registry-conformance/coverage-report.json @@ -1,6 +1,6 @@ { "registeredSubTypeCount": 65, - "exercisedSubTypeCount": 53, + "exercisedSubTypeCount": 55, "untestedSubTypes": [ "attr.boolean", "attr.class", @@ -10,8 +10,6 @@ "attr.int", "attr.intMap", "attr.long", - "validator.atLeastOne", - "validator.comparison", "validator.presentIff", "validator.requiredWhen" ], @@ -73,7 +71,6 @@ "formExclude", "instruction", "mutability", - "sortable", "sortableDefaultOrder", "unique", "xmlText" @@ -121,7 +118,6 @@ "formExclude", "instruction", "mutability", - "sortable", "sortableDefaultOrder", "unique", "xmlText" @@ -148,7 +144,6 @@ { "key": "field.int", "untestedAttrs": [ - "column", "dbColumnType", "example", "formExclude", @@ -188,7 +183,6 @@ "sortable", "sortableDefaultOrder", "unique", - "valueType", "xmlText" ] }, @@ -211,7 +205,6 @@ { "key": "field.string", "untestedAttrs": [ - "formExclude", "sortableDefaultOrder", "xmlText" ] @@ -324,12 +317,6 @@ "symmetric" ] }, - { - "key": "source.rdb", - "untestedAttrs": [ - "materializedView" - ] - }, { "key": "template.output", "untestedAttrs": [ diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 3fddf47555..94c79b6d58 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1045,6 +1045,13 @@ "required": false, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "db.indexed", "valueType": "boolean", @@ -4678,12 +4685,33 @@ "rules": "@fields names two or more fields of the owning entity. Satisfied when any one of them is non-null.", "whenToUse": "At least one of several fields must be present (email or phone). Declare it instead of hand-written OR-presence checks.", "attrs": [ + { + "name": "condition", + "valueType": "expression", + "isArray": false, + "required": false, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." + }, + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "fields", "valueType": "string", "isArray": true, "required": true, "description": "Names of the candidate fields; at least one must be present." + }, + { + "name": "max", + "valueType": "int", + "isArray": false, + "required": false, + "description": "The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE)." } ], "children": [] @@ -4717,6 +4745,20 @@ "rules": "@left and @right must name fields of the owning entity. @op is one of gt/gte/lt/lte/ne/eq. The comparison is null-tolerant where the backend's relational operator is (SQL: a NULL operand yields no violation).", "whenToUse": "Two sibling fields must stand in an order (start <= end, currentHp <= maxHp). Declare it instead of hand-writing the cross-field assertion.", "attrs": [ + { + "name": "condition", + "valueType": "expression", + "isArray": false, + "required": false, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." + }, + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "left", "valueType": "string", @@ -4755,6 +4797,13 @@ "description": "Bounds string length / collection size via @min/@max.", "whenToUse": "Bound a string's length or a collection's size. Use @min/@max instead of hand-written guards.", "attrs": [ + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -4778,6 +4827,13 @@ "description": "Bounds a numeric value's magnitude via @min/@max.", "whenToUse": "Bound a number's magnitude. Use @min/@max instead of hand-written range checks.", "attrs": [ + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -4802,6 +4858,20 @@ "rules": "@field and @when must name fields of the owning entity. @equals is rendered per @when's field subtype. Stricter than requiredWhen — also forbids @field when the condition is false.", "whenToUse": "A field must be present exactly when a condition holds, absent otherwise (biconditional). Declare it instead of hand-written presence logic.", "attrs": [ + { + "name": "condition", + "valueType": "expression", + "isArray": false, + "required": false, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." + }, + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "equals", "valueType": "string", @@ -4832,6 +4902,13 @@ "description": "Requires the value match a regular expression (@pattern).", "whenToUse": "A string must match a pattern (email, slug, code). Set @pattern instead of hand-writing the regex test.", "attrs": [ + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -4871,6 +4948,20 @@ "rules": "@field and @when must name fields of the owning entity. @equals is the gating value, compared against @when's value (rendered per @when's field subtype — boolean true/false, enum/string literal, numeric literal).", "whenToUse": "A field becomes required only when another field has a given value. Declare it instead of conditional validation code.", "attrs": [ + { + "name": "condition", + "valueType": "expression", + "isArray": false, + "required": false, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." + }, + { + "name": "constraintName", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, { "name": "equals", "valueType": "string", diff --git a/fixtures/registry-conformance/providers.json b/fixtures/registry-conformance/providers.json index ee86a2fdf8..22a49da7b3 100644 --- a/fixtures/registry-conformance/providers.json +++ b/fixtures/registry-conformance/providers.json @@ -23,6 +23,7 @@ "projectsOnto": [ "field.*", "field.date", + "field.enum", "field.object", "field.time", "field.timestamp", @@ -30,7 +31,14 @@ "identity.reference", "identity.secondary", "index.lookup", - "source.rdb" + "source.rdb", + "validator.atLeastOne", + "validator.comparison", + "validator.length", + "validator.numeric", + "validator.presentIff", + "validator.regex", + "validator.requiredWhen" ] }, "metaobjects-documentation": { diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index 82b59bc3d4..aef27002ed 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -66,6 +66,23 @@ public static class ExpressionGrammar /// Structural well-formedness of an expression tree (known node kinds, ops, /// arity). Returns an empty list when valid. Mirrors TS validateExprNode. /// + /// The field names an expression tree references, in order of appearance. + public static List FieldRefs(object? node) + { + var refs = new List(); + void Walk(object? x) + { + if (x is not IReadOnlyDictionary n) return; + if (Get(n, KEY_FIELD) is string f) refs.Add(f); + Walk(Get(n, KEY_LEFT)); + Walk(Get(n, KEY_RIGHT)); + Walk(Get(n, KEY_ARG)); + if (Get(n, KEY_ARGS) is IEnumerable args) foreach (var a in args) Walk(a); + } + Walk(node); + return refs; + } + public static List ValidateExprNode(object? node) { if (node is not IReadOnlyDictionary n) diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs index 5c1e4e8892..e5e556e859 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs @@ -49,4 +49,17 @@ public static class ValidatorConstants public const string VALIDATOR_ATTR_WHEN = "when"; public const string VALIDATOR_ATTR_EQUALS = "equals"; public const string VALIDATOR_ATTR_FIELDS = "fields"; + /// comparison / requiredWhen / presentIff / atLeastOne: the case the rule applies in (an attr.expression). + public const string VALIDATOR_ATTR_CONDITION = "condition"; + /// A CHECK-generating validator (db provider): the database name of that CHECK. + public const string VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName"; + + /// The validators meta migrate renders as a CHECK (and so may carry @constraintName): + /// numeric, length, regex and the cross-field ones. required is NOT NULL; array and base have none. + public static readonly string[] CHECK_VALIDATOR_SUBTYPES = + [ + VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX, + VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, VALIDATOR_SUBTYPE_PRESENT_IFF, + VALIDATOR_SUBTYPE_AT_LEAST_ONE, + ]; } diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs index 42d3b756a3..220bd34206 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs @@ -30,6 +30,11 @@ public static class ValidatorSchema /// Attrs per validator subtype. required uses none; regex adds @pattern; /// length / numeric / array (and the base) use @min / @max. /// + /// @condition on a cross-field validator: the case the rule applies in (an attr.expression). + private static readonly AttrSchema ConditionAttr = new(Name: ValidatorConstants.VALIDATOR_ATTR_CONDITION, + ValueType: AttrConstants.ATTR_SUBTYPE_EXPRESSION, Required: false, + Description: "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself."); + public static readonly IReadOnlyDictionary> ValidatorAttrsMap = new Dictionary> { @@ -57,6 +62,7 @@ public static class ValidatorSchema Description: "Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=)."), new AttrSchema(Name: ValidatorConstants.VALIDATOR_ATTR_RIGHT, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, Description: "Name of the right-hand field of the owning entity."), + ConditionAttr, ], [ValidatorConstants.VALIDATOR_SUBTYPE_REQUIRED_WHEN] = [ @@ -66,6 +72,7 @@ public static class ValidatorSchema Required: true, Description: "Name of the gating field whose value triggers the requirement."), new AttrSchema(Name: ValidatorConstants.VALIDATOR_ATTR_EQUALS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, Description: "The gating value; when @when equals this, @field must be present."), + ConditionAttr, ], [ValidatorConstants.VALIDATOR_SUBTYPE_PRESENT_IFF] = [ @@ -75,11 +82,15 @@ public static class ValidatorSchema Required: true, Description: "Name of the gating field."), new AttrSchema(Name: ValidatorConstants.VALIDATOR_ATTR_EQUALS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, Description: "The gating value; @field is present exactly when @when equals this."), + ConditionAttr, ], [ValidatorConstants.VALIDATOR_SUBTYPE_AT_LEAST_ONE] = [ new AttrSchema(Name: ValidatorConstants.VALIDATOR_ATTR_FIELDS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, IsArray: true, Description: "Names of the candidate fields; at least one must be present."), + ConditionAttr, + new AttrSchema(Name: ValidatorConstants.VALIDATOR_ATTR_MAX, ValueType: AttrConstants.ATTR_SUBTYPE_INT, + Required: false, Description: "The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE)."), ], }; } diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index b2ea908026..2d8d311a12 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -538,6 +538,7 @@ public LoadResult Load(IReadOnlyList sources) errors.AddRange(ValidationPasses.ValidateFieldMap(root)); errors.AddRange(ValidationPasses.ValidateEnumMaxLength(root)); errors.AddRange(ValidationPasses.ValidateIdentitySequence(root)); + errors.AddRange(ValidationPasses.ValidateCrossFieldValidators(root)); // Pass 9: template @payloadRef / @requiredSlots resolution errors.AddRange(ValidationPasses.ValidateTemplatePayloadRefs(root)); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 51a575382c..85f2480578 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2106,6 +2106,62 @@ private static void ValidateAttrSchemaNode( // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the // identity that declares one of them. Mirrors TS validateIdentitySequence. // --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the + // database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, and + // every field a @condition names a field of the owning entity (ERR_BAD_ATTR_VALUE). Read + // RESOLVING (ADR-0039). Mirrors TS validateCrossFieldValidators. + // --------------------------------------------------------------------------- + private static readonly HashSet CrossFieldValidatorSubtypes = new(StringComparer.Ordinal) + { + VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, + VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE, + }; + + public static IReadOnlyList ValidateCrossFieldValidators(MetaData root) + { + var errors = new List(); + foreach (var obj in root.Children().OfType()) + { + var fieldNames = obj.Fields().Select(f => f.Name).ToHashSet(StringComparer.Ordinal); + foreach (var v in obj.OwnChildren().Where(c => c.Type == TYPE_VALIDATOR && CrossFieldValidatorSubtypes.Contains(c.SubType))) + { + if (v.SubType == VALIDATOR_SUBTYPE_AT_LEAST_ONE && v.Attr(VALIDATOR_ATTR_MAX) is long max) + { + var fields = v.Attr(VALIDATOR_ATTR_FIELDS) switch + { + string s => 1, + IReadOnlyList ss => ss.Count, + IReadOnlyList os => os.Count, + _ => 0, + }; + if (max < 1 || max > fields) + { + errors.Add(new MetaError( + $"validator.atLeastOne \"{obj.Name}.{v.Name}\" @max {max} must be between 1 and the number of its @fields ({fields}).", + ErrorCode.ERR_BAD_ATTR_VALUE, + Envelope: v.Source)); + continue; + } + } + var condition = v.Attr(VALIDATOR_ATTR_CONDITION); + if (condition is null) continue; + var unknown = MetaObjects.Core.Attr.ExpressionGrammar.FieldRefs(condition) + .Distinct(StringComparer.Ordinal).Where(f => !fieldNames.Contains(f)) + .OrderBy(f => f, StringComparer.Ordinal).ToList(); + if (unknown.Count > 0) + { + errors.Add(new MetaError( + $"validator.{v.SubType} \"{obj.Name}.{v.Name}\" @condition names {string.Join(", ", unknown.Select(f => $"\"{f}\""))}, " + + $"which {(unknown.Count == 1 ? "is not a field" : "are not fields")} of \"{obj.Name}\".", + ErrorCode.ERR_BAD_ATTR_VALUE, + Envelope: v.Source)); + } + } + } + return errors; + } + public static IReadOnlyList ValidateIdentitySequence(MetaData root) { var errors = new List(); diff --git a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs index fa00eca507..300a7dc76c 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs @@ -52,6 +52,20 @@ public void RegisterTypes(TypeRegistry registry) FieldConstants.FIELD_SUBTYPE_TIMESTAMP, attributes: [DbSchema.LocalTimeSchema]); + // @constraintName: the database name of the CHECK a field.enum's member list, and a + // CHECK-generating validator, generates — db.json's field.enum and validator extends blocks. + registry.Extend( + MetaObjects.Shared.BaseTypes.TYPE_FIELD, + FieldConstants.FIELD_SUBTYPE_ENUM, + attributes: [DbSchema.EnumConstraintNameSchema]); + foreach (string subType in Core.Validator.ValidatorConstants.CHECK_VALIDATOR_SUBTYPES) + { + registry.Extend( + MetaObjects.Shared.BaseTypes.TYPE_VALIDATOR, + subType, + attributes: [DbSchema.ValidatorConstraintNameSchema]); + } + // @flattenedColumnPrefix is field.object-ONLY (the flattened-member column prefix), mirroring // db.json's field.object extends block. registry.Extend( diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index 96be31247f..7a13df2191 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -104,6 +104,20 @@ public static class DbSchema Required: false, Description: "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider."); + /// @constraintName on a validator — the database name of the CHECK it generates. + public static readonly AttrSchema ValidatorConstraintNameSchema = new AttrSchema( + Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_CONSTRAINT_NAME, + ValueType: AttrConstants.ATTR_SUBTYPE_STRING, + Required: false, + Description: "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider."); + + /// @constraintName on a field.enum — the database name of its membership CHECK. + public static readonly AttrSchema EnumConstraintNameSchema = new AttrSchema( + Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_CONSTRAINT_NAME, + ValueType: AttrConstants.ATTR_SUBTYPE_STRING, + Required: false, + Description: "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider."); + /// @sequenceStart — the first value of an increment key's sequence; on identity.primary. public static readonly AttrSchema SequenceStartSchema = new AttrSchema( Name: DbConstants.IDENTITY_ATTR_SEQUENCE_START, diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index 79734985ba..e1d1cb0327 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -59,6 +59,20 @@ { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } ] }, + { + "type": "field", + "subType": "enum", + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "validator", + "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + ] + }, { "type": "identity", "subType": "primary", diff --git a/server/csharp/MetaObjects/SpecMetamodel/validator.json b/server/csharp/MetaObjects/SpecMetamodel/validator.json index 9520605bd7..43a306ddc3 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/validator.json +++ b/server/csharp/MetaObjects/SpecMetamodel/validator.json @@ -66,7 +66,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "left", "min": 1, "max": 1, "description": "Name of the left-hand field of the owning entity." }, { "type": "attr", "subType": "string", "name": "op", "min": 1, "max": 1, "allowedValues": ["gt", "gte", "lt", "lte", "ne", "eq"], "description": "Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=)." }, - { "type": "attr", "subType": "string", "name": "right", "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." } + { "type": "attr", "subType": "string", "name": "right", "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -78,7 +79,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "field", "min": 1, "max": 1, "description": "Name of the field that becomes required when the condition holds." }, { "type": "attr", "subType": "string", "name": "when", "min": 1, "max": 1, "description": "Name of the gating field whose value triggers the requirement." }, - { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." } + { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -90,7 +92,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "field", "min": 1, "max": 1, "description": "Name of the field whose presence is governed by the condition." }, { "type": "attr", "subType": "string", "name": "when", "min": 1, "max": 1, "description": "Name of the gating field." }, - { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." } + { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -100,7 +103,9 @@ "whenToUse": "At least one of several fields must be present (email or phone). Declare it instead of hand-written OR-presence checks.", "rules": "@fields names two or more fields of the owning entity. Satisfied when any one of them is non-null.", "children": [ - { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." } + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." }, + { "type": "attr", "subType": "int", "name": "max", "min": 0, "max": 1, "description": "The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE)." } ] } ] diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java index 3bf3898bcf..f16630f29c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java @@ -1,6 +1,7 @@ package com.metaobjects.database; import com.metaobjects.attr.StringAttribute; +import java.util.List; import com.metaobjects.index.Index; import com.metaobjects.identity.SecondaryIdentity; import com.metaobjects.registry.MetaDataRegistry; @@ -116,7 +117,7 @@ public String getProviderId() { @Override public String[] getDependencies() { // Depends on field types, object types, identity types, and index types so it loads after them. - return new String[]{"field-types", "object-types", "identity-types", "index-types"}; + return new String[]{"field-types", "object-types", "identity-types", "index-types", "validator-types"}; } @Override @@ -148,6 +149,23 @@ public void registerTypes(MetaDataRegistry registry) { .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); }); + // --- @constraintName: the CHECK name of a CHECK-generating validator, and of a --- + // field.enum's membership (db.json's validator and field.enum blocks; identity.reference + // declares its own). required is NOT NULL; array and base generate no CHECK. + for (Class c : List.of( + com.metaobjects.validator.LengthValidator.class, + com.metaobjects.validator.RegexValidator.class, + com.metaobjects.validator.NumericValidator.class, + com.metaobjects.validator.ComparisonValidator.class, + com.metaobjects.validator.RequiredWhenValidator.class, + com.metaobjects.validator.PresentIffValidator.class, + com.metaobjects.validator.AtLeastOneValidator.class, + com.metaobjects.field.EnumField.class)) { + registry.extendType(c, def -> def + .optionalAttributeWithConstraints(com.metaobjects.validator.MetaValidator.ATTR_CONSTRAINT_NAME) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle()); + } + // --- index.lookup RDB-physical attrs --- registry.extendType(com.metaobjects.index.LookupIndex.class, def -> { diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index fe9f80fa28..6acaa3d171 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -264,6 +264,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { pass(collected, () -> validateObjectFieldStorage(root)); validateEnumMaxLength(root, collected); validateIdentitySequence(root, collected); + validateCrossFieldValidators(root, collected); pass(collected, () -> validateFieldMap(root)); pass(collected, () -> validateIdentityFieldsAndGeneration(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). @@ -2388,6 +2389,63 @@ private static List junctionReferenceFkFields(MetaObject junction) { // identity that declares one of them, every offender collected. Mirrors TS. // ========================================================================= + // Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the + // database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, and + // every field a @condition names a field of the owning entity (ERR_BAD_ATTR_VALUE). Every + // violation is collected. Mirrors TS validateCrossFieldValidators. + static void validateCrossFieldValidators(MetaRoot root, List out) { + java.util.Set crossField = java.util.Set.of( + com.metaobjects.validator.ComparisonValidator.SUBTYPE_COMPARISON, + com.metaobjects.validator.RequiredWhenValidator.SUBTYPE_REQUIRED_WHEN, + com.metaobjects.validator.PresentIffValidator.SUBTYPE_PRESENT_IFF, + com.metaobjects.validator.AtLeastOneValidator.SUBTYPE_AT_LEAST_ONE); + for (MetaObject obj : root.getChildren(MetaObject.class, false)) { + java.util.Set fieldNames = new java.util.HashSet<>(); + for (com.metaobjects.field.MetaField f : obj.getMetaFields()) fieldNames.add(f.getShortName()); + for (com.metaobjects.validator.MetaValidator v + : obj.getChildren(com.metaobjects.validator.MetaValidator.class, false)) { + if (!crossField.contains(v.getSubType())) continue; + String label = v.getSubType() + " \"" + obj.getShortName() + "." + v.getShortName() + "\""; + if (com.metaobjects.validator.AtLeastOneValidator.SUBTYPE_AT_LEAST_ONE.equals(v.getSubType()) + && v.hasMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_MAX) + && v.getMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_MAX).getValue() instanceof Number n) { + long max = n.longValue(); + Object raw = v.hasMetaAttr(com.metaobjects.validator.AtLeastOneValidator.ATTR_FIELDS) + ? v.getMetaAttr(com.metaobjects.validator.AtLeastOneValidator.ATTR_FIELDS).getValue() : null; + int count = raw instanceof java.util.Collection c ? c.size() : raw == null ? 0 : 1; + if (max < 1 || max > count) { + out.add(new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @max " + max + + " must be between 1 and the number of its @fields (" + count + ").", + ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); + continue; + } + } + if (!v.hasMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION)) continue; + java.util.TreeSet unknown = new java.util.TreeSet<>(); + collectExprFieldRefs(v.getMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION).getValue(), unknown); + unknown.removeAll(fieldNames); + if (unknown.isEmpty()) continue; + StringBuilder names = new StringBuilder(); + for (String u : unknown) names.append(names.length() == 0 ? "" : ", ").append('"').append(u).append('"'); + out.add(new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @condition names " + names + + ", which " + (unknown.size() == 1 ? "is not a field" : "are not fields") + + " of \"" + obj.getShortName() + "\".", + ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); + } + } + } + + /** The field names an expression tree (ExpressionAttribute's Map form) references. */ + private static void collectExprFieldRefs(Object node, java.util.Set out) { + if (node instanceof java.util.Map m) { + if (m.get("field") instanceof String f) out.add(f); + for (String k : List.of("left", "right", "arg")) collectExprFieldRefs(m.get(k), out); + if (m.get("args") instanceof java.util.Collection args) for (Object a : args) collectExprFieldRefs(a, out); + } + } + static void validateIdentitySequence(MetaRoot root, List out) { for (MetaObject obj : root.getChildren(MetaObject.class, false)) { for (com.metaobjects.identity.PrimaryIdentity id diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/AtLeastOneValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/AtLeastOneValidator.java index ea7ceea0c4..be5aaae941 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/AtLeastOneValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/AtLeastOneValidator.java @@ -42,6 +42,8 @@ public static void registerTypes(MetaDataRegistry registry) { .inheritsFrom(TYPE_VALIDATOR, SUBTYPE_BASE); def.requiredAttributeWithConstraints(ATTR_FIELDS).ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints(ATTR_CONDITION) + .ofType(com.metaobjects.attr.ExpressionAttribute.SUBTYPE_EXPRESSION).asSingle(); }); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/ComparisonValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/ComparisonValidator.java index 82ddc56898..fee1a184c4 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/ComparisonValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/ComparisonValidator.java @@ -50,6 +50,8 @@ public static void registerTypes(MetaDataRegistry registry) { def.requiredAttributeWithConstraints(ATTR_OP).ofType(StringAttribute.SUBTYPE_STRING) .withEnum("gt", "gte", "lt", "lte", "ne", "eq"); def.requiredAttributeWithConstraints(ATTR_RIGHT).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_CONDITION) + .ofType(com.metaobjects.attr.ExpressionAttribute.SUBTYPE_EXPRESSION).asSingle(); }); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java index 656b463353..c0ba1630c3 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java @@ -43,6 +43,12 @@ public abstract class MetaValidator extends MetaData { /** Cross-port maximum-bound attribute ({@code @max}). */ public final static String ATTR_MAX = "max"; + /** A cross-field validator's @condition: the rule applies only where this expression holds. */ + public final static String ATTR_CONDITION = "condition"; + + /** The database name of the CHECK a CHECK-generating validator (or a field.enum's membership) generates. */ + public final static String ATTR_CONSTRAINT_NAME = "constraintName"; + /** * Register this type with the MetaDataRegistry (called by provider) * @param registry the MetaDataRegistry to register with diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/PresentIffValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/PresentIffValidator.java index 198bf92574..49f4cd049f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/PresentIffValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/PresentIffValidator.java @@ -50,6 +50,8 @@ public static void registerTypes(MetaDataRegistry registry) { def.requiredAttributeWithConstraints(ATTR_FIELD).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); def.requiredAttributeWithConstraints(ATTR_WHEN).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); def.requiredAttributeWithConstraints(ATTR_EQUALS).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_CONDITION) + .ofType(com.metaobjects.attr.ExpressionAttribute.SUBTYPE_EXPRESSION).asSingle(); }); } diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/RequiredWhenValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/RequiredWhenValidator.java index c4b718d2f9..689ed22cda 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/RequiredWhenValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/RequiredWhenValidator.java @@ -49,6 +49,8 @@ public static void registerTypes(MetaDataRegistry registry) { def.requiredAttributeWithConstraints(ATTR_FIELD).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); def.requiredAttributeWithConstraints(ATTR_WHEN).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); def.requiredAttributeWithConstraints(ATTR_EQUALS).ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_CONDITION) + .ofType(com.metaobjects.attr.ExpressionAttribute.SUBTYPE_EXPRESSION).asSingle(); }); } diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 5a00288a48..f2db7ca8b4 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -1078,6 +1078,8 @@ def _register_subtypes( AttrSchema(name=vc.VALIDATOR_ATTR_MIN, value_type=ATTR_SUBTYPE_INT), AttrSchema(name=vc.VALIDATOR_ATTR_MAX, value_type=ATTR_SUBTYPE_INT), ] +# A cross-field validator's optional @condition (an expression over the entity's fields). +_VALIDATOR_CONDITION_ATTR = AttrSchema(name=vc.VALIDATOR_ATTR_CONDITION, value_type=ATTR_SUBTYPE_EXPRESSION) _VALIDATOR_ATTRS_BY_SUBTYPE: dict[str, list[AttrSchema]] = { SUBTYPE_BASE: list(_VALIDATOR_MIN_MAX_ATTRS), vc.VALIDATOR_SUBTYPE_REQUIRED: [], @@ -1094,19 +1096,24 @@ def _register_subtypes( AttrSchema(name=vc.VALIDATOR_ATTR_OP, value_type=ATTR_SUBTYPE_STRING, required=True, allowed_values=("gt", "gte", "lt", "lte", "ne", "eq")), AttrSchema(name=vc.VALIDATOR_ATTR_RIGHT, value_type=ATTR_SUBTYPE_STRING, required=True), + _VALIDATOR_CONDITION_ATTR, ], vc.VALIDATOR_SUBTYPE_REQUIRED_WHEN: [ AttrSchema(name=vc.VALIDATOR_ATTR_FIELD, value_type=ATTR_SUBTYPE_STRING, required=True), AttrSchema(name=vc.VALIDATOR_ATTR_WHEN, value_type=ATTR_SUBTYPE_STRING, required=True), AttrSchema(name=vc.VALIDATOR_ATTR_EQUALS, value_type=ATTR_SUBTYPE_STRING, required=True), + _VALIDATOR_CONDITION_ATTR, ], vc.VALIDATOR_SUBTYPE_PRESENT_IFF: [ AttrSchema(name=vc.VALIDATOR_ATTR_FIELD, value_type=ATTR_SUBTYPE_STRING, required=True), AttrSchema(name=vc.VALIDATOR_ATTR_WHEN, value_type=ATTR_SUBTYPE_STRING, required=True), AttrSchema(name=vc.VALIDATOR_ATTR_EQUALS, value_type=ATTR_SUBTYPE_STRING, required=True), + _VALIDATOR_CONDITION_ATTR, ], vc.VALIDATOR_SUBTYPE_AT_LEAST_ONE: [ AttrSchema(name=vc.VALIDATOR_ATTR_FIELDS, value_type=ATTR_SUBTYPE_STRING, required=True, is_array=True), + AttrSchema(name=vc.VALIDATOR_ATTR_MAX, value_type=ATTR_SUBTYPE_INT), + _VALIDATOR_CONDITION_ATTR, ], } for _sub, _attrs in _VALIDATOR_ATTRS_BY_SUBTYPE.items(): diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 3353d3d429..bd6c444b09 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -87,6 +87,7 @@ TYPE_REQUIREMENT, TYPE_SOURCE, TYPE_TEMPLATE, + TYPE_VALIDATOR, ) from ..meta.template import template_constants as tc from ..meta.presentation.layout.layout_constants import ( @@ -253,6 +254,8 @@ def run_validations( _validate_enum_max_length(root, errors) # identity.primary @sequenceStart / @sequenceName need @generation "increment". _validate_identity_sequence(root, errors) + # cross-field validators — atLeastOne @max in range; @condition names entity fields. + _validate_cross_field_validators(root, errors) # field.map — exactly one of @valueType (scalar) or @objectRef (VO), and # @valueType (when set) must name a known scalar subtype. _validate_field_map(root, errors) @@ -3789,6 +3792,67 @@ def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None )) +# Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the +# database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, and +# every field a @condition names a field of the owning entity (ERR_BAD_ATTR_VALUE). Read +# RESOLVING (ADR-0039). Mirrors TS validateCrossFieldValidators. +def _expr_field_refs(node: object, out: set[str]) -> None: + if not isinstance(node, dict): + return + if isinstance(node.get("field"), str): + out.add(node["field"]) + for key in ("left", "right", "arg"): + _expr_field_refs(node.get(key), out) + args = node.get("args") + if isinstance(args, list): + for a in args: + _expr_field_refs(a, out) + + +def _validate_cross_field_validators(root: MetaData, errors: list[MetaError]) -> None: + from ..meta.core.validator import validator_constants as vc + + for obj in root.children(): + if obj.type != TYPE_OBJECT: + continue + field_names = {f.name for f in obj.fields()} + for v in obj.own_children(): + if v.type != TYPE_VALIDATOR or v.sub_type not in vc.CROSS_FIELD_VALIDATOR_SUBTYPES: + continue + if v.sub_type == vc.VALIDATOR_SUBTYPE_AT_LEAST_ONE: + maximum = v.get_meta_attr(vc.VALIDATOR_ATTR_MAX) + if isinstance(maximum, int) and not isinstance(maximum, bool): + fields = v.get_meta_attr(vc.VALIDATOR_ATTR_FIELDS) + count = len(fields) if isinstance(fields, list) else (0 if fields is None else 1) + if maximum < 1 or maximum > count: + errors.append(MetaError( + code=ErrorCode.ERR_BAD_ATTR_VALUE, + message=( + f'validator.atLeastOne "{obj.name}.{v.name}" @max {maximum} must be ' + f"between 1 and the number of its @fields ({count})." + ), + envelope=v.source, + )) + continue + condition = v.get_meta_attr(vc.VALIDATOR_ATTR_CONDITION) + if condition is None: + continue + refs: set[str] = set() + _expr_field_refs(condition, refs) + unknown = sorted(refs - field_names) + if unknown: + names = ", ".join(f'"{u}"' for u in unknown) + verb = "is not a field" if len(unknown) == 1 else "are not fields" + errors.append(MetaError( + code=ErrorCode.ERR_BAD_ATTR_VALUE, + message=( + f'validator.{v.sub_type} "{obj.name}.{v.name}" @condition names {names}, ' + f'which {verb} of "{obj.name}".' + ), + envelope=v.source, + )) + + # field.enum @maxLength — the column length of a string-stored enum: # 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the longest # offender named; diff --git a/server/python/src/metaobjects/meta/core/validator/validator_constants.py b/server/python/src/metaobjects/meta/core/validator/validator_constants.py index 5c16eae8b2..7509c4eef9 100644 --- a/server/python/src/metaobjects/meta/core/validator/validator_constants.py +++ b/server/python/src/metaobjects/meta/core/validator/validator_constants.py @@ -29,3 +29,14 @@ VALIDATOR_ATTR_WHEN = "when" VALIDATOR_ATTR_EQUALS = "equals" VALIDATOR_ATTR_FIELDS = "fields" +# A cross-field validator's @condition: the rule applies only where this expression holds. +VALIDATOR_ATTR_CONDITION = "condition" +# The database name of the CHECK a CHECK-generating validator generates (db provider). +VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName" +# The cross-field validators (entity-scoped; the database enforces them as CHECKs). +CROSS_FIELD_VALIDATOR_SUBTYPES = ( + VALIDATOR_SUBTYPE_COMPARISON, + VALIDATOR_SUBTYPE_REQUIRED_WHEN, + VALIDATOR_SUBTYPE_PRESENT_IFF, + VALIDATOR_SUBTYPE_AT_LEAST_ONE, +) diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index 644ba3a73d..17e1308f21 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -24,9 +24,10 @@ IDENTITY_SUBTYPE_SECONDARY, ) from ...core.index.index_constants import INDEX_SUBTYPE_LOOKUP +from ...core.validator import validator_constants as vc from ....provider import Provider from ....registry import AttrSchema, TypeRegistry -from ....shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_INDEX +from ....shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_INDEX, TYPE_VALIDATOR from .db_constants import ( FIELD_ATTR_DB_COLUMN_TYPE, FIELD_ATTR_LOCAL_TIME, @@ -186,6 +187,36 @@ ) +_ENUM_CONSTRAINT_NAME_SCHEMA = AttrSchema( + name=vc.VALIDATOR_ATTR_CONSTRAINT_NAME, + value_type=ATTR_SUBTYPE_STRING, + required=False, + description=( + "The database name of the CHECK constraint this enum's member list generates. " + "Absent:
    __chk. Lets a model adopt a database whose CHECKs were " + "named by hand. RDB-physical — contributed by the db provider." + ), +) +_VALIDATOR_CONSTRAINT_NAME_SCHEMA = AttrSchema( + name=vc.VALIDATOR_ATTR_CONSTRAINT_NAME, + value_type=ATTR_SUBTYPE_STRING, + required=False, + description=( + "The database name of the CHECK constraint this validator generates (numeric, length, " + "regex and the cross-field validators; the others generate no CHECK). Absent: the " + "derived
    ___chk. Lets a model adopt a database whose CHECKs " + "were named by hand. RDB-physical — contributed by the db provider." + ), +) +# The validators meta migrate renders as a CHECK: required is NOT NULL; array and base have none. +_VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME = ( + vc.VALIDATOR_SUBTYPE_NUMERIC, + vc.VALIDATOR_SUBTYPE_LENGTH, + vc.VALIDATOR_SUBTYPE_REGEX, + *vc.CROSS_FIELD_VALIDATOR_SUBTYPES, +) + + def _register(registry: TypeRegistry) -> None: for sub_type in _DB_FIELD_SUBTYPES: registry.extend( @@ -225,6 +256,10 @@ def _register(registry: TypeRegistry) -> None: _REFERENCE_ON_UPDATE_SCHEMA, ], ) + # @constraintName names the CHECK a validator / a field.enum's membership generates. + registry.extend(TYPE_FIELD, fc.FIELD_SUBTYPE_ENUM, attributes=[_ENUM_CONSTRAINT_NAME_SCHEMA]) + for sub_type in _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME: + registry.extend(TYPE_VALIDATOR, sub_type, attributes=[_VALIDATOR_CONSTRAINT_NAME_SCHEMA]) # index.lookup: same RDB physical attrs as identity.secondary (@orders/@where/@expr/@using). registry.extend( TYPE_INDEX, diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index 79734985ba..e1d1cb0327 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -59,6 +59,20 @@ { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } ] }, + { + "type": "field", + "subType": "enum", + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "validator", + "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + ] + }, { "type": "identity", "subType": "primary", diff --git a/server/python/src/metaobjects/spec_metamodel/validator.json b/server/python/src/metaobjects/spec_metamodel/validator.json index 9520605bd7..43a306ddc3 100644 --- a/server/python/src/metaobjects/spec_metamodel/validator.json +++ b/server/python/src/metaobjects/spec_metamodel/validator.json @@ -66,7 +66,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "left", "min": 1, "max": 1, "description": "Name of the left-hand field of the owning entity." }, { "type": "attr", "subType": "string", "name": "op", "min": 1, "max": 1, "allowedValues": ["gt", "gte", "lt", "lte", "ne", "eq"], "description": "Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=)." }, - { "type": "attr", "subType": "string", "name": "right", "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." } + { "type": "attr", "subType": "string", "name": "right", "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -78,7 +79,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "field", "min": 1, "max": 1, "description": "Name of the field that becomes required when the condition holds." }, { "type": "attr", "subType": "string", "name": "when", "min": 1, "max": 1, "description": "Name of the gating field whose value triggers the requirement." }, - { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." } + { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -90,7 +92,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "field", "min": 1, "max": 1, "description": "Name of the field whose presence is governed by the condition." }, { "type": "attr", "subType": "string", "name": "when", "min": 1, "max": 1, "description": "Name of the gating field." }, - { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." } + { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -100,7 +103,9 @@ "whenToUse": "At least one of several fields must be present (email or phone). Declare it instead of hand-written OR-presence checks.", "rules": "@fields names two or more fields of the owning entity. Satisfied when any one of them is non-null.", "children": [ - { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." } + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." }, + { "type": "attr", "subType": "int", "name": "max", "min": 0, "max": 1, "description": "The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE)." } ] } ] diff --git a/server/typescript/packages/metadata/src/core/validator/validator-constants.ts b/server/typescript/packages/metadata/src/core/validator/validator-constants.ts index 719828e1f9..22524989bf 100644 --- a/server/typescript/packages/metadata/src/core/validator/validator-constants.ts +++ b/server/typescript/packages/metadata/src/core/validator/validator-constants.ts @@ -50,3 +50,15 @@ export const VALIDATOR_ATTR_FIELDS = "fields"; // Comparison operators (@op allowed values) → relational operator. export const VALIDATOR_COMPARISON_OPS = ["gt", "gte", "lt", "lte", "ne", "eq"] as const; export type ComparisonOp = (typeof VALIDATOR_COMPARISON_OPS)[number]; + +/** comparison / requiredWhen / presentIff / atLeastOne: the case the rule applies in (an attr.expression). */ +export const VALIDATOR_ATTR_CONDITION = "condition"; +/** Every validator (db provider): the database name of the CHECK it generates. */ +export const VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName"; +/** The cross-field validators: the database enforces them, nothing else evaluates them. */ +export const CROSS_FIELD_VALIDATOR_SUBTYPES: readonly string[] = [ + VALIDATOR_SUBTYPE_COMPARISON, + VALIDATOR_SUBTYPE_REQUIRED_WHEN, + VALIDATOR_SUBTYPE_PRESENT_IFF, + VALIDATOR_SUBTYPE_AT_LEAST_ONE, +]; diff --git a/server/typescript/packages/metadata/src/core/validator/validator-definition.embedded.ts b/server/typescript/packages/metadata/src/core/validator/validator-definition.embedded.ts index c8f5c6a83d..dd8e520ad6 100644 --- a/server/typescript/packages/metadata/src/core/validator/validator-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/validator/validator-definition.embedded.ts @@ -180,6 +180,14 @@ export const VALIDATOR_DEFINITION: ProviderDefinition = { "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." + }, + { + "type": "attr", + "subType": "expression", + "name": "condition", + "min": 0, + "max": 1, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, @@ -213,6 +221,14 @@ export const VALIDATOR_DEFINITION: ProviderDefinition = { "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." + }, + { + "type": "attr", + "subType": "expression", + "name": "condition", + "min": 0, + "max": 1, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, @@ -246,6 +262,14 @@ export const VALIDATOR_DEFINITION: ProviderDefinition = { "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." + }, + { + "type": "attr", + "subType": "expression", + "name": "condition", + "min": 0, + "max": 1, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, @@ -264,6 +288,22 @@ export const VALIDATOR_DEFINITION: ProviderDefinition = { "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." + }, + { + "type": "attr", + "subType": "expression", + "name": "condition", + "min": 0, + "max": 1, + "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." + }, + { + "type": "attr", + "subType": "int", + "name": "max", + "min": 0, + "max": 1, + "description": "The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE)." } ] } diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index dd4a315d7e..7fb587155c 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -94,6 +94,7 @@ export { } from "./core/requirement/resolve-claim.js"; export * from "./core/relationship/relationship-constants.js"; export * from "./core/query/query-constants.js"; +export { EXPR_OP_IS_NOT_NULL, EXPR_OP_NOT, EXPR_FN_COALESCE, type ExprNode } from "./core/attr/meta-attr-expression.js"; export * from "./persistence/source/source-constants.js"; export * from "./persistence/origin/origin-constants.js"; export * from "./template/template-constants.js"; diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index 74c89bc8f1..972ea143fc 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -26,7 +26,7 @@ import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, - validateEnumMaxLength, validateIdentitySequence, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; + validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -731,6 +731,9 @@ export class MetaDataLoader { // identity.primary @sequenceStart / @sequenceName need @generation "increment". errors.push(...validateIdentitySequence(root)); + // Cross-field validators: atLeastOne @max in range; @condition names real fields. + errors.push(...validateCrossFieldValidators(root)); + // Tenth pass: one-primary multi-source rule — if an object has ≥1 source, // exactly one must carry role "primary" (ERR_SOURCE_NO_PRIMARY / // ERR_SOURCE_MULTIPLE_PRIMARY). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 5b79984360..3d56934b7f 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -10,6 +10,14 @@ // Private: _findObject, _findField, _findRelationship, // _validateFromPath, _validateViaPath (helpers, not exported). +import { TYPE_VALIDATOR } from "../shared/base-types.js"; +import { + CROSS_FIELD_VALIDATOR_SUBTYPES, + VALIDATOR_ATTR_CONDITION, + VALIDATOR_ATTR_FIELDS, + VALIDATOR_ATTR_MAX, + VALIDATOR_SUBTYPE_AT_LEAST_ONE, +} from "../core/validator/validator-constants.js"; import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; import type { MetaReferenceIdentity } from "../core/identity/meta-identity.js"; @@ -1679,6 +1687,59 @@ export function validateDerivedFieldProvidability(root: MetaData): ParseError[] return errors; } +// --------------------------------------------------------------------------- +// Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the +// database enforces as CHECKs: +// - atLeastOne @max is between 1 and the number of its @fields (ERR_BAD_ATTR_VALUE); +// - every field a @condition expression names is a field of the owning entity +// (ERR_BAD_ATTR_VALUE), so the CHECK it renders to references a real column. +// Read RESOLVING (ADR-0039): an entity's validators and fields include inherited ones. +// --------------------------------------------------------------------------- + +/** The field names an attr.expression tree references. */ +function expressionFieldRefs(node: unknown, out: string[] = []): string[] { + if (typeof node !== "object" || node === null) return out; + const n = node as Record; + if (typeof n["field"] === "string") out.push(n["field"]); + for (const key of ["left", "right", "arg"]) expressionFieldRefs(n[key], out); + for (const key of ["args"]) if (Array.isArray(n[key])) for (const a of n[key] as unknown[]) expressionFieldRefs(a, out); + return out; +} + +export function validateCrossFieldValidators(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { + const fieldNames = new Set((obj as MetaObject).fields().map((f) => f.name)); + // ADR-0039: own — each validator is checked where it is declared. + for (const v of obj.ownChildren()) { + if (v.type !== TYPE_VALIDATOR || !CROSS_FIELD_VALIDATOR_SUBTYPES.includes(v.subType)) continue; + if (v.subType === VALIDATOR_SUBTYPE_AT_LEAST_ONE) { + const max = v.attr(VALIDATOR_ATTR_MAX); + const fields = [v.attr(VALIDATOR_ATTR_FIELDS)].flat().filter((f) => typeof f === "string"); + if (typeof max === "number" && (max < 1 || max > fields.length)) { + errors.push(new ParseError( + `validator.atLeastOne "${obj.name}.${v.name}" @max ${max} must be between 1 and the number of its @fields (${fields.length}).`, + { code: "ERR_BAD_ATTR_VALUE", source: v.source }, + )); + continue; + } + } + const condition = v.attr(VALIDATOR_ATTR_CONDITION); + if (condition !== undefined) { + const unknown = [...new Set(expressionFieldRefs(condition))].filter((f) => !fieldNames.has(f)).sort(); + if (unknown.length > 0) { + errors.push(new ParseError( + `validator.${v.subType} "${obj.name}.${v.name}" @condition names ${unknown.map((f) => `"${f}"`).join(", ")}, ` + + `which ${unknown.length === 1 ? "is not a field" : "are not fields"} of "${obj.name}".`, + { code: "ERR_BAD_ATTR_VALUE", source: v.source }, + )); + } + } + } + } + return errors; +} + // --------------------------------------------------------------------------- // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation // "increment" key draws from. On any other generation there is no sequence, so either one diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index 54114bbe19..0a7072f3e2 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -254,6 +254,42 @@ export const DB_DEFINITION: ProviderDefinition = { } ] }, + { + "type": "field", + "subType": "enum", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "constraintName", + "min": 0, + "max": 1, + "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + } + ] + }, + { + "type": "validator", + "subType": [ + "numeric", + "length", + "regex", + "comparison", + "requiredWhen", + "presentIff", + "atLeastOne" + ], + "children": [ + { + "type": "attr", + "subType": "string", + "name": "constraintName", + "min": 0, + "max": 1, + "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + } + ] + }, { "type": "identity", "subType": "primary", diff --git a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts index 57c6c4c6e0..ba3eb4c95d 100644 --- a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts @@ -108,6 +108,11 @@ const ENUM_CORE_EXTRA: Record = { maxLength: { valueType: "int", required: false }, }; +// db provider: the name of the CHECK an enum's member list generates. +const ENUM_DB_EXTRA: Record = { + constraintName: { valueType: "string", required: false }, +}; + /** Scoped concern attrs (db / prompt). */ const STORAGE_EXTRA: Record = { storage: { valueType: "string", required: false }, @@ -166,7 +171,7 @@ function expectedAttrsFor(subType: string): Record { if (subType === FIELD_SUBTYPE_OBJECT) Object.assign(exp, OBJECT_CORE_EXTRA, STORAGE_EXTRA); if (subType === FIELD_SUBTYPE_MAP) Object.assign(exp, MAP_EXTRA); if (subType === FIELD_SUBTYPE_CURRENCY) Object.assign(exp, CURRENCY_EXTRA); - if (subType === FIELD_SUBTYPE_ENUM) Object.assign(exp, ENUM_CORE_EXTRA, ENUM_PROMPT_EXTRA); + if (subType === FIELD_SUBTYPE_ENUM) Object.assign(exp, ENUM_CORE_EXTRA, ENUM_PROMPT_EXTRA, ENUM_DB_EXTRA); if (TEMPORAL.has(subType)) Object.assign(exp, AUTO_SET_EXTRA); if (subType === FIELD_SUBTYPE_TIMESTAMP) Object.assign(exp, LOCAL_TIME_EXTRA); if (subType === "uri" || subType === "inet") Object.assign(exp, LENIENT_EXTRA); diff --git a/server/typescript/packages/metadata/test/validator-definition-completeness.test.ts b/server/typescript/packages/metadata/test/validator-definition-completeness.test.ts index 0e2c247254..da24a23a4f 100644 --- a/server/typescript/packages/metadata/test/validator-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/validator-definition-completeness.test.ts @@ -41,19 +41,24 @@ const EXPECTED: Record "b" OR …`, not `NOT ("a" = "b") OR …`. +// +// The negation is exact in SQL's three-valued logic: a flipped comparison is NULL exactly when +// the original is, isNull/isNotNull swap, and/or follow De Morgan. A field resolves to its +// physical column through the caller's lookup; a field the lookup does not know refuses the +// render (the loader refuses that model first, ERR_BAD_ATTR_VALUE). + +import { + EXPR_FN_COALESCE, + EXPR_OP_IS_NOT_NULL, + EXPR_OP_NOT, + FILTER_COMPOSE_AND, + FILTER_COMPOSE_OR, + FILTER_OP_EQ, + FILTER_OP_GT, + FILTER_OP_GTE, + FILTER_OP_IS_NULL, + FILTER_OP_LT, + FILTER_OP_LTE, + FILTER_OP_NE, + type ExprNode, +} from "@metaobjectsdev/metadata"; +import type { Dialect } from "./types.js"; + +const SQL_OP: Readonly> = { + [FILTER_OP_EQ]: "=", [FILTER_OP_NE]: "<>", [FILTER_OP_GT]: ">", + [FILTER_OP_GTE]: ">=", [FILTER_OP_LT]: "<", [FILTER_OP_LTE]: "<=", +}; + +const NEGATED_OP: Readonly> = { + [FILTER_OP_EQ]: FILTER_OP_NE, [FILTER_OP_NE]: FILTER_OP_EQ, + [FILTER_OP_GT]: FILTER_OP_LTE, [FILTER_OP_LTE]: FILTER_OP_GT, + [FILTER_OP_LT]: FILTER_OP_GTE, [FILTER_OP_GTE]: FILTER_OP_LT, + [FILTER_OP_IS_NULL]: EXPR_OP_IS_NOT_NULL, [EXPR_OP_IS_NOT_NULL]: FILTER_OP_IS_NULL, +}; + +type Node = Record; + +/** The logical negation of `node`, pushed down to its comparisons. */ +export function negateExpression(node: ExprNode): ExprNode { + const n = node as Node; + const op = n["op"]; + if (op === EXPR_OP_NOT) return n["arg"] as ExprNode; + if (op === FILTER_COMPOSE_AND || op === FILTER_COMPOSE_OR) { + return { + op: op === FILTER_COMPOSE_AND ? FILTER_COMPOSE_OR : FILTER_COMPOSE_AND, + args: (n["args"] as ExprNode[]).map(negateExpression), + } as ExprNode; + } + if (typeof op === "string" && NEGATED_OP[op] !== undefined) { + return { ...n, op: NEGATED_OP[op] } as ExprNode; + } + return { op: EXPR_OP_NOT, arg: node } as ExprNode; +} + +/** + * `node` as SQL. `column(field)` is the quoted physical column for a field name, or undefined + * when the entity has no such field. + */ +export function renderExpressionSql( + node: ExprNode, column: (field: string) => string | undefined, dialect: Dialect | undefined, +): string { + const n = node as Node; + if (typeof n["field"] === "string") { + const col = column(n["field"]); + if (col === undefined) throw new Error(`@condition names "${n["field"]}", which is not a field of the entity`); + return col; + } + if ("value" in n) return renderLiteral(n["value"], dialect); + const op = n["op"]; + const sub = (x: unknown): string => renderExpressionSql(x as ExprNode, column, dialect); + if (typeof op === "string" && SQL_OP[op] !== undefined) return `${sub(n["left"])} ${SQL_OP[op]} ${sub(n["right"])}`; + if (op === FILTER_OP_IS_NULL) return `${sub(n["arg"])} IS NULL`; + if (op === EXPR_OP_IS_NOT_NULL) return `${sub(n["arg"])} IS NOT NULL`; + if (op === EXPR_OP_NOT) return `NOT (${sub(n["arg"])})`; + if (op === FILTER_COMPOSE_AND || op === FILTER_COMPOSE_OR) { + return (n["args"] as unknown[]).map((a) => `(${sub(a)})`).join(op === FILTER_COMPOSE_AND ? " AND " : " OR "); + } + if (n["fn"] === EXPR_FN_COALESCE) return `COALESCE(${(n["args"] as unknown[]).map(sub).join(", ")})`; + throw new Error(`@condition: an expression node migrate cannot render: ${JSON.stringify(node)}`); +} + +function renderLiteral(v: unknown, dialect: Dialect | undefined): string { + if (v === null) return "NULL"; + if (typeof v === "boolean") return dialect === "sqlite" || dialect === "d1" ? (v ? "1" : "0") : (v ? "TRUE" : "FALSE"); + if (typeof v === "number") return String(v); + return `'${String(v).replace(/'/g, "''")}'`; +} diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 84393e8e03..e0affc8125 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,4 +1,5 @@ import { DuplicateSqlNameError, FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; +import { negateExpression, renderExpressionSql } from "./check-expression.js"; import { canBeUniqueConstraint, resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, @@ -64,6 +65,10 @@ import { resolveEnumMaxLength, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START, + VALIDATOR_ATTR_CONDITION, + VALIDATOR_ATTR_MAX, + VALIDATOR_ATTR_CONSTRAINT_NAME, + type ExprNode, } from "@metaobjectsdev/metadata"; import type { SqlType } from "./sql-type.js"; import type { @@ -895,7 +900,7 @@ function buildChecks( } else { expression = `${qcol} IN (${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ")})`; } - checks.push({ name: `${tableName}_${col}_chk`, expression }); + checks.push({ name: declaredCheckName(field) ?? `${tableName}_${col}_chk`, expression }); } } // Validator-derived checks. @@ -906,13 +911,13 @@ function buildChecks( const enforcedMax = skipRedundant && enforcesLength && columnType.kind === "text" ? columnType.maxLength : undefined; for (const v of field.validators()) { const check = validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); - if (check) checks.push(check); + if (check) checks.push(withDeclaredName(check, v)); } } // Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne). for (const v of entity.validators()) { const check = crossFieldCheck(v, entity, tableName, strategy, dialect); - if (check) checks.push(check); + if (check) checks.push(withDeclaredName(withCondition(check, v, entity, strategy, dialect), v)); } return checks; } @@ -974,6 +979,35 @@ function renderEquals( * resolved to its physical column by name; nothing raw is read from metadata. * Returns null (skips the check) if any referenced field is missing. */ +/** A validator's or field.enum's declared CHECK name (`@constraintName`; ADR-0039 resolving), if any. */ +function declaredCheckName(node: MetaData): string | undefined { + const name = node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + return typeof name === "string" && name.length > 0 ? name : undefined; +} + +function withDeclaredName(check: CheckDescriptor, node: MetaData): CheckDescriptor { + const name = declaredCheckName(node); + return name === undefined ? check : { ...check, name }; +} + +/** + * A cross-field validator's `@condition` (an attr.expression): the rule applies only when it + * holds, so the CHECK is the negated condition OR the rule. A row the condition is NULL for is + * not checked, as for any CHECK. + */ +function withCondition( + check: CheckDescriptor, v: MetaValidator, entity: MetaObject, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, +): CheckDescriptor { + const condition = v.attr(VALIDATOR_ATTR_CONDITION); + if (condition === undefined || condition === null || typeof condition !== "object") return check; + const column = (name: string): string | undefined => { + const field = entity.fields().find((f) => f.name === name); + return field === undefined ? undefined : quoteCheckCol(resolveColumnName(field, strategy)); + }; + const unless = renderExpressionSql(negateExpression(condition as ExprNode), column, dialect); + return { ...check, expression: `(${unless}) OR (${check.expression})` }; +} + function crossFieldCheck( v: MetaValidator, entity: MetaObject, tableName: string, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, @@ -1019,6 +1053,18 @@ function crossFieldCheck( const refs = names.map((n) => resolveRef(entity, n, strategy)); if (refs.length === 0 || refs.some((r) => r === null)) return null; const firstCol = resolveColumnName(refs[0]!.field, strategy); + // @max bounds how many may be present (@max 1: exactly one). Postgres counts them with + // num_nonnulls; SQLite adds the presence tests, which it evaluates as 0 / 1. + const max = v.attr(VALIDATOR_ATTR_MAX); + if (typeof max === "number") { + const count = dialect === "sqlite" || dialect === "d1" + ? `(${refs.map((r) => `(${r!.qcol} IS NOT NULL)`).join(" + ")})` + : `num_nonnulls(${refs.map((r) => r!.qcol).join(", ")})`; + return { + name: `${tableName}_${firstCol}_atleastone_chk`, + expression: max === 1 ? `${count} = 1` : `${count} BETWEEN 1 AND ${max}`, + }; + } return { name: `${tableName}_${firstCol}_atleastone_chk`, expression: refs.map((r) => `${r!.qcol} IS NOT NULL`).join(" OR "), diff --git a/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts b/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts new file mode 100644 index 0000000000..5ac1d01e2e --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts @@ -0,0 +1,73 @@ +/** + * CHECKs a database names by hand, an exactly-one presence rule, and a rule that applies in + * one case only: + * - `@constraintName` on a validator or a field.enum is the CHECK's database name; + * - `validator.atLeastOne @max` bounds the present fields (`@max: 1` = exactly one); + * - `@condition` on a cross-field validator: the CHECK is the negated condition OR the rule, + * the negation pushed into the comparison so it reads as written by hand. + */ +import { describe, test, expect } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; + +const FIXTURE = join(import.meta.dir, "../../../../../../fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json"); + +async function checks(dialect: "postgres" | "sqlite" = "postgres") { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(readFileSync(FIXTURE, "utf8"))]); + expect(errors).toHaveLength(0); + const t = buildExpectedSchema(root, { dialect }).tables.find((x) => x.name === "OfficeHours")!; + return Object.fromEntries(t.checks.map((c) => [c.name, c.expression])); +} + +describe("cross-field CHECK extensions", () => { + test("@constraintName names the enum, field-validator (length, regex, numeric) and cross-field CHECKs", async () => { + expect(Object.keys(await checks()).sort()).toEqual([ + "CK_OfficeHours_Code", + "CK_OfficeHours_CodeShape", + "CK_OfficeHours_ExactlyOneSource", + "CK_OfficeHours_Kind", + "CK_OfficeHours_SameDayValidation", + "CK_OfficeHours_StartDay", + ]); + }); + + test("atLeastOne @max 1 is exactly one present (Postgres num_nonnulls)", async () => { + expect((await checks())["CK_OfficeHours_ExactlyOneSource"]).toBe('num_nonnulls("patient_id", "caregiver_id") = 1'); + }); + + test("atLeastOne @max 1 on SQLite counts the present fields", async () => { + expect((await checks("sqlite"))["CK_OfficeHours_ExactlyOneSource"]) + .toBe('(("patient_id" IS NOT NULL) + ("caregiver_id" IS NOT NULL)) = 1'); + }); + + test("@condition: the negated condition, then the rule", async () => { + expect((await checks())["CK_OfficeHours_SameDayValidation"]).toBe('("start_day" <> "end_day") OR ("end_time" > "start_time")'); + }); + + test("atLeastOne @max above 1 is a range", async () => { + const doc = { "metadata.root": { package: "acme", children: [{ "object.entity": { name: "T", children: [ + { "source.rdb": { "@table": "t" } }, { "field.long": { name: "id" } }, + { "field.long": { name: "a" } }, { "field.long": { name: "b" } }, { "field.long": { name: "c" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "validator.atLeastOne": { name: "few", "@fields": ["a", "b", "c"], "@max": 2 } }, + ] } }] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toHaveLength(0); + const t = buildExpectedSchema(root, { dialect: "postgres" }).tables[0]!; + expect(t.checks.map((c) => c.expression)).toEqual(['num_nonnulls("a", "b", "c") BETWEEN 1 AND 2']); + }); + + test("no @max, no @condition, no @constraintName: unchanged", async () => { + const doc = { "metadata.root": { package: "acme", children: [{ "object.entity": { name: "T", children: [ + { "source.rdb": { "@table": "t" } }, { "field.long": { name: "id" } }, + { "field.long": { name: "a" } }, { "field.long": { name: "b" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"] } }, + ] } }] } }; + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + const t = buildExpectedSchema(root, { dialect: "postgres" }).tables[0]!; + expect(t.checks).toEqual([{ name: "t_a_atleastone_chk", expression: '"a" IS NOT NULL OR "b" IS NOT NULL' }]); + }); +}); diff --git a/site-reference/providers.html b/site-reference/providers.html index 325916464e..53b00ae10d 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -81,14 +81,14 @@

    metaobjects-core-types

  • template.prompt: @format, @maxChars, @maxTokens, @model, @owner, @payloadRef, @promptStyle, @requiredSlots, @requiredTags, @responseFormat, @responseRef, @since, @textRef
  • template.toolcall: @maxTokens, @owner, @payloadRef, @since, @toolName
  • validator.array: @max, @min
  • -
  • validator.atLeastOne: @fields
  • +
  • validator.atLeastOne: @condition, @fields, @max
  • validator.base: @max, @min
  • -
  • validator.comparison: @left, @op, @right
  • +
  • validator.comparison: @condition, @left, @op, @right
  • validator.length: @max, @min
  • validator.numeric: @max, @min
  • -
  • validator.presentIff: @equals, @field, @when
  • +
  • validator.presentIff: @condition, @equals, @field, @when
  • validator.regex: @max, @min, @pattern
  • -
  • validator.requiredWhen: @equals, @field, @when
  • +
  • validator.requiredWhen: @condition, @equals, @field, @when
  • metaobjects-db

    DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @storage on field.object, @autoSet on temporal fields, @table/@kind/@role/@schema on source.rdb.

    @@ -100,7 +100,7 @@

    metaobjects-db

  • field.date: @autoSet, @column, @db.indexed, @dbColumnType
  • field.decimal: @column, @db.indexed, @dbColumnType
  • field.double: @column, @db.indexed, @dbColumnType
  • -
  • field.enum: @column, @db.indexed, @dbColumnType
  • +
  • field.enum: @column, @constraintName, @db.indexed, @dbColumnType
  • field.float: @column, @db.indexed, @dbColumnType
  • field.inet: @column, @db.indexed, @dbColumnType
  • field.int: @column, @db.indexed, @dbColumnType
  • @@ -117,6 +117,13 @@

    metaobjects-db

  • identity.secondary: @expr, @orders, @using, @where
  • index.lookup: @expr, @orders, @using, @where
  • source.rdb: @function, @kind, @materializedView, @parameterRef, @proc, @role, @schema, @sql, @table, @unmanaged, @view
  • +
  • validator.atLeastOne: @constraintName
  • +
  • validator.comparison: @constraintName
  • +
  • validator.length: @constraintName
  • +
  • validator.numeric: @constraintName
  • +
  • validator.presentIff: @constraintName
  • +
  • validator.regex: @constraintName
  • +
  • validator.requiredWhen: @constraintName
  • metaobjects-documentation

    Universal documentation common attrs (description / title / notes / deprecated / replacedBy / seeAlso / aliases) accepted on every metatype.

    diff --git a/site-reference/types/field.html b/site-reference/types/field.html index 40045743ef..8da1adb9c1 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -1024,6 +1024,15 @@

    field.enum

    + + + + + + +
    Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json).
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this enum's member list generates. Absent: __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + diff --git a/site-reference/types/validator.html b/site-reference/types/validator.html index 50f22a081d..6a1f483852 100644 --- a/site-reference/types/validator.html +++ b/site-reference/types/validator.html @@ -107,6 +107,24 @@

    validator.atLeastOne

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    @db.indexed boolean no
    @conditionexpressionnometaobjects-core-typesThe case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself.
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + @@ -115,6 +133,15 @@

    validator.atLeastOne

    + + + + + + + + +
    @fields string[] yes metaobjects-core-types Names of the candidate fields; at least one must be present.
    @maxintnometaobjects-core-typesThe most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE).

    Allowed children

    No structural children.

    @@ -174,6 +201,24 @@

    validator.comparison

    @conditionexpressionnometaobjects-core-typesThe case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself.
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + @@ -221,6 +266,15 @@

    validator.length

    + + + + + + +
    @left string yes
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + @@ -259,6 +313,15 @@

    validator.numeric

    + + + + + + +
    @max int no
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + @@ -298,6 +361,24 @@

    validator.presentIff

    + + + + + + + + + + + + + + + +
    @max int no
    @conditionexpressionnometaobjects-core-typesThe case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself.
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + @@ -345,6 +426,15 @@

    validator.regex

    + + + + + + +
    @equals string yes
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + @@ -401,6 +491,24 @@

    validator.requiredWhen

    + + + + + + + + + + + + + + + + - + diff --git a/site-reference/types/field.html b/site-reference/types/field.html index 65c948f69a..fe5cd23463 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -988,7 +988,7 @@

    field.double

  • view.* — 0..*
  • field.duration

    -

    A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.

    +

    A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.

    Owning provider: metaobjects-core-types

    When to use: A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span ("every 3 months") is not a duration: model it as an int and a unit.

    Attributes

    diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index 57bb390cbe..29176405ef 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -190,7 +190,7 @@ "subType": "duration", "dataType": "string", "extendsBase": true, - "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit." } ] From c2402d2692e9c81f63f97941e1a49f5f50ae1cc9 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Tue, 3 Nov 2026 14:07:26 -0500 Subject: [PATCH 027/267] chore(release): added vocabulary bumps the metamodel minor again This reverts 55dcc71b0. metamodelVersion is the one signal that two ports know the same vocabulary: without a bump, a port left on the old vocabulary reports the same number and only fails strict verify on the new attributes. Additive vocabulary moves the metamodel MINOR again; the packages still ship it as a patch, since the two numbers are separate (ADR-0035 Amendment 2). metamodelVersion is now 1.3 for field.duration, the CHECK vocabulary, the sequence and flattened-prefix attributes, and the upperFirst rule. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++++------- docs/RELEASING.md | 2 +- examples/showcase/site-payload.json | 2 +- fixtures/registry-conformance/expected-registry.json | 2 +- scripts/check-metamodel-version.mjs | 8 ++------ scripts/test-metamodel-version.mjs | 10 ++++------ server/csharp/MetaObjects/RegistryManifest.cs | 2 +- .../com/metaobjects/registry/RegistryManifest.java | 2 +- server/python/src/metaobjects/registry_manifest.py | 2 +- .../codegen-ts/test/shared-model-file.test.ts | 2 +- .../packages/metadata/src/registry-manifest.ts | 2 +- 11 files changed, 19 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39dccc25ba..50ea77fc74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,11 @@ here.** ## [Unreleased] +**`metamodelVersion` moves to `1.3`.** This release adds vocabulary (`field.duration`, +`@constraintName`, `@condition`, `atLeastOne @max`, `@sequenceStart`, `@sequenceName`, +`@flattenedColumnPrefix`, the `upperFirst` column rule) and nothing that loaded before stops +loading. A port that reports `1.2` does not know that vocabulary; upgrade every port together. + ### Added - **`field.duration`: a fixed-length span of time, in every port.** `TimeSpan` in C#, @@ -129,13 +134,6 @@ here.** ### Changed -- **Added vocabulary no longer moves `metamodelVersion`.** The metamodel spec version now moves - only when metadata that loaded may stop loading or change meaning. A new type, subtype, - optional attribute or enum member leaves it unchanged, and its CHANGELOG entry names it; the - package version follows the versioning table in `docs/RELEASING.md`, as before. Matching - `metamodelVersion`s therefore no longer prove two ports know the same vocabulary; compare - their releases. - - **`meta migrate` refuses a foreign key that references columns the target does not hold unique.** Behaviour change: an `identity.reference` whose dotted `@references` names target fields that are not the target's primary key, a plain `identity.secondary` (no `@where`, no `@expr`) or a single diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 74aac3b2df..4a8f6df227 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -304,7 +304,7 @@ requires. Same shape as `buf breaking --against '.git#tag=…'` / `oasdiff`. | Change | Required move | |---|---| | a type/subtype removed; an attr removed; an attr made required, retyped or re-arrayed; an enum member removed or an open attr closed; a child rule removed, its `min` raised or its `max` lowered; a default subtype changed | **major** (pre-1.0: minor — see below) | -| a type/subtype added; an optional attr added; an enum member added; a child rule added or relaxed; a default subtype added | **none** — every document that loaded still loads, identically, so `metamodelVersion` stays put and the CHANGELOG names what was added. The package version follows the versioning table above | +| a type/subtype added; an optional attr added; an enum member added; a child rule added or relaxed; a default subtype added | **minor** | | prose only (`description` / `rules` / `whenToUse`) | none — but read the warning | **Pre-1.0 a breaking change moves the MINOR**, for the same reason the package line diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 2a85f6d912..fba3494620 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -4,7 +4,7 @@ "pypi": "1.2.0", "nuget": "1.2.0", "maven": "8.2.0", - "metamodel": "1.2" + "metamodel": "1.3" }, "counts": { "fixtures": 437, diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index bbb82ec019..59a8ee972a 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1,5 +1,5 @@ { - "metamodelVersion": "1.2", + "metamodelVersion": "1.3", "types": [ { "type": "attr", diff --git a/scripts/check-metamodel-version.mjs b/scripts/check-metamodel-version.mjs index 890e397733..fb7844cdd8 100755 --- a/scripts/check-metamodel-version.mjs +++ b/scripts/check-metamodel-version.mjs @@ -117,11 +117,7 @@ const isPre1 = (v) => v.major === 0; */ export function requiredBump(severity, base, { correction = false } = {}) { if (severity === "none") return "none"; - // ADDITIVE moves no metamodel number. Every document that loaded still loads, and means - // the same, so nothing an adopter's metadata relies on changed: the CHANGELOG entry names - // the new vocabulary, and the package version follows docs/RELEASING.md. The number moves - // only when existing metadata may stop loading or change meaning. - if (severity === "additive") return "none"; + if (severity === "additive") return "minor"; if (correction) return "minor"; // breaking, but a correction — never a metamodel major return isPre1(base) ? "minor" : "major"; // breaking } @@ -143,7 +139,7 @@ export function satisfies(bump, base, cur) { // Classification. // // BREAKING — metadata that used to load may now fail, or mean something else. -// ADDITIVE — every previously-valid document still loads, identically. Requires no bump. +// ADDITIVE — every previously-valid document still loads, identically. // PROSE — human-readable only; the classifier declines to guess (see the header). // --------------------------------------------------------------------------- diff --git a/scripts/test-metamodel-version.mjs b/scripts/test-metamodel-version.mjs index 31b0a33934..19190074cd 100755 --- a/scripts/test-metamodel-version.mjs +++ b/scripts/test-metamodel-version.mjs @@ -275,10 +275,8 @@ const v = (s) => parseVersion(s, "test"); const bump = (sev, base) => requiredBump(sev, v(base)); if (bump("none", "1.0") !== "none") bad("no change requires no bump"); else ok("no change requires no bump"); -// Additive vocabulary moves no metamodel number: every document that loaded still loads, -// identically, so the CHANGELOG names it and the package version follows docs/RELEASING.md. -if (bump("additive", "1.0") !== "none") bad("additive requires no bump"); -else ok("additive requires no bump"); +if (bump("additive", "1.0") !== "minor") bad("additive requires a minor"); +else ok("additive requires a minor"); if (bump("breaking", "1.0") !== "major") bad("post-1.0 breaking requires a major"); else ok("post-1.0 breaking requires a major"); // Pre-1.0 the major carries no promise, so a break moves the minor — the same rule the @@ -307,8 +305,8 @@ else ok("pre-1.0 the correction flag changes nothing"); // It cannot upgrade a lesser severity into a bump it did not earn. if (corr("none", "1.0") !== "none") bad("a correction over `none` is still none"); else ok("a correction over `none` is still none"); -if (corr("additive", "1.0") !== "none") bad("a correction over `additive` is still none"); -else ok("a correction over `additive` is still none"); +if (corr("additive", "1.0") !== "minor") bad("a correction over `additive` is still a minor"); +else ok("a correction over `additive` is still a minor"); const sat = (b, base, cur) => satisfies(b, v(base), v(cur)); if (sat("minor", "1.0", "1.0")) bad("an unmoved version must NOT satisfy a minor"); diff --git a/server/csharp/MetaObjects/RegistryManifest.cs b/server/csharp/MetaObjects/RegistryManifest.cs index b59670f15d..8f0ee03576 100644 --- a/server/csharp/MetaObjects/RegistryManifest.cs +++ b/server/csharp/MetaObjects/RegistryManifest.cs @@ -375,7 +375,7 @@ private static ManifestType ToManifestType(TypeDefinition def) => /// unstable (semver major-0). The 1.0 cut flips this to "1.0". /// Emitted as the FIRST top-level key in the registry manifest (C4). /// - public const string MetamodelVersion = "1.2"; + public const string MetamodelVersion = "1.3"; /// /// Emit the canonical registry manifest as a byte-stable JSON string. diff --git a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java index 596e86fd55..fcecf70cae 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java +++ b/server/java/metadata/src/main/java/com/metaobjects/registry/RegistryManifest.java @@ -277,7 +277,7 @@ public static List metamodelProviders() { * the 1.0 cut will flip it to {@code "1.0"}. Mirrors the TS reference's * {@code METAMODEL_VERSION} constant. */ - public static final String METAMODEL_VERSION = "1.2"; + public static final String METAMODEL_VERSION = "1.3"; // ------------------------------------------------------------------ // SP-G Phase1 Units2-3 — manifest emitter exclusions (documented, uniform diff --git a/server/python/src/metaobjects/registry_manifest.py b/server/python/src/metaobjects/registry_manifest.py index 0340fb466b..9e99593953 100644 --- a/server/python/src/metaobjects/registry_manifest.py +++ b/server/python/src/metaobjects/registry_manifest.py @@ -255,7 +255,7 @@ def _sorted_children(definition: TypeDefinition) -> list[dict[str, object]]: return children -METAMODEL_VERSION = "1.2" +METAMODEL_VERSION = "1.3" """Rolled-up spec-version for the cross-port registry manifest. ``"0"`` = pre-1.0 / unstable (semver major-0). Flips to ``"1.0"`` at the diff --git a/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts b/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts index 438403a266..6ee797c377 100644 --- a/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/shared-model-file.test.ts @@ -208,7 +208,7 @@ describe("sharedModelFile()", () => { schema_version: 1, name: "acme-common", version: "1.0.0", - metamodelVersion: "1.2", + metamodelVersion: "1.3", artifact: "acme-common.metaobjects.json", integrity: PINNED_HASH, packages: ["acme::common"], diff --git a/server/typescript/packages/metadata/src/registry-manifest.ts b/server/typescript/packages/metadata/src/registry-manifest.ts index 3f1acdfe96..4fa5345bce 100644 --- a/server/typescript/packages/metadata/src/registry-manifest.ts +++ b/server/typescript/packages/metadata/src/registry-manifest.ts @@ -112,7 +112,7 @@ export interface ManifestType { * constant read `"0.10"`). Bump with that script — never by hand — so the manifest and * all four port constants move together. */ -export const METAMODEL_VERSION = "1.2"; +export const METAMODEL_VERSION = "1.3"; /** The full canonical manifest. All collections are sorted for byte-stability. */ interface RegistryManifest { From c52e71f04030ecb56e0a094d2b86966617f7da69 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Tue, 3 Nov 2026 15:52:05 -0500 Subject: [PATCH 028/267] fix: the overfitting review's findings, in every port A review of this branch asked where a limit was imposed across ports or fitted to one adopter. Each port and database now keeps its own capability. field.duration - A week (nW) is exactly 7 days; a fraction may have any number of digits. Each port writes its own precision (TypeScript and Python 6, C# 7, Java and Kotlin 9) and truncates toward zero; storage holds microseconds. - fixtures/duration-wire splits into `wire` (every port) and `codecs` (only the ports with that codec). Python drops a helper it kept only to pass a group. - A @condition or @equals literal against a duration renders in the column's form (interval text on Postgres, microseconds on SQLite/D1), including through coalesce; a literal that is not a duration is refused. - The in-memory driver stores and compares microseconds, so ordering and range filters follow the span. - Python's Postgres reads refuse a month or year interval (psycopg turned one into 30 days) and read negative intervals right (pg8000 misread them). C#: the Npgsql interval mapping is public and top-level, so EF compiled models work; LINQ translation is tested. migrate - efcore truncates names at 63 only on Postgres; EF's SQLite provider truncates nothing. - Skipping redundant CHECKs is its own setting, migrate.checks.skipRedundant, not part of a naming preset. A conventions object still setting skipRedundantChecks is refused. - Schema conventions no longer ride on MetaRoot: the cli resolves them once and passes them to every expected-schema build, drift run and the Prisma generator. meta gen and verify --codegen refuse an unknown preset, as migrate and verify --db do. - Advisories: a live interval modelled as a string, and a sequence that SQLite cannot hold, are reported instead of passing silently. Elsewhere - The PascalCase column rule is now upperFirst (unreleased; no alias). - A flattened field's own column constant is deprecated in every port. - Python drops enum-length resolution nothing used; the config block is still accepted. - Fixture and doc examples use neutral names. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 36 +- .../skills/metaobjects-authoring/SKILL.md | 2 +- docs/CONFORMANCE.md | 4 +- docs/features/field-types.md | 14 +- docs/features/migrations-and-drift.md | 43 ++- docs/features/migrations/physical-naming.md | 13 +- docs/ports/csharp.md | 31 +- .../drizzle-fastify/filter-value-format.ts | 2 +- .../codegen/templates/duration-wire-helper.ts | 25 +- .../codegen/templates/zod-validators.ts | 2 +- .../drizzle-fastify/filter-value-format.ts | 2 +- .../codegen/templates/duration-wire-helper.ts | 25 +- .../codegen/templates/zod-validators.ts | 2 +- .../skills/metaobjects-authoring/SKILL.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 2 +- .../skills/metaobjects-authoring/SKILL.md | 2 +- .../input/meta.checks.json | 8 +- .../input/meta.checks.json | 8 +- .../input/meta.checks.json | 30 +- .../input/meta.checks.json | 8 +- .../input/meta.checks.json | 12 +- .../expected.json | 26 +- .../input/meta.checks.json | 26 +- .../expected/openapi.json | 40 +-- .../contract/AllFields.create.schema.json | 4 +- .../acme/contract/AllFields.schema.json | 4 +- .../contract/AllFields.strict.schema.json | 2 +- .../contract/AllFields.update.schema.json | 4 +- .../expected/openapi.json | 40 +-- .../contract/AllFields.create.schema.json | 4 +- .../acme/contract/AllFields.schema.json | 4 +- .../contract/AllFields.strict.schema.json | 2 +- .../contract/AllFields.update.schema.json | 4 +- .../all-fields/expected/openapi.json | 40 +-- .../contract/AllFields.create.schema.json | 4 +- .../acme/contract/AllFields.schema.json | 4 +- .../contract/AllFields.strict.schema.json | 2 +- .../contract/AllFields.update.schema.json | 4 +- fixtures/duration-wire/README.md | 73 ++-- fixtures/duration-wire/vectors.json | 188 +++++----- fixtures/enum-length-conformance/README.md | 18 +- fixtures/metamodel-docs/expected/INDEX.md | 2 +- .../metamodel-docs/expected/types/field.md | 2 +- .../physical-names/cases.json | 8 +- .../expected-registry.json | 2 +- fixtures/validation-conformance/cases.json | 2 +- .../runtime-errors.json | 21 +- .../DurationWireTests.cs | 80 +++-- .../NamesGeneratorTests.cs | 30 ++ .../ObjectFieldCodegenTests.cs | 2 +- .../ReportExportGeneratorTests.cs | 4 +- .../MetaObjects.Codegen/CSharpNaming.cs | 2 +- .../csharp/MetaObjects.Codegen/CodegenCli.cs | 6 +- .../Generators/DbContextGenerator.cs | 235 +++++++------ .../Generators/EntityGenerator.cs | 106 +++--- .../Generators/NamesGenerator.cs | 21 +- .../Generators/ReportExportGenerator.cs | 17 +- .../Runtime/DurationWire.cs | 104 +++--- .../Runtime/EfCoreFilterDispatch.cs | 6 +- .../Api/DurationWireGeneratedApiTests.cs | 70 +--- .../DurationIntervalEfCoreTests.cs | 332 ++++++++++++++++++ .../Generated/AppDbContext.g.cs | 218 ++++++------ .../Generated/DurationWire.g.cs | 104 +++--- .../MetaObjects.IntegrationTests.csproj | 9 + .../Runner/WriteCoercion.cs | 2 +- .../MetaObjects/Config/NeutralConfig.cs | 4 +- .../MetaObjects/Core/Field/FieldConstants.cs | 4 +- .../csharp/MetaObjects/Meta/PhysicalNaming.cs | 17 +- .../MetaObjects/SpecMetamodel/field.json | 2 +- server/java/codegen-kotlin/pom.xml | 8 + .../kotlin/KotlinDurationWireEmitter.kt | 92 +++-- .../kotlin/KotlinExposedTableGenerator.kt | 4 +- .../generator/kotlin/KotlinGenUtil.kt | 2 +- .../generator/kotlin/KotlinNamesGenerator.kt | 24 +- .../kotlin/KotlinReportExportGenerator.kt | 12 +- .../kotlin/KotlinDurationWireTest.kt | 65 ++-- .../kotlin/KotlinNamesGeneratorTest.kt | 49 +++ .../spring/SpringNamesGenerator.java | 41 ++- .../spring/SpringOutputParserGenerator.java | 2 +- .../spring/SpringReportExportGenerator.java | 16 +- .../spring/runtime/CanonicalDuration.java | 45 +-- .../SpringDurationWireCompileRunTest.java | 5 +- .../spring/SpringNamesGeneratorTest.java | 63 +++- .../spring/runtime/DurationWireTest.java | 30 +- .../metaobjects/database/ColumnNaming.java | 15 +- .../metaobjects/database/PhysicalNaming.java | 10 +- .../com/metaobjects/field/DurationField.java | 7 +- .../com/metaobjects/field/DurationWire.java | 89 ++--- .../field/DurationWireVectorsTest.java | 64 +++- server/python/src/metaobjects/cli.py | 5 +- .../codegen/generators/names_generator.py | 9 + .../codegen/runtime/duration_wire.py | 49 ++- .../src/metaobjects/config/dependencies.py | 4 - .../src/metaobjects/config/neutral_config.py | 26 +- .../src/metaobjects/config/source_resolver.py | 3 - server/python/src/metaobjects/enum_length.py | 82 ----- .../metaobjects/loader/meta_data_loader.py | 2 - .../meta/core/field/field_constants.py | 5 +- .../python/src/metaobjects/meta/meta_root.py | 4 - server/python/src/metaobjects/naming.py | 20 +- .../src/metaobjects/runtime/object_manager.py | 107 +++++- .../metaobjects/runtime/validator_runner.py | 2 +- .../src/metaobjects/spec_metamodel/field.json | 2 +- .../tests/codegen/test_duration_codegen.py | 5 +- .../tests/codegen/test_names_flattened.py | 9 + .../tests/config/test_neutral_config.py | 20 ++ .../test_enum_length_conformance.py | 65 ---- .../integration/test_duration_postgres.py | 56 +++ .../tests/runtime/test_duration_wire.py | 38 +- .../tests/runtime/test_validator_runner.py | 9 +- .../tests/unit/test_column_naming_strategy.py | 10 +- .../packages/cli/src/commands/gen.ts | 31 +- .../packages/cli/src/commands/migrate.ts | 104 ++++-- .../packages/cli/src/commands/verify.ts | 46 ++- .../packages/cli/src/lib/agent-schema.ts | 4 + .../packages/cli/src/lib/catalog-listing.ts | 5 +- .../packages/cli/src/lib/codegen-drift.ts | 3 +- .../cli/src/lib/collection-load-options.ts | 5 +- .../packages/cli/src/lib/fk-index-advisory.ts | 4 + .../cli/src/lib/gen-migrate-advice.ts | 5 + .../cli/src/lib/load-metaobjects-config.ts | 9 +- .../src/lib/referential-action-advisory.ts | 7 +- .../packages/cli/src/lib/schema-advisories.ts | 19 + .../cli/src/lib/schema-build-options.ts | 56 +++ .../migrate-checks-skip-redundant.test.ts | 121 +++++++ .../test/migrate-schema-conventions.test.ts | 49 ++- .../cli/test/unit/gen-migrate-advice.test.ts | 3 +- .../codegen-ts/src/contract/field-schema.ts | 18 +- .../packages/codegen-ts/src/generator.ts | 8 + .../src/generators/prisma-schema-file.ts | 1 + .../src/prisma/build-prisma-schema.ts | 8 +- .../codegen-ts/src/reference/prisma-schema.ts | 1 + .../packages/codegen-ts/src/runner.ts | 4 + .../src/templates/duration-wire-helper.ts | 25 +- .../codegen-ts/src/templates/names-decl.ts | 16 +- .../codegen-ts/src/templates/output-parser.ts | 2 +- .../src/templates/zod-validators.ts | 2 +- .../test/contract/contract-behaviours.test.ts | 8 +- .../duration-json-schema-pattern.test.ts | 21 +- .../test/duration-wire-helper.test.ts | 55 +-- .../codegen-ts/test/names-flattened.test.ts | 92 ++++- .../output-parser-subtype-coverage.test.ts | 2 +- .../test/prisma/prisma-schema.test.ts | 22 ++ .../test/templates/zod-validators.test.ts | 3 +- .../test/zod-validators-execution.test.ts | 4 +- .../metadata/src/core/field/duration-wire.ts | 24 +- .../core/field/field-definition.embedded.ts | 2 +- .../typescript/packages/metadata/src/index.ts | 2 +- .../packages/metadata/src/naming.ts | 19 +- .../packages/metadata/src/shared/meta-root.ts | 9 - .../packages/metadata/test/naming.test.ts | 10 +- .../migrate-ts/src/check-expression.ts | 25 +- .../packages/migrate-ts/src/diff/index.ts | 53 ++- .../packages/migrate-ts/src/drift/drift.ts | 8 +- .../packages/migrate-ts/src/errors.ts | 9 +- .../migrate-ts/src/expected-schema.ts | 76 +++- .../packages/migrate-ts/src/expected.ts | 2 +- .../packages/migrate-ts/src/index.ts | 4 +- .../migrate-ts/src/schema-conventions.ts | 45 ++- .../packages/migrate-ts/src/snapshot/plan.ts | 10 +- .../packages/migrate-ts/src/types.ts | 16 + .../pg-cross-field-checks-roundtrip.test.ts | 15 + .../integration/pg-duration-roundtrip.test.ts | 10 +- .../test/unit/check-redundant.test.ts | 65 +++- .../unit/cross-field-check-extensions.test.ts | 67 +++- .../test/unit/duration-column.test.ts | 20 ++ .../unit/expected-schema-conventions.test.ts | 21 +- .../test/unit/identity-sequence.test.ts | 9 +- .../test/unit/schema-conventions.test.ts | 24 +- .../src/drivers/in-memory-driver.ts | 34 +- .../drizzle-fastify/filter-value-format.ts | 2 +- .../packages/runtime-ts/src/query-builder.ts | 1 + .../packages/runtime-ts/src/type-coercer.ts | 10 +- .../runtime-ts/src/validator-runner.ts | 4 +- .../test/duration-wire-vectors.test.ts | 59 ++-- .../test/object-manager-duration.test.ts | 25 +- .../typescript/packages/sdk/src/collection.ts | 6 + server/typescript/packages/sdk/src/config.ts | 4 + server/typescript/packages/sdk/src/memory.ts | 14 +- .../test/schema-conventions-config.test.ts | 52 ++- .../src/templates/duration-wire-helper.ts | 25 +- .../src/templates/zod-validators.ts | 2 +- site-reference/index.html | 2 +- site-reference/types/field.html | 2 +- .../ADR-0058-one-physical-naming-setting.md | 4 +- spec/metamodel/field.json | 2 +- 188 files changed, 3271 insertions(+), 1642 deletions(-) create mode 100644 server/csharp/MetaObjects.IntegrationTests/DurationIntervalEfCoreTests.cs delete mode 100644 server/python/src/metaobjects/enum_length.py delete mode 100644 server/python/tests/conformance/test_enum_length_conformance.py create mode 100644 server/typescript/packages/cli/src/lib/schema-advisories.ts create mode 100644 server/typescript/packages/cli/src/lib/schema-build-options.ts create mode 100644 server/typescript/packages/cli/test/migrate-checks-skip-redundant.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 50ea77fc74..f0fd08cf71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,9 @@ loading. A port that reports `1.2` does not know that vocabulary; upgrade every a Postgres `interval` column, and a 64-bit integer of microseconds on SQLite, D1 and MySQL, so sorting and range filters follow the span on every database. The wire form is an ISO-8601 duration of days, hours, minutes and seconds, and every port writes the same canonical form (`PT1H30M`, - `PT26H`, `-PT1M30S`, `PT0S`); years, months and weeks are refused. Postgres does not accept a + `PT26H`, `-PT1M30S`, `PT0S`), with as many fractional digits as its own duration type holds (6 in + TypeScript and Python, 7 in C#, 9 in Java and Kotlin). A week is 7 days and a day 24 hours; years + and months are refused. Postgres does not accept a signed ISO-8601 duration as input, so a value bound as text, and a declared `@default`, use its own `HH:MM:SS` spelling, which it returns unchanged. Filters: every numeric operator. Shared vectors in `fixtures/duration-wire/`; see `docs/features/field-types.md`. Each port is @@ -92,19 +94,21 @@ loading. A port that reports `1.2` does not know that vocabulary; upgrade every - **A string-stored enum's column length: `@maxLength` on `field.enum`, and `enums.maxLength`.** `@maxLength` on a `field.enum` makes its column `VARCHAR(n)`, and `"enums": { "maxLength": n }` in `.metaobjects/config.json` gives every enum without one a default; with neither, the column - stays unbounded text, as before. Every port reads the setting and resolves the length through - one core function (`resolveEnumMaxLength`, `EnumLength.ResolveMaxLength`, - `EnumLength.resolveMaxLength`, `resolve_enum_max_length`), and `meta migrate`, the Drizzle, - Prisma, EF Core and Exposed bindings use it. A member longer than the length is refused + stays unbounded text, as before. The ports that size a column resolve the length through one + core function (`resolveEnumMaxLength` in TypeScript, `EnumLength.ResolveMaxLength` in C#, + `EnumLength.resolveMaxLength` on the JVM), and `meta migrate`, the Drizzle, Prisma, EF Core and + Exposed bindings use it. Python emits no column types, so it accepts the `enums` block and + sizes nothing. A member longer than the length is refused (`ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH`): at load for `@maxLength`, when the column is sized for the project default, which `meta migrate` and `meta verify` report by name. `@maxLength` beside `@intValueMap` is refused at load (`ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP`). A new shared - corpus, `fixtures/enum-length-conformance/`, pins the resolution in every port. -- **A `PascalCase` column rule.** `"naming": { "columns": "PascalCase" }` in + corpus, `fixtures/enum-length-conformance/`, pins the resolution in those ports. +- **An `upperFirst` column rule.** `"naming": { "columns": "upperFirst" }` in `.metaobjects/config.json` upper-cases a field name's first letter and changes nothing else - (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`), in every port: the column names EF Core - creates, so a camelCase model over an EF-built schema needs `@column` only where the database - spells a name differently. A column rule only; `literal` tables keep a PascalCase object name. + (`createdAt` → `CreatedAt`, `requestURL` → `RequestURL`, `address_line1` → `Address_line1`), in + every port. A schema whose columns are the field names with a capital first letter (EF Core's + default, for one) then needs `@column` only where the database spells a name differently. A + column rule only; `literal` tables keep an object name verbatim. See `docs/features/migrations/physical-naming.md`. - **Schema conventions for the database objects no code addresses.** `migrate.conventions` in `.metaobjects/config.json` picks how `meta migrate` names primary-key and foreign-key @@ -112,14 +116,18 @@ loading. A port that reports `1.2` does not know that vocabulary; upgrade every is a constraint or an index. `default` is what migrate has always emitted, so nothing changes unless you set it. `efcore` reproduces EF Core's conventions (`PK_`, `FK_`, `IX_`, its 63-character `~` truncation, alternate keys as constraints), so a database built by EF Core - migrations and one built by `meta migrate` match. It also leaves out the CHECKs a column type - already guarantees (`skipRedundantChecks`): a `validator.length` maximum the column's - `VARCHAR(n)` enforces (not on SQLite or D1, which do not enforce one), and a minimum of 0 or - less; an EF Core database has none of them. A project can supply its own conventions + migrations and one built by `meta migrate` match. A project can supply its own conventions object from `metaobjects.config.ts`; an unknown preset name, or an object missing a member, is refused by name. The PK name is now introspected too, so a `baseline --from-db` snapshot of a database whose primary keys are not named `
    @max int no
    @conditionexpressionnometaobjects-core-typesThe case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself.
    @constraintNamestringnometaobjects-dbThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index 79734985ba..e1d1cb0327 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -59,6 +59,20 @@ { "type": "attr", "subType": "string", "name": "using", "min": 0, "max": 1, "description": "Index access method (e.g. \"gin\", \"gist\", \"hash\"); default \"btree\" (not rendered). Pair with @expr for e.g. a GIN index over an array/jsonb expression. RDB-physical — contributed by the db provider." } ] }, + { + "type": "field", + "subType": "enum", + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    @equals string yes
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + ] + }, + { + "type": "validator", + "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], + "children": [ + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + ] + }, { "type": "identity", "subType": "primary", diff --git a/spec/metamodel/validator.json b/spec/metamodel/validator.json index 9520605bd7..43a306ddc3 100644 --- a/spec/metamodel/validator.json +++ b/spec/metamodel/validator.json @@ -66,7 +66,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "left", "min": 1, "max": 1, "description": "Name of the left-hand field of the owning entity." }, { "type": "attr", "subType": "string", "name": "op", "min": 1, "max": 1, "allowedValues": ["gt", "gte", "lt", "lte", "ne", "eq"], "description": "Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=)." }, - { "type": "attr", "subType": "string", "name": "right", "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." } + { "type": "attr", "subType": "string", "name": "right", "min": 1, "max": 1, "description": "Name of the right-hand field of the owning entity." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -78,7 +79,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "field", "min": 1, "max": 1, "description": "Name of the field that becomes required when the condition holds." }, { "type": "attr", "subType": "string", "name": "when", "min": 1, "max": 1, "description": "Name of the gating field whose value triggers the requirement." }, - { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." } + { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; when @when equals this, @field must be present." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -90,7 +92,8 @@ "children": [ { "type": "attr", "subType": "string", "name": "field", "min": 1, "max": 1, "description": "Name of the field whose presence is governed by the condition." }, { "type": "attr", "subType": "string", "name": "when", "min": 1, "max": 1, "description": "Name of the gating field." }, - { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." } + { "type": "attr", "subType": "string", "name": "equals", "min": 1, "max": 1, "description": "The gating value; @field is present exactly when @when equals this." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." } ] }, { @@ -100,7 +103,9 @@ "whenToUse": "At least one of several fields must be present (email or phone). Declare it instead of hand-written OR-presence checks.", "rules": "@fields names two or more fields of the owning entity. Satisfied when any one of them is non-null.", "children": [ - { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." } + { "type": "attr", "subType": "string", "name": "fields", "isArray": true, "min": 1, "max": 1, "description": "Names of the candidate fields; at least one must be present." }, + { "type": "attr", "subType": "expression", "name": "condition", "min": 0, "max": 1, "description": "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself." }, + { "type": "attr", "subType": "int", "name": "max", "min": 0, "max": 1, "description": "The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE)." } ] } ] From de6b8320d7133ad4ac4993bdcc343a94d13f4a8b Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Tue, 3 Nov 2026 07:50:19 -0500 Subject: [PATCH 024/267] fix(schema): the review's findings on validator CHECK names and conditions - atLeastOne @max above 1 is two comparisons, not BETWEEN: Postgres stores a BETWEEN as two comparisons, so the CHECK drifted on every run without the canonicalisation probe. A live-PG test applies the new CHECKs and re-diffs. - @condition is type-checked at load in every port: a boolean expression, a literal of its field's kind (an enum member for field.enum), no null literal. A compound comparison operand is parenthesised, and an int-backed enum member is compared as its stored integer. - A declared CHECK name another constraint on the table has, or one over 63 bytes on Postgres, is refused by migrate and verify (ERR_CHECK_NAME). A declared name keeps a length CHECK the efcore conventions would skip. - Docs: where @constraintName is allowed, rename behaviour on SQLite, the docs site's rendering of @max and @condition, the authoring skill's table. - C# CHECK_VALIDATOR_SUBTYPES is an IReadOnlyList; misplaced doc comments. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 14 +- .../skills/metaobjects-authoring/SKILL.md | 7 +- docs/CONFORMANCE.md | 6 +- docs/features/migrations-and-drift.md | 24 ++- examples/showcase/site-payload.json | 4 +- .../skills/metaobjects-authoring/SKILL.md | 7 +- .../skills/metaobjects-authoring/SKILL.md | 7 +- .../skills/metaobjects-authoring/SKILL.md | 7 +- .../skills/metaobjects-authoring/SKILL.md | 7 +- .../skills/metaobjects-authoring/SKILL.md | 7 +- .../expected-errors.json | 15 ++ .../input/meta.checks.json | 62 ++++++++ .../expected-errors.json | 55 +++++++ .../input/meta.checks.json | 136 ++++++++++++++++ .../expected-errors.json | 35 +++++ .../input/meta.checks.json | 105 +++++++++++++ .../Core/Attr/ExpressionGrammar.cs | 18 +-- .../Core/Validator/ValidatorConstants.cs | 2 +- .../Core/Validator/ValidatorSchema.cs | 8 +- .../MetaObjects/Loader/ValidationPasses.cs | 131 +++++++++++++--- .../metaobjects/loader/ValidationPhase.java | 146 +++++++++++++++--- .../metaobjects/loader/validation_passes.py | 113 +++++++++++++- .../packages/cli/src/commands/migrate.ts | 5 + .../packages/cli/src/commands/verify.ts | 7 + .../cli/test/verify-schema-refusals.test.ts | 25 +++ .../docs-site/src/builders/object-data.ts | 27 +++- .../metadata/src/loader/validation-passes.ts | 66 +++++++- .../migrate-ts/src/check-expression.ts | 35 ++++- .../packages/migrate-ts/src/errors.ts | 39 +++++ .../migrate-ts/src/expected-schema.ts | 86 +++++++++-- .../packages/migrate-ts/src/index.ts | 4 +- .../pg-cross-field-checks-roundtrip.test.ts | 88 +++++++++++ .../unit/cross-field-check-extensions.test.ts | 117 +++++++++++++- 34 files changed, 1312 insertions(+), 105 deletions(-) create mode 100644 fixtures/conformance/error-validator-at-least-one-max-zero/expected-errors.json create mode 100644 fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json create mode 100644 fixtures/conformance/error-validator-condition-type/expected-errors.json create mode 100644 fixtures/conformance/error-validator-condition-type/input/meta.checks.json create mode 100644 fixtures/conformance/error-validator-condition-unknown-fields/expected-errors.json create mode 100644 fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json create mode 100644 server/typescript/packages/migrate-ts/test/integration/pg-cross-field-checks-roundtrip.test.ts diff --git a/AGENTS.md b/AGENTS.md index 02dec857e5..68abde0b54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (433 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (436 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e085f0094..91bc316ba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,15 +12,19 @@ here.** ### Added -- **CHECK names, conditions and "exactly one" from validators.** `@constraintName` on any - `validator.*` node, and on a `field.enum` for its membership CHECK, names the CHECK `meta migrate` +- **CHECK names, conditions and "exactly one" from validators.** `@constraintName` on a validator + that generates a CHECK (`numeric`, `length`, `regex` and the cross-field four), and on a + `field.enum` for its membership CHECK, names the CHECK `meta migrate` generates, for a database whose CHECKs were named by hand. A cross-field validator (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) takes `@condition`, an expression over the entity's fields, so the rule holds only where it does. `validator.atLeastOne` takes `@max`; `@max: 1` is exactly one of its `@fields`. All three are database-only and optional; a model - without them generates what it did. A `@condition` naming a field the entity does not have, or a - `@max` outside 1 to the number of `@fields`, is refused at load (`ERR_BAD_ATTR_VALUE`) in every - port. See `docs/features/migrations-and-drift.md`, "CHECKs from validators". + without them generates what it did. A `@condition` naming a field the entity does not have, one + that is not a boolean expression, one comparing a field with a literal of another kind (or with + `null`), or a `@max` outside 1 to the number of `@fields`, is refused at load + (`ERR_BAD_ATTR_VALUE`) in every port. A declared CHECK name another constraint on the table + already has, or one over 63 bytes on Postgres, is refused by `meta migrate` and `meta verify` + (`ERR_CHECK_NAME`). See `docs/features/migrations-and-drift.md`, "CHECKs from validators". - **Contract emitters: JSON Schema and OpenAPI generators (FR-022).** `jsonSchemaFile()` (`contract-schema`) writes JSON Schema 2020-12 for each object's read, create and update shapes, and a strict structured-output subset with `profile: "strict"`. `openApiFile()` (`openapi`) writes one diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md index d3c3fdad9d..ad11e13b60 100644 --- a/agent-context/skills/metaobjects-authoring/SKILL.md +++ b/agent-context/skills/metaobjects-authoring/SKILL.md @@ -436,13 +436,18 @@ enforcement (a CHECK constraint / cross-field assertion) — no raw expression i | `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | -| `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.atLeastOne` | at least one of `@fields` (2+) is present; with `@max`, at most that many (`@max: 1` = exactly one) | `@fields`, `@max` | + +All four take an optional `@condition`, an expression over the entity's fields (the +`origin.computed` grammar): the rule then holds only where the condition does. And every validator +that becomes a CHECK takes an optional db-provider `@constraintName` naming it. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 2bd138db15..d753e82668 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 433 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 436 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -286,7 +286,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (433) +### `fixtures/conformance/` — metamodel loader + canonical serializer (436) | Fixture prefix | Feature doc | |---|---| @@ -612,7 +612,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 433 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 436 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index cad515937e..51093e41a5 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -414,16 +414,26 @@ the re-diff is empty afterwards. Postgres keeps `IS [NOT] DISTINCT FROM`. A `validator.*` node and a `field.enum`'s member list each become a CHECK constraint. Three attributes shape it, all database-only (no generated code reads them): -- **`@constraintName`** names the CHECK, for a database whose CHECKs were named by hand. On any - `validator.*` node, and on a `field.enum` for its membership CHECK. Absent, the name is derived - (`
    ___chk`, `
    __chk` for an enum), as before. +- **`@constraintName`** names the CHECK, for a database whose CHECKs were named by hand. On the + validators that generate a CHECK (`numeric`, `length`, `regex`, `comparison`, `requiredWhen`, + `presentIff`, `atLeastOne`; `required` is a NOT NULL, not a CHECK), and on a `field.enum` for its + membership CHECK. Absent, the name is derived (`
    ___chk`, + `
    __chk` for an enum), as before. A declared name is refused (`ERR_CHECK_NAME`) when + another constraint on the table already has it, or, on Postgres, when it is over 63 bytes + (Postgres would truncate it, and the CHECK would never match its declaration). Under the + `efcore` conventions, a `validator.length` with a declared name is kept even where the column's + length already enforces it. - **`@condition`** on a cross-field validator (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) is an expression, in the grammar `origin.computed` uses, over the entity's fields. The rule holds only where the condition does: the CHECK is `(NOT condition) OR (rule)`, with - the negation folded in (`kind = 'Clinic'` becomes `kind <> 'Clinic'`). A field the condition - names that is not a field of the entity is refused at load (`ERR_BAD_ATTR_VALUE`). + the negation folded in (`kind = 'Clinic'` becomes `kind <> 'Clinic'`). It is checked at load + (`ERR_BAD_ATTR_VALUE`): every field it names is a field of the entity, it is a boolean + expression, a literal compared with a field is of that field's kind (and, for an enum, one of + its `@values`), and no comparison has a `null` literal (`x = NULL` is never true: use `isNull` + or `isNotNull`). An int-backed enum's member is compared as its stored integer. - **`@max`** on `validator.atLeastOne` caps how many of its `@fields` may be present. `@max: 1` is "exactly one": `num_nonnulls(a, b) = 1` on Postgres, a sum of `IS NOT NULL` tests on SQLite. + A higher `@max` is `count >= 1 AND count <= max`. It must be between 1 and the number of `@fields` (`ERR_BAD_ATTR_VALUE`). ```json @@ -442,7 +452,9 @@ attributes shape it, all database-only (no generated code reads them): On Postgres the last one is `CK_Notes_Owner CHECK (("kind" <> 'Owned') OR (num_nonnulls("patient_id", "case_id") = 1))`. -Renaming a CHECK this way is a drop and an add of the same rule, under `--allow drop-check`. +Renaming a CHECK this way is a drop and an add of the same rule on Postgres, under +`--allow drop-check`. On SQLite and D1 a CHECK is matched by its expression when the name does not +match, so a rename alone proposes nothing and the database keeps the old name. ## Schema conventions: names for objects no code addresses diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index e38fa75291..6a33118e7e 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,8 +7,8 @@ "metamodel": "1.2" }, "counts": { - "fixtures": 433, - "corpora": 36, + "fixtures": 436, + "corpora": 37, "baseTypes": 17 }, "snippets": { diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index d3c3fdad9d..ad11e13b60 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -436,13 +436,18 @@ enforcement (a CHECK constraint / cross-field assertion) — no raw expression i | `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | -| `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.atLeastOne` | at least one of `@fields` (2+) is present; with `@max`, at most that many (`@max: 1` = exactly one) | `@fields`, `@max` | + +All four take an optional `@condition`, an expression over the entity's fields (the +`origin.computed` grammar): the rule then holds only where the condition does. And every validator +that becomes a CHECK takes an optional db-provider `@constraintName` naming it. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md index d3c3fdad9d..ad11e13b60 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -436,13 +436,18 @@ enforcement (a CHECK constraint / cross-field assertion) — no raw expression i | `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | -| `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.atLeastOne` | at least one of `@fields` (2+) is present; with `@max`, at most that many (`@max: 1` = exactly one) | `@fields`, `@max` | + +All four take an optional `@condition`, an expression over the entity's fields (the +`origin.computed` grammar): the rule then holds only where the condition does. And every validator +that becomes a CHECK takes an optional db-provider `@constraintName` naming it. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md index d3c3fdad9d..ad11e13b60 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -436,13 +436,18 @@ enforcement (a CHECK constraint / cross-field assertion) — no raw expression i | `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | -| `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.atLeastOne` | at least one of `@fields` (2+) is present; with `@max`, at most that many (`@max: 1` = exactly one) | `@fields`, `@max` | + +All four take an optional `@condition`, an expression over the entity's fields (the +`origin.computed` grammar): the rule then holds only where the condition does. And every validator +that becomes a CHECK takes an optional db-provider `@constraintName` naming it. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index d3c3fdad9d..ad11e13b60 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -436,13 +436,18 @@ enforcement (a CHECK constraint / cross-field assertion) — no raw expression i | `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | -| `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.atLeastOne` | at least one of `@fields` (2+) is present; with `@max`, at most that many (`@max: 1` = exactly one) | `@fields`, `@max` | + +All four take an optional `@condition`, an expression over the entity's fields (the +`origin.computed` grammar): the rule then holds only where the condition does. And every validator +that becomes a CHECK takes an optional db-provider `@constraintName` naming it. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md index d3c3fdad9d..ad11e13b60 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -436,13 +436,18 @@ enforcement (a CHECK constraint / cross-field assertion) — no raw expression i | `validator.comparison` | two fields stand in a relational order (`@left @op @right`) | `@left`, `@op` (`gt`/`gte`/`lt`/`lte`/`ne`/`eq`), `@right` | | `validator.requiredWhen` | `@field` is required when `@when` equals `@equals` | `@field`, `@when`, `@equals` | | `validator.presentIff` | `@field` is present **iff** `@when` equals `@equals` (biconditional) | `@field`, `@when`, `@equals` | -| `validator.atLeastOne` | at least one of `@fields` (2+) is present | `@fields` | +| `validator.atLeastOne` | at least one of `@fields` (2+) is present; with `@max`, at most that many (`@max: 1` = exactly one) | `@fields`, `@max` | + +All four take an optional `@condition`, an expression over the entity's fields (the +`origin.computed` grammar): the rule then holds only where the condition does. And every validator +that becomes a CHECK takes an optional db-provider `@constraintName` naming it. ```json { "validator.comparison": { "name": "hpInRange", "@left": "currentHp", "@op": "lte", "@right": "maxHp" } } { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/conformance/error-validator-at-least-one-max-zero/expected-errors.json b/fixtures/conformance/error-validator-at-least-one-max-zero/expected-errors.json new file mode 100644 index 0000000000..7f6dc3760e --- /dev/null +++ b/fixtures/conformance/error-validator-at-least-one-max-zero/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[7]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json b/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json new file mode 100644 index 0000000000..f99b2161d4 --- /dev/null +++ b/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json @@ -0,0 +1,62 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { + "source.rdb": {} + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "field.boolean": { + "name": "active" + } + }, + { + "field.enum": { + "name": "kind", + "@values": [ + "Owned", + "Shared" + ] + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id" + } + }, + { + "validator.atLeastOne": { + "name": "none", + "@fields": [ + "patientId", + "caregiverId" + ], + "@max": 0 + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-validator-condition-type/expected-errors.json b/fixtures/conformance/error-validator-condition-type/expected-errors.json new file mode 100644 index 0000000000..1d444732f3 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-type/expected-errors.json @@ -0,0 +1,55 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[7]['validator.atLeastOne']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[8]['validator.atLeastOne']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[9]['validator.atLeastOne']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[10]['validator.atLeastOne']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[11]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-validator-condition-type/input/meta.checks.json b/fixtures/conformance/error-validator-condition-type/input/meta.checks.json new file mode 100644 index 0000000000..2e6a63b835 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-type/input/meta.checks.json @@ -0,0 +1,136 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { + "source.rdb": {} + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "field.boolean": { + "name": "active" + } + }, + { + "field.enum": { + "name": "kind", + "@values": [ + "Owned", + "Shared" + ] + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id" + } + }, + { + "validator.atLeastOne": { + "name": "notBoolean", + "@fields": [ + "patientId", + "caregiverId" + ], + "@condition": { + "field": "patientId" + } + } + }, + { + "validator.atLeastOne": { + "name": "booleanAsString", + "@fields": [ + "patientId", + "caregiverId" + ], + "@condition": { + "op": "eq", + "left": { + "field": "active" + }, + "right": { + "value": "true" + } + } + } + }, + { + "validator.atLeastOne": { + "name": "nullLiteral", + "@fields": [ + "patientId", + "caregiverId" + ], + "@condition": { + "op": "ne", + "left": { + "field": "patientId" + }, + "right": { + "value": null + } + } + } + }, + { + "validator.atLeastOne": { + "name": "notAMember", + "@fields": [ + "patientId", + "caregiverId" + ], + "@condition": { + "op": "eq", + "left": { + "field": "kind" + }, + "right": { + "value": "Nope" + } + } + } + }, + { + "validator.atLeastOne": { + "name": "numberAsString", + "@fields": [ + "patientId", + "caregiverId" + ], + "@condition": { + "op": "eq", + "left": { + "value": "5" + }, + "right": { + "field": "patientId" + } + } + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-validator-condition-unknown-fields/expected-errors.json b/fixtures/conformance/error-validator-condition-unknown-fields/expected-errors.json new file mode 100644 index 0000000000..d0e328844e --- /dev/null +++ b/fixtures/conformance/error-validator-condition-unknown-fields/expected-errors.json @@ -0,0 +1,35 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[7]['validator.requiredWhen']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[8]['validator.presentIff']" + } + }, + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[9]['validator.comparison']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json b/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json new file mode 100644 index 0000000000..9c3acba6d8 --- /dev/null +++ b/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json @@ -0,0 +1,105 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { + "source.rdb": {} + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "patientId" + } + }, + { + "field.long": { + "name": "caregiverId" + } + }, + { + "field.boolean": { + "name": "active" + } + }, + { + "field.enum": { + "name": "kind", + "@values": [ + "Owned", + "Shared" + ] + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": "id" + } + }, + { + "validator.requiredWhen": { + "name": "rw", + "@field": "patientId", + "@when": "kind", + "@equals": "Owned", + "@condition": { + "op": "and", + "args": [ + { + "op": "isNull", + "arg": { + "field": "nosuch" + } + }, + { + "op": "isNull", + "arg": { + "field": "other" + } + } + ] + } + } + }, + { + "validator.presentIff": { + "name": "pi", + "@field": "caregiverId", + "@when": "kind", + "@equals": "Shared", + "@condition": { + "op": "isNotNull", + "arg": { + "field": "gone" + } + } + } + }, + { + "validator.comparison": { + "name": "cmp", + "@left": "patientId", + "@op": "lt", + "@right": "caregiverId", + "@condition": { + "op": "isNotNull", + "arg": { + "field": "missing" + } + } + } + } + ] + } + } + ] + } +} diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index aef27002ed..ac96a913b3 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -57,15 +57,6 @@ public static class ExpressionGrammar FILTER_COMPOSE_AND, FILTER_COMPOSE_OR, }; - // ------------------------------------------------------------------------- - // Structural validation — known node kinds, ops, arity. No entity/type - // context (see InferExprType for typing). Returns [] when valid. - // ------------------------------------------------------------------------- - - /// - /// Structural well-formedness of an expression tree (known node kinds, ops, - /// arity). Returns an empty list when valid. Mirrors TS validateExprNode. - /// /// The field names an expression tree references, in order of appearance. public static List FieldRefs(object? node) { @@ -83,6 +74,15 @@ void Walk(object? x) return refs; } + // ------------------------------------------------------------------------- + // Structural validation — known node kinds, ops, arity. No entity/type + // context (see InferExprType for typing). Returns [] when valid. + // ------------------------------------------------------------------------- + + /// + /// Structural well-formedness of an expression tree (known node kinds, ops, + /// arity). Returns an empty list when valid. Mirrors TS validateExprNode. + /// public static List ValidateExprNode(object? node) { if (node is not IReadOnlyDictionary n) diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs index e5e556e859..f957d03cfd 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs @@ -56,7 +56,7 @@ public static class ValidatorConstants /// The validators meta migrate renders as a CHECK (and so may carry @constraintName): /// numeric, length, regex and the cross-field ones. required is NOT NULL; array and base have none. - public static readonly string[] CHECK_VALIDATOR_SUBTYPES = + public static readonly IReadOnlyList CHECK_VALIDATOR_SUBTYPES = [ VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX, VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, VALIDATOR_SUBTYPE_PRESENT_IFF, diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs index 220bd34206..69925ce443 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorSchema.cs @@ -26,15 +26,15 @@ public static class ValidatorSchema Description: "Maximum allowed value (length, numeric value, or array element count depending on the validator subtype)."), ]; - /// - /// Attrs per validator subtype. required uses none; regex adds @pattern; - /// length / numeric / array (and the base) use @min / @max. - /// /// @condition on a cross-field validator: the case the rule applies in (an attr.expression). private static readonly AttrSchema ConditionAttr = new(Name: ValidatorConstants.VALIDATOR_ATTR_CONDITION, ValueType: AttrConstants.ATTR_SUBTYPE_EXPRESSION, Required: false, Description: "The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself."); + /// + /// Attrs per validator subtype. required uses none; regex adds @pattern; + /// length / numeric / array (and the base) use @min / @max. + /// public static readonly IReadOnlyDictionary> ValidatorAttrsMap = new Dictionary> { diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 85f2480578..a18a99868b 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2090,27 +2090,12 @@ private static void ValidateAttrSchemaNode( } } - // --------------------------------------------------------------------------- - // field.enum @maxLength — the column length of a string-stored enum: - // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the - // longest offender named; - // 2. it is refused beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP): an - // int-stored enum's column is an integer, so a length would change nothing. - // Read RESOLVING (ADR-0039), reported on the node that DECLARES one of the three, so an - // enum that only inherits them is not reported twice. Every field.enum in the tree is - // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. - // --------------------------------------------------------------------------- - // --------------------------------------------------------------------------- - // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation - // "increment" key draws from; on any other generation there is none, so either one is - // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the - // identity that declares one of them. Mirrors TS validateIdentitySequence. - // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the - // database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, and - // every field a @condition names a field of the owning entity (ERR_BAD_ATTR_VALUE). Read - // RESOLVING (ADR-0039). Mirrors TS validateCrossFieldValidators. + // database enforces as CHECKs (ERR_BAD_ATTR_VALUE): atLeastOne @max is between 1 and the + // number of its @fields; every field a @condition names is a field of the owning entity; + // and the @condition can become a CHECK guard (ConditionProblem). Read RESOLVING + // (ADR-0039). Mirrors TS validateCrossFieldValidators. // --------------------------------------------------------------------------- private static readonly HashSet CrossFieldValidatorSubtypes = new(StringComparer.Ordinal) { @@ -2146,22 +2131,118 @@ public static IReadOnlyList ValidateCrossFieldValidators(MetaData roo } var condition = v.Attr(VALIDATOR_ATTR_CONDITION); if (condition is null) continue; + var label = $"validator.{v.SubType} \"{obj.Name}.{v.Name}\" @condition"; var unknown = MetaObjects.Core.Attr.ExpressionGrammar.FieldRefs(condition) .Distinct(StringComparer.Ordinal).Where(f => !fieldNames.Contains(f)) .OrderBy(f => f, StringComparer.Ordinal).ToList(); if (unknown.Count > 0) { errors.Add(new MetaError( - $"validator.{v.SubType} \"{obj.Name}.{v.Name}\" @condition names {string.Join(", ", unknown.Select(f => $"\"{f}\""))}, " + + $"{label} names {string.Join(", ", unknown.Select(f => $"\"{f}\""))}, " + $"which {(unknown.Count == 1 ? "is not a field" : "are not fields")} of \"{obj.Name}\".", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: v.Source)); + continue; + } + if (ConditionProblem(condition, obj) is { } problem) + { + errors.Add(new MetaError($"{label} {problem}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: v.Source)); } } } return errors; } + /// Field subtypes whose values a condition compares with a number literal. + private static readonly HashSet ConditionNumberSubtypes = new(StringComparer.Ordinal) + { + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, + }; + + /// + /// Why a cross-field validator's @condition cannot become a CHECK guard, or null when + /// it can. Its names are already known to be fields. The rule, the same in every port: + /// it types cleanly (the origin.computed inference) and its root is boolean, since a CHECK + /// negates it; a literal compared with a field is of that field's kind (a boolean for + /// field.boolean, a number for a numeric field, a string otherwise) and, for field.enum, one + /// of its @values; and no comparison has a null literal (x = NULL is never true, so + /// use isNull / isNotNull). Mirrors TS conditionProblem. + /// + private static string? ConditionProblem(object condition, MetaObject obj) + { + var fields = new Dictionary(StringComparer.Ordinal); + foreach (var f in obj.Fields()) fields.TryAdd(f.Name, f); + var inferred = MetaObjects.Core.Attr.ExpressionGrammar.InferExprType( + condition, name => fields.TryGetValue(name, out var f) ? f.SubType : null); + if (inferred.Errors.Count > 0) return $"is not a valid expression: {string.Join("; ", inferred.Errors)}."; + if (inferred.Type != FIELD_SUBTYPE_BOOLEAN) + { + return $"must be a boolean expression (a comparison, a null test, or and / or / not of them), not a field.{inferred.Type ?? "undefined"}."; + } + string? problem = null; + void Visit(object? node) + { + if (problem is not null || node is not IReadOnlyDictionary n) return; + if (n.TryGetValue("left", out var left) && left is not null && n.TryGetValue("right", out var right) && right is not null) + { + foreach (var (a, b) in new[] { (left, right), (right, left) }) + { + if (a is not IReadOnlyDictionary lit || !lit.TryGetValue("value", out var value)) continue; + if (value is null) + { + problem = "compares with null, which is never true: use isNull or isNotNull."; + return; + } + if (b is not IReadOnlyDictionary refNode + || !refNode.TryGetValue("field", out var refName) || refName is not string name + || !fields.TryGetValue(name, out var field)) + { + continue; + } + var kind = field.SubType == FIELD_SUBTYPE_BOOLEAN ? "boolean" + : ConditionNumberSubtypes.Contains(field.SubType) ? "number" : "string"; + var actual = value switch + { + bool => "boolean", + long or int or double => "number", + string => "string", + _ => null, + }; + if (actual != kind) + { + problem = $"compares \"{field.Name}\" (field.{field.SubType}) with {JsonStringify(value)}; it needs a {kind}."; + return; + } + var members = field.SubType == FIELD_SUBTYPE_ENUM ? field.EffectiveEnumValues : null; + if (members is not null && !members.Contains(Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture), StringComparer.Ordinal)) + { + problem = $"compares \"{field.Name}\" with {JsonStringify(value)}, which is not one of its @values ({string.Join(", ", members)})."; + return; + } + } + } + n.TryGetValue("left", out var l); + Visit(l); + n.TryGetValue("right", out var r); + Visit(r); + n.TryGetValue("arg", out var g); + Visit(g); + if (n.TryGetValue("args", out var args) && args is IEnumerable list) + { + foreach (var x in list) Visit(x); + } + } + Visit(condition); + return problem; + } + + // --------------------------------------------------------------------------- + // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation + // "increment" key draws from; on any other generation there is none, so either one is + // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the + // identity that declares one of them. Mirrors TS validateIdentitySequence. + // --------------------------------------------------------------------------- public static IReadOnlyList ValidateIdentitySequence(MetaData root) { var errors = new List(); @@ -2212,6 +2293,16 @@ public static IReadOnlyList ValidateIdentitySequence(MetaData root) return errors; } + // --------------------------------------------------------------------------- + // field.enum @maxLength — the column length of a string-stored enum: + // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the + // longest offender named; + // 2. it is refused beside @intValueMap (ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP): an + // int-stored enum's column is an integer, so a length would change nothing. + // Read RESOLVING (ADR-0039), reported on the node that DECLARES one of the three, so an + // enum that only inherits them is not reported twice. Every field.enum in the tree is + // checked, root-level abstract enums included. Mirrors TS validateEnumMaxLength. + // --------------------------------------------------------------------------- public static IReadOnlyList ValidateEnumMaxLength(MetaData root) { var errors = new List(); diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 6acaa3d171..3ecd4a8e94 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -2383,16 +2383,12 @@ private static List junctionReferenceFkFields(MetaObject junction) { // ========================================================================= // ========================================================================= - // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation - // "increment" key draws from; on any other generation there is none, so either one is - // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the - // identity that declares one of them, every offender collected. Mirrors TS. - // ========================================================================= - // Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the - // database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, and - // every field a @condition names a field of the owning entity (ERR_BAD_ATTR_VALUE). Every - // violation is collected. Mirrors TS validateCrossFieldValidators. + // database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields; + // every field a @condition names is a field of the owning entity; and the @condition can + // become a CHECK guard (see conditionProblem). ERR_BAD_ATTR_VALUE, one per validator, + // every violation collected. Mirrors TS validateCrossFieldValidators. + // ========================================================================= static void validateCrossFieldValidators(MetaRoot root, List out) { java.util.Set crossField = java.util.Set.of( com.metaobjects.validator.ComparisonValidator.SUBTYPE_COMPARISON, @@ -2400,8 +2396,8 @@ static void validateCrossFieldValidators(MetaRoot root, List com.metaobjects.validator.PresentIffValidator.SUBTYPE_PRESENT_IFF, com.metaobjects.validator.AtLeastOneValidator.SUBTYPE_AT_LEAST_ONE); for (MetaObject obj : root.getChildren(MetaObject.class, false)) { - java.util.Set fieldNames = new java.util.HashSet<>(); - for (com.metaobjects.field.MetaField f : obj.getMetaFields()) fieldNames.add(f.getShortName()); + java.util.Map> fields = new java.util.LinkedHashMap<>(); + for (MetaField f : obj.getMetaFields()) fields.put(f.getShortName(), f); for (com.metaobjects.validator.MetaValidator v : obj.getChildren(com.metaobjects.validator.MetaValidator.class, false)) { if (!crossField.contains(v.getSubType())) continue; @@ -2422,21 +2418,122 @@ static void validateCrossFieldValidators(MetaRoot root, List } } if (!v.hasMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION)) continue; + Object condition = v.getMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION).getValue(); java.util.TreeSet unknown = new java.util.TreeSet<>(); - collectExprFieldRefs(v.getMetaAttr(com.metaobjects.validator.MetaValidator.ATTR_CONDITION).getValue(), unknown); - unknown.removeAll(fieldNames); - if (unknown.isEmpty()) continue; - StringBuilder names = new StringBuilder(); - for (String u : unknown) names.append(names.length() == 0 ? "" : ", ").append('"').append(u).append('"'); - out.add(new MetaDataException( - ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @condition names " + names - + ", which " + (unknown.size() == 1 ? "is not a field" : "are not fields") - + " of \"" + obj.getShortName() + "\".", - ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); + collectExprFieldRefs(condition, unknown); + unknown.removeAll(fields.keySet()); + if (!unknown.isEmpty()) { + StringBuilder names = new StringBuilder(); + for (String u : unknown) names.append(names.length() == 0 ? "" : ", ").append('"').append(u).append('"'); + out.add(new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @condition names " + names + + ", which " + (unknown.size() == 1 ? "is not a field" : "are not fields") + + " of \"" + obj.getShortName() + "\".", + ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); + continue; + } + String problem = conditionProblem(condition, fields); + if (problem != null) { + out.add(new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": validator." + label + " @condition " + problem, + ErrorCode.ERR_BAD_ATTR_VALUE, v.getSource())); + } } } } + /** Field subtypes whose values a condition compares with a number literal. */ + private static final java.util.Set CONDITION_NUMBER_SUBTYPES = java.util.Set.of( + IntegerField.SUBTYPE_INT, LongField.SUBTYPE_LONG, DoubleField.SUBTYPE_DOUBLE, + FloatField.SUBTYPE_FLOAT, DecimalField.SUBTYPE_DECIMAL, CurrencyField.SUBTYPE_CURRENCY); + + /** + * Why a cross-field validator's {@code @condition} cannot become a CHECK guard, or + * {@code null} when it can. Its names are already known to be fields. The rule, the same + * in every port: + * - it types cleanly (the origin.computed inference) and its root is boolean, since a + * CHECK negates it; + * - a literal compared with a field is of that field's kind (a boolean for field.boolean, + * a number for a numeric field, a string otherwise) and, for field.enum, one of its + * @values; + * - no comparison has a null literal: {@code x = NULL} is never true, so use isNull / + * isNotNull. + * Mirrors TS conditionProblem. + */ + private static String conditionProblem(Object condition, java.util.Map> fields) { + ExpressionAttribute.InferResult inferred = ExpressionAttribute.inferExprType( + condition, name -> fields.containsKey(name) ? fields.get(name).getSubType() : null); + if (!inferred.errors.isEmpty()) { + return "is not a valid expression: " + String.join("; ", inferred.errors) + "."; + } + if (!BooleanField.SUBTYPE_BOOLEAN.equals(inferred.type)) { + return "must be a boolean expression (a comparison, a null test, or and / or / not of them), not a field." + + inferred.type + "."; + } + return conditionLiteralProblem(condition, fields); + } + + /** The first comparison in {@code node} whose literal side cannot be compared with its + * other side, as conditionProblem's message tail, or {@code null}. */ + private static String conditionLiteralProblem(Object node, java.util.Map> fields) { + if (!(node instanceof java.util.Map n)) return null; + if (n.get("left") != null && n.get("right") != null) { + Object[][] sides = { { n.get("left"), n.get("right") }, { n.get("right"), n.get("left") } }; + for (Object[] side : sides) { + if (!(side[0] instanceof java.util.Map lit) || !lit.containsKey("value")) continue; + Object value = lit.get("value"); + if (value == null) { + return "compares with null, which is never true: use isNull or isNotNull."; + } + MetaField field = side[1] instanceof java.util.Map ref && ref.get("field") instanceof String f + ? fields.get(f) : null; + if (field == null) continue; + String subType = field.getSubType(); + String kind = BooleanField.SUBTYPE_BOOLEAN.equals(subType) ? "boolean" + : CONDITION_NUMBER_SUBTYPES.contains(subType) ? "number" : "string"; + boolean matches = switch (kind) { + case "boolean" -> value instanceof Boolean; + case "number" -> value instanceof Number; + default -> value instanceof String; + }; + if (!matches) { + return "compares \"" + field.getShortName() + "\" (field." + subType + ") with " + + conditionJsonLiteral(value) + "; it needs a " + kind + "."; + } + if (EnumField.SUBTYPE_ENUM.equals(subType) && field.hasMetaAttr(EnumField.ATTR_VALUES) + && field.getMetaAttr(EnumField.ATTR_VALUES).getValue() instanceof java.util.Collection members) { + List names = new java.util.ArrayList<>(); + for (Object m : members) names.add(String.valueOf(m)); + if (!names.contains(String.valueOf(value))) { + return "compares \"" + field.getShortName() + "\" with " + conditionJsonLiteral(value) + + ", which is not one of its @values (" + String.join(", ", names) + ")."; + } + } + } + } + for (String k : List.of("left", "right", "arg")) { + String p = conditionLiteralProblem(n.get(k), fields); + if (p != null) return p; + } + if (n.get("args") instanceof java.util.Collection args) { + for (Object a : args) { + String p = conditionLiteralProblem(a, fields); + if (p != null) return p; + } + } + return null; + } + + /** A condition literal as JSON, the way TS JSON.stringify renders it (an integral + * double without a fraction). */ + private static String conditionJsonLiteral(Object value) { + if ((value instanceof Double || value instanceof Float) && !Double.isInfinite(((Number) value).doubleValue()) + && ((Number) value).doubleValue() == Math.rint(((Number) value).doubleValue())) { + return Long.toString(((Number) value).longValue()); + } + return new com.google.gson.GsonBuilder().disableHtmlEscaping().create().toJson(value); + } + /** The field names an expression tree (ExpressionAttribute's Map form) references. */ private static void collectExprFieldRefs(Object node, java.util.Set out) { if (node instanceof java.util.Map m) { @@ -2446,6 +2543,13 @@ private static void collectExprFieldRefs(Object node, java.util.Set out) } } + // ========================================================================= + // identity.primary @sequenceStart / @sequenceName describe the sequence an @generation + // "increment" key draws from; on any other generation there is none, so either one is + // refused (ERR_SEQUENCE_WITHOUT_INCREMENT). Read RESOLVING (ADR-0039), reported on the + // identity that declares one of them, every offender collected. Mirrors TS. + // ========================================================================= + static void validateIdentitySequence(MetaRoot root, List out) { for (MetaObject obj : root.getChildren(MetaObject.class, false)) { for (com.metaobjects.identity.PrimaryIdentity id diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index bd6c444b09..1dd0a7bae2 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -7,6 +7,7 @@ """ from __future__ import annotations +import json import math import re from typing import Callable, NamedTuple @@ -3793,9 +3794,10 @@ def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None # Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the -# database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, and -# every field a @condition names a field of the owning entity (ERR_BAD_ATTR_VALUE). Read -# RESOLVING (ADR-0039). Mirrors TS validateCrossFieldValidators. +# database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, +# every field a @condition names a field of the owning entity, and a @condition that can +# become a CHECK guard (see _condition_problem) — all ERR_BAD_ATTR_VALUE. Read RESOLVING +# (ADR-0039). Mirrors TS validateCrossFieldValidators. def _expr_field_refs(node: object, out: set[str]) -> None: if not isinstance(node, dict): return @@ -3809,6 +3811,97 @@ def _expr_field_refs(node: object, out: set[str]) -> None: _expr_field_refs(a, out) +# Field subtypes whose values a condition compares with a number literal. +_CONDITION_NUMBER_SUBTYPES = frozenset({ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +}) + + +def _json_literal(value: object) -> str: + """A literal as JSON.stringify writes it, so the message matches the TS port's.""" + if isinstance(value, float) and value.is_integer(): + value = int(value) + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + + +def _literal_is_kind(value: object, kind: str) -> bool: + # bool is a subclass of int in Python: a bool literal is not a number, nor a number a bool. + if kind == "boolean": + return isinstance(value, bool) + if kind == "number": + return isinstance(value, (int, float)) and not isinstance(value, bool) + return isinstance(value, str) + + +def _condition_problem(condition: object, obj: MetaData) -> str | None: + """Why a cross-field validator's ``@condition`` cannot become a CHECK guard, or None when + it can. Its names are already known to be fields. The rule, the same in every port: + - it types cleanly (the origin.computed inference) and its root is boolean, since a + CHECK negates it; + - a literal compared with a field is of that field's kind (a boolean for field.boolean, + a number for a numeric field, a string otherwise) and, for field.enum, one of its + @values; + - no comparison has a null literal: ``x = NULL`` is never true, so use isNull / isNotNull. + Mirrors TS conditionProblem.""" + fields = {f.name: f for f in obj.fields()} + inferred = infer_expr_type( + condition, lambda name: fields[name].sub_type if name in fields else None + ) + if inferred.errors: + return f"is not a valid expression: {'; '.join(inferred.errors)}." + if inferred.type != FIELD_SUBTYPE_BOOLEAN: + return ( + "must be a boolean expression (a comparison, a null test, or and / or / not of " + f"them), not a field.{inferred.type}." + ) + + def visit(node: object) -> str | None: + if not isinstance(node, dict): + return None + if node.get("left") is not None and node.get("right") is not None: + for lit, ref in ((node["left"], node["right"]), (node["right"], node["left"])): + if not isinstance(lit, dict) or "value" not in lit: + continue + value = lit["value"] + if value is None: + return "compares with null, which is never true: use isNull or isNotNull." + name = ref.get("field") if isinstance(ref, dict) else None + field = fields.get(name) if isinstance(name, str) else None + if field is None: + continue + sub = field.sub_type + kind = ( + "boolean" if sub == FIELD_SUBTYPE_BOOLEAN + else "number" if sub in _CONDITION_NUMBER_SUBTYPES + else "string" + ) + if not _literal_is_kind(value, kind): + return ( + f'compares "{field.name}" (field.{sub}) with {_json_literal(value)}; ' + f"it needs a {kind}." + ) + members = field.get_meta_attr(FIELD_ATTR_VALUES) if sub == FIELD_SUBTYPE_ENUM else None + if isinstance(members, list) and str(value) not in [str(m) for m in members]: + return ( + f'compares "{field.name}" with {_json_literal(value)}, which is not one ' + f"of its @values ({', '.join(str(m) for m in members)})." + ) + for key in ("left", "right", "arg"): + found = visit(node.get(key)) + if found is not None: + return found + args = node.get("args") + if isinstance(args, list): + for a in args: + found = visit(a) + if found is not None: + return found + return None + + return visit(condition) + + def _validate_cross_field_validators(root: MetaData, errors: list[MetaError]) -> None: from ..meta.core.validator import validator_constants as vc @@ -3837,6 +3930,7 @@ def _validate_cross_field_validators(root: MetaData, errors: list[MetaError]) -> condition = v.get_meta_attr(vc.VALIDATOR_ATTR_CONDITION) if condition is None: continue + label = f'validator.{v.sub_type} "{obj.name}.{v.name}" @condition' refs: set[str] = set() _expr_field_refs(condition, refs) unknown = sorted(refs - field_names) @@ -3845,10 +3939,15 @@ def _validate_cross_field_validators(root: MetaData, errors: list[MetaError]) -> verb = "is not a field" if len(unknown) == 1 else "are not fields" errors.append(MetaError( code=ErrorCode.ERR_BAD_ATTR_VALUE, - message=( - f'validator.{v.sub_type} "{obj.name}.{v.name}" @condition names {names}, ' - f'which {verb} of "{obj.name}".' - ), + message=f'{label} names {names}, which {verb} of "{obj.name}".', + envelope=v.source, + )) + continue + problem = _condition_problem(condition, obj) + if problem is not None: + errors.append(MetaError( + code=ErrorCode.ERR_BAD_ATTR_VALUE, + message=f"{label} {problem}", envelope=v.source, )) diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index 29d5bea596..7317c1f1b9 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -22,6 +22,7 @@ import { isPrimaryKeyChangeError, isDeclaredRenameError, isDuplicateSqlNameError, + isInvalidCheckNameError, isFkTargetNotUniqueError, FkTargetNotUniqueError, type FkTargetViolation, @@ -382,6 +383,8 @@ const PK_CHANGE_HINT = "align the primary key manually, or reconcile the metadata identity to match the live table"; const DUPLICATE_SQL_NAME_HINT = "rename one of the colliding declarations; an index's database name is its identity.secondary / index.lookup name, not prefixed with its table"; +const CHECK_NAME_HINT = + "give each constraint on a table its own @constraintName, at most 63 bytes"; const FK_TARGET_NOT_UNIQUE_HINT = "declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"; const DECLARED_RENAME_HINT = @@ -1171,6 +1174,8 @@ export async function migrateCommand( if (err instanceof AlreadyEmittedError) return err.exitCode; // A metadata defect, not a tool failure: two declarations generate one database name. if (isDuplicateSqlNameError(err)) return refuseEngineError(err, DUPLICATE_SQL_NAME_HINT, fmt); + // A metadata defect too: a declared CHECK name that duplicates another constraint or is too long. + if (isInvalidCheckNameError(err)) return refuseEngineError(err, CHECK_NAME_HINT, fmt); // A metadata defect too: a foreign key whose target columns are not a unique key there. if (isFkTargetNotUniqueError(err)) return refuseEngineError(err, FK_TARGET_NOT_UNIQUE_HINT, fmt); // A metadata defect too: an enum member longer than the project's enums.maxLength. diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 46433d8169..f74c40fb69 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -93,6 +93,7 @@ import { type ShadowSchemaSource, withoutFlywayHistory, isFkTargetNotUniqueError, + isInvalidCheckNameError, isUnknownSchemaConventionsError, resolveSchemaConventions, type SchemaConventions, @@ -729,6 +730,7 @@ export async function verifyCommand( governed = scopeExpectedSchema(built, schemaScope, importedOption(collection)); } catch (err) { if (isEnumLengthRefusal(err)) return refuseEnumLength(err); + if (isInvalidCheckNameError(err)) { log.error(`verify: ${err.message}`); return 1; } throw err; } } @@ -1334,6 +1336,7 @@ export async function verifyCommand( // Building the expected schema to check the scope raises the same metadata refusals // the comparison below would; report them by name, not as an uncaught error. if (isEnumLengthRefusal(err)) return refuseEnumLength(err); + if (isInvalidCheckNameError(err)) { log.error(`verify: ${err.message}`); return 1; } throw err; } if (scopeMismatch !== undefined) { @@ -1429,6 +1432,10 @@ export async function verifyCommand( log.error("verify: declare an identity.secondary on the target entity with exactly the referenced fields, or reference its primary key"); return 1; } + if (isInvalidCheckNameError(err)) { + log.error(`verify: ${err.message}`); + return 1; + } if (isEnumLengthRefusal(err)) return refuseEnumLength(err); if (isUnknownSchemaConventionsError(err)) { log.error(`verify: ${err.message}`); diff --git a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts index 24e600b9ba..58c8375dda 100644 --- a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts +++ b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts @@ -106,4 +106,29 @@ describe("meta verify — schema refusals", () => { expect(scoped.code).toBe(1); expect(scoped.out).toContain('field.enum "Ticket.status" has the member "IN_PROGRESS"'); }); + + test("--db: a declared CHECK name two validators share is refused by name, not as an introspection failure", async () => { + const root = await mkdtemp(join(tmpdir(), "verify-schema-refusals-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Slot", children: [ + { "source.rdb": { "@table": "slots" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "a" } }, + { "field.long": { name: "b" } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, + { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@constraintName": "CK_Slot" } }, + { "validator.comparison": { name: "cmp", "@left": "a", "@op": "lt", "@right": "b", "@constraintName": "CK_Slot" } }, + ] } }, + ] } }), "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8"); + + const { code, out } = await capture(() => verifyCommand(["--db", `file:${join(root, "t.db")}`], root)); + expect(code).toBe(1); + expect(out).toContain("ERR_CHECK_NAME"); + expect(out).toContain('CHECK "CK_Slot" on table "slots"'); + expect(out).not.toContain("failed to introspect"); + }); }); diff --git a/server/typescript/packages/docs-site/src/builders/object-data.ts b/server/typescript/packages/docs-site/src/builders/object-data.ts index 2181a0dd51..430aa63d3b 100644 --- a/server/typescript/packages/docs-site/src/builders/object-data.ts +++ b/server/typescript/packages/docs-site/src/builders/object-data.ts @@ -253,8 +253,15 @@ export function buildObjectPage(fqn: string, g: LinkGraph, cov: CoverageTracker) if (v.subType === "comparison") rule = `${esc(String(at("left") ?? ""))} ${esc(String(at("op") ?? ""))} ${esc(String(at("right") ?? ""))}`; else if (v.subType === "requiredWhen") rule = `${esc(String(at("field") ?? ""))} required when ${esc(String(at("when") ?? ""))} = ${esc(String(at("equals") ?? ""))}`; else if (v.subType === "presentIff") rule = `${esc(String(at("field") ?? ""))} present iff ${esc(String(at("when") ?? ""))} = ${esc(String(at("equals") ?? ""))}`; - else if (v.subType === "atLeastOne") { const fs = at("fields"); rule = `at least one of ${esc(Array.isArray(fs) ? fs.map(String).join(", ") : String(fs ?? ""))}`; } + else if (v.subType === "atLeastOne") { + const fs = at("fields"); + const max = at("max"); + const list = esc(Array.isArray(fs) ? fs.map(String).join(", ") : String(fs ?? "")); + rule = max === 1 ? `exactly one of ${list}` : typeof max === "number" ? `between 1 and ${max} of ${list}` : `at least one of ${list}`; + } else rule = esc(v.subType); + const condition = at("condition"); + if (condition !== undefined && rule !== esc(v.subType)) rule += `, when ${esc(expressionText(condition))}`; validators.push({ scope: "object", subject: v.name || v.subType, rule }); } validators.sort((a, b) => a.subject.localeCompare(b.subject)); @@ -366,3 +373,21 @@ export function buildObjectPage(fqn: string, g: LinkGraph, cov: CoverageTracker) report, reporting, }; } + +const EXPR_TEXT_OP: Readonly> = { eq: "=", ne: "≠", gt: ">", gte: "≥", lt: "<", lte: "≤" }; + +/** An attr.expression as one line of reading text (a cross-field validator's @condition). */ +function expressionText(node: unknown): string { + if (typeof node !== "object" || node === null) return String(node); + const n = node as Record; + if (typeof n["field"] === "string") return n["field"]; + if ("value" in n) return JSON.stringify(n["value"]); + const op = n["op"]; + if (typeof op === "string" && EXPR_TEXT_OP[op] !== undefined) return `${expressionText(n["left"])} ${EXPR_TEXT_OP[op]} ${expressionText(n["right"])}`; + if (op === "isNull") return `${expressionText(n["arg"])} is empty`; + if (op === "isNotNull") return `${expressionText(n["arg"])} is set`; + if (op === "not") return `not (${expressionText(n["arg"])})`; + if ((op === "and" || op === "or") && Array.isArray(n["args"])) return n["args"].map((a) => `(${expressionText(a)})`).join(` ${op} `); + if (n["fn"] === "coalesce" && Array.isArray(n["args"])) return `coalesce(${n["args"].map(expressionText).join(", ")})`; + return JSON.stringify(node); +} diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 3d56934b7f..653fdb5fef 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1706,6 +1706,64 @@ function expressionFieldRefs(node: unknown, out: string[] = []): string[] { return out; } +/** Field subtypes whose values a condition compares with a number literal. */ +const _CONDITION_NUMBER_SUBTYPES = new Set([ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +]); + +/** + * Why a cross-field validator's `@condition` cannot become a CHECK guard, or undefined when it + * can. Its names are already known to be fields. The rule, the same in every port: + * - it types cleanly (the origin.computed inference) and its root is boolean, since a CHECK + * negates it; + * - a literal compared with a field is of that field's kind (a boolean for field.boolean, a + * number for a numeric field, a string otherwise) and, for field.enum, one of its @values; + * - no comparison has a null literal: `x = NULL` is never true, so use isNull / isNotNull. + */ +function conditionProblem(condition: unknown, obj: MetaObject): string | undefined { + const fields = new Map(obj.fields().map((f) => [f.name, f] as const)); + const inferred = inferExprType(condition as ExprNode, (name) => fields.get(name)?.subType); + if (inferred.errors.length > 0) return `is not a valid expression: ${inferred.errors.join("; ")}.`; + if (inferred.type !== FIELD_SUBTYPE_BOOLEAN) { + return `must be a boolean expression (a comparison, a null test, or and / or / not of them), not a field.${String(inferred.type)}.`; + } + let problem: string | undefined; + const visit = (node: unknown): void => { + if (problem !== undefined || typeof node !== "object" || node === null) return; + const n = node as Record; + if (n["left"] !== undefined && n["right"] !== undefined) { + for (const [a, b] of [[n["left"], n["right"]], [n["right"], n["left"]]] as const) { + const lit = a as Record; + const ref = b as Record; + if (!("value" in lit)) continue; + if (lit["value"] === null) { + problem = `compares with null, which is never true: use isNull or isNotNull.`; + return; + } + const field = typeof ref["field"] === "string" ? fields.get(ref["field"]) : undefined; + if (field === undefined) continue; + const value = lit["value"]; + const kind = field.subType === FIELD_SUBTYPE_BOOLEAN ? "boolean" + : _CONDITION_NUMBER_SUBTYPES.has(field.subType) ? "number" : "string"; + if (typeof value !== kind) { + problem = `compares "${field.name}" (field.${field.subType}) with ${JSON.stringify(value)}; it needs a ${kind}.`; + return; + } + const members = field.subType === FIELD_SUBTYPE_ENUM ? field.attr(FIELD_ATTR_VALUES) : undefined; + if (Array.isArray(members) && !members.map(String).includes(String(value))) { + problem = `compares "${field.name}" with ${JSON.stringify(value)}, which is not one of its @values (${members.join(", ")}).`; + return; + } + } + } + for (const key of ["left", "right", "arg"]) visit(n[key]); + if (Array.isArray(n["args"])) for (const a of n["args"]) visit(a); + }; + visit(condition); + return problem; +} + export function validateCrossFieldValidators(root: MetaData): ParseError[] { const errors: ParseError[] = []; for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { @@ -1726,13 +1784,19 @@ export function validateCrossFieldValidators(root: MetaData): ParseError[] { } const condition = v.attr(VALIDATOR_ATTR_CONDITION); if (condition !== undefined) { + const label = `validator.${v.subType} "${obj.name}.${v.name}" @condition`; const unknown = [...new Set(expressionFieldRefs(condition))].filter((f) => !fieldNames.has(f)).sort(); if (unknown.length > 0) { errors.push(new ParseError( - `validator.${v.subType} "${obj.name}.${v.name}" @condition names ${unknown.map((f) => `"${f}"`).join(", ")}, ` + + `${label} names ${unknown.map((f) => `"${f}"`).join(", ")}, ` + `which ${unknown.length === 1 ? "is not a field" : "are not fields"} of "${obj.name}".`, { code: "ERR_BAD_ATTR_VALUE", source: v.source }, )); + continue; + } + const problem = conditionProblem(condition, obj as MetaObject); + if (problem !== undefined) { + errors.push(new ParseError(`${label} ${problem}`, { code: "ERR_BAD_ATTR_VALUE", source: v.source })); } } } diff --git a/server/typescript/packages/migrate-ts/src/check-expression.ts b/server/typescript/packages/migrate-ts/src/check-expression.ts index 312ccd86ea..2b4d997b91 100644 --- a/server/typescript/packages/migrate-ts/src/check-expression.ts +++ b/server/typescript/packages/migrate-ts/src/check-expression.ts @@ -55,12 +55,27 @@ export function negateExpression(node: ExprNode): ExprNode { return { op: EXPR_OP_NOT, arg: node } as ExprNode; } +/** + * How a literal compared with a field is stored in that field's column, when that is not the + * literal itself: an int-backed enum (`@intValueMap`) stores a member as its integer. Answers the + * SQL for the stored value, or undefined to render the literal as written. + */ +export type StoredLiteral = (field: string, value: unknown) => string | undefined; + +/** A node SQL can use as a comparison operand without parentheses. */ +function isAtom(x: unknown): boolean { + const n = x as Node; + return typeof n["field"] === "string" || "value" in n || n["fn"] !== undefined; +} + /** * `node` as SQL. `column(field)` is the quoted physical column for a field name, or undefined - * when the entity has no such field. + * when the entity has no such field. A compound operand of a comparison or a null test is + * parenthesised: `IS` binds looser than `=`, and `AND` / `OR` looser than both. */ export function renderExpressionSql( node: ExprNode, column: (field: string) => string | undefined, dialect: Dialect | undefined, + stored?: StoredLiteral, ): string { const n = node as Node; if (typeof n["field"] === "string") { @@ -70,10 +85,20 @@ export function renderExpressionSql( } if ("value" in n) return renderLiteral(n["value"], dialect); const op = n["op"]; - const sub = (x: unknown): string => renderExpressionSql(x as ExprNode, column, dialect); - if (typeof op === "string" && SQL_OP[op] !== undefined) return `${sub(n["left"])} ${SQL_OP[op]} ${sub(n["right"])}`; - if (op === FILTER_OP_IS_NULL) return `${sub(n["arg"])} IS NULL`; - if (op === EXPR_OP_IS_NOT_NULL) return `${sub(n["arg"])} IS NOT NULL`; + const sub = (x: unknown): string => renderExpressionSql(x as ExprNode, column, dialect, stored); + const operand = (x: unknown, other: unknown): string => { + const o = (other ?? {}) as Node; + if (stored !== undefined && "value" in (x as Node) && typeof o["field"] === "string") { + const sql = stored(o["field"], (x as Node)["value"]); + if (sql !== undefined) return sql; + } + return isAtom(x) ? sub(x) : `(${sub(x)})`; + }; + if (typeof op === "string" && SQL_OP[op] !== undefined) { + return `${operand(n["left"], n["right"])} ${SQL_OP[op]} ${operand(n["right"], n["left"])}`; + } + if (op === FILTER_OP_IS_NULL) return `${operand(n["arg"], undefined)} IS NULL`; + if (op === EXPR_OP_IS_NOT_NULL) return `${operand(n["arg"], undefined)} IS NOT NULL`; if (op === EXPR_OP_NOT) return `NOT (${sub(n["arg"])})`; if (op === FILTER_COMPOSE_AND || op === FILTER_COMPOSE_OR) { return (n["args"] as unknown[]).map((a) => `(${sub(a)})`).join(op === FILTER_COMPOSE_AND ? " AND " : " OR "); diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index 9dc1d1047c..f9cba66068 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -333,6 +333,45 @@ export function isDuplicateSqlNameError(err: unknown): err is DuplicateSqlNameEr return err instanceof Error && err.name === "DuplicateSqlNameError"; } +/** One problem with a declared CHECK name (`@constraintName` on a validator or a field.enum). */ +export interface CheckNameProblem { + readonly table: string; + readonly name: string; + /** Another constraint on the same table already has the name. */ + readonly duplicateOf?: string; + /** The name is longer than Postgres's 63-byte identifier limit, in bytes. */ + readonly bytes?: number; +} + +/** + * A declared CHECK name that cannot be applied as written. Two constraints on one table with + * one name fail at apply on Postgres ("already exists") and, on SQLite, collapse in a + * name-keyed diff so every run proposes the CHECK again. A name over 63 bytes is truncated by + * Postgres when it is created, so the declared name never matches the database and the CHECK + * drifts forever. Either way the fix is to the metadata, so it is refused while the expected + * schema is built. + */ +export class InvalidCheckNameError extends Error { + override readonly name = "InvalidCheckNameError"; + readonly problems: readonly CheckNameProblem[]; + + constructor(problems: readonly CheckNameProblem[]) { + const lines = problems.map((p) => p.duplicateOf !== undefined + ? ` CHECK "${p.name}" on table "${p.table}" has the same name as ${p.duplicateOf}` + : ` CHECK "${p.name}" on table "${p.table}" is ${p.bytes} bytes; Postgres keeps only the first 63`); + super( + `ERR_CHECK_NAME: a declared @constraintName cannot be applied as written.\n${lines.join("\n")}\n` + + "Give each constraint on a table its own @constraintName, at most 63 bytes.", + ); + this.problems = problems; + } +} + +/** Is `err` the {@link InvalidCheckNameError} from a declared CHECK name that cannot be applied? */ +export function isInvalidCheckNameError(err: unknown): err is InvalidCheckNameError { + return err instanceof Error && err.name === "InvalidCheckNameError"; +} + /** `migrate.conventions` names a schema-conventions preset that does not exist. */ export class UnknownSchemaConventionsError extends Error { override readonly name = "UnknownSchemaConventionsError"; diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index e0affc8125..0eb0feef94 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -1,4 +1,6 @@ -import { DuplicateSqlNameError, FkTargetNotUniqueError, type FkTargetViolation } from "./errors.js"; +import { + DuplicateSqlNameError, FkTargetNotUniqueError, InvalidCheckNameError, type CheckNameProblem, type FkTargetViolation, +} from "./errors.js"; import { negateExpression, renderExpressionSql } from "./check-expression.js"; import { canBeUniqueConstraint, resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; import type { @@ -301,6 +303,7 @@ export function buildExpectedSchemaWithProvenance( // declares but never emits (on a TPH subtype) is no key a database can reference. const fkTargetViolations = collectFkTargetViolations(tables, fkCtx.origins, provenance); applySchemaConventions(tables, conventions); + checkDeclaredCheckNames(tables, dialect); // Pass 3: dialect-specific SqlType normalization. if (dialect === "sqlite") { @@ -900,7 +903,8 @@ function buildChecks( } else { expression = `${qcol} IN (${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ")})`; } - checks.push({ name: declaredCheckName(field) ?? `${tableName}_${col}_chk`, expression }); + const enumCheck = { name: `${tableName}_${col}_chk`, expression }; + checks.push(withDeclaredName(enumCheck, field)); } } // Validator-derived checks. @@ -910,7 +914,12 @@ function buildChecks( const enforcesLength = dialect !== "sqlite" && dialect !== "d1"; const enforcedMax = skipRedundant && enforcesLength && columnType.kind === "text" ? columnType.maxLength : undefined; for (const v of field.validators()) { - const check = validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); + // A declared @constraintName asks for the CHECK by name, so it is kept even where the + // conventions would skip it as redundant. + const keep = declaredCheckName(v) !== undefined; + const check = keep + ? validatorCheck(v, qcol, tableName, col, dialect) + : validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); if (check) checks.push(withDeclaredName(check, v)); } } @@ -974,20 +983,60 @@ function renderEquals( return `'${s.replace(/'/g, "''")}'`; } -/** - * Derive a CHECK from an entity-scoped cross-field validator. Every reference is - * resolved to its physical column by name; nothing raw is read from metadata. - * Returns null (skips the check) if any referenced field is missing. - */ /** A validator's or field.enum's declared CHECK name (`@constraintName`; ADR-0039 resolving), if any. */ function declaredCheckName(node: MetaData): string | undefined { const name = node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); return typeof name === "string" && name.length > 0 ? name : undefined; } +/** The CHECKs whose name was declared (`@constraintName`), so the name checks below apply only + * to names an author wrote: a derived name keeps the behaviour it always had. */ +const DECLARED_CHECKS = new WeakSet(); + function withDeclaredName(check: CheckDescriptor, node: MetaData): CheckDescriptor { const name = declaredCheckName(node); - return name === undefined ? check : { ...check, name }; + if (name === undefined) return check; + const named = { ...check, name }; + DECLARED_CHECKS.add(named); + return named; +} + +/** Postgres's identifier limit, in bytes (NAMEDATALEN - 1). A longer name is truncated. */ +const PG_IDENTIFIER_MAX_BYTES = 63; + +/** + * Refuse a declared CHECK name another constraint on the same table already has, or (on + * Postgres) one over 63 bytes. Runs after the conventions have named primary keys, foreign + * keys and unique constraints. A collision among derived names is left as it always was. + */ +function checkDeclaredCheckNames(tables: readonly TableDescriptor[], dialect: Dialect | undefined): void { + const problems: CheckNameProblem[] = []; + const limited = dialect !== "sqlite" && dialect !== "d1"; + for (const t of tables) { + const declared = new Set(t.checks.filter((c) => DECLARED_CHECKS.has(c)).map((c) => c.name)); + if (declared.size === 0) continue; + const owners = new Map(); + const reported = new Set(); + const claim = (name: string, label: string): void => { + const prior = owners.get(name); + if (prior === undefined) { + owners.set(name, label); + } else if (declared.has(name) && !reported.has(name)) { + reported.add(name); + problems.push({ table: t.name, name, duplicateOf: prior }); + } + }; + if (t.primaryKey.length > 0) claim(t.primaryKeyName ?? `${t.name}_pkey`, "the primary key"); + for (const fk of t.foreignKeys) claim(fk.name, `the foreign key "${fk.name}"`); + for (const ix of t.indexes) if (ix.constraint === "unique") claim(ix.name, `the unique constraint "${ix.name}"`); + for (const c of t.checks) claim(c.name, `another CHECK named "${c.name}"`); + if (!limited) continue; + for (const name of declared) { + const bytes = Buffer.byteLength(name, "utf8"); + if (bytes > PG_IDENTIFIER_MAX_BYTES) problems.push({ table: t.name, name, bytes }); + } + } + if (problems.length > 0) throw new InvalidCheckNameError(problems); } /** @@ -1004,10 +1053,23 @@ function withCondition( const field = entity.fields().find((f) => f.name === name); return field === undefined ? undefined : quoteCheckCol(resolveColumnName(field, strategy)); }; - const unless = renderExpressionSql(negateExpression(condition as ExprNode), column, dialect); + // An int-backed enum (@intValueMap) stores a member as its integer, so a member compared + // with it is rendered as that integer. + const stored = (name: string, value: unknown): string | undefined => { + const field = entity.fields().find((f) => f.name === name); + const intMap = field === undefined ? undefined : intValueMapOf(field); + const n = intMap === undefined || typeof value !== "string" ? undefined : intMap[value]; + return typeof n === "number" ? String(n) : undefined; + }; + const unless = renderExpressionSql(negateExpression(condition as ExprNode), column, dialect, stored); return { ...check, expression: `(${unless}) OR (${check.expression})` }; } +/** + * Derive a CHECK from an entity-scoped cross-field validator. Every reference is + * resolved to its physical column by name; nothing raw is read from metadata. + * Returns null (skips the check) if any referenced field is missing. + */ function crossFieldCheck( v: MetaValidator, entity: MetaObject, tableName: string, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, @@ -1062,7 +1124,9 @@ function crossFieldCheck( : `num_nonnulls(${refs.map((r) => r!.qcol).join(", ")})`; return { name: `${tableName}_${firstCol}_atleastone_chk`, - expression: max === 1 ? `${count} = 1` : `${count} BETWEEN 1 AND ${max}`, + // Two comparisons, not BETWEEN: Postgres stores a BETWEEN as these two comparisons, and + // writing it the way Postgres reads it back keeps the CHECK free of drift. + expression: max === 1 ? `${count} = 1` : `${count} >= 1 AND ${count} <= ${max}`, }; } return { diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index dcbb10485a..5ff33395f2 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -61,6 +61,8 @@ export { DuplicateSqlNameError, allowOptionFor, isBlockedChangesError, isPrimaryKeyChangeError, isDeclaredRenameError, isDuplicateSqlNameError, + InvalidCheckNameError, + isInvalidCheckNameError, isFkTargetNotUniqueError, isUnknownSchemaConventionsError, UnknownSchemaConventionsError, @@ -68,7 +70,7 @@ export { FkTargetNotUniqueError, type FkTargetViolation, } from "./errors.js"; -export type { SqlNameCollision } from "./errors.js"; +export type { SqlNameCollision, CheckNameProblem } from "./errors.js"; // Drop+add pairs in one table that may be a rename — the CLI's hint text reads it so the // declared rename is offered ahead of the data-losing `--allow drop-column`. diff --git a/server/typescript/packages/migrate-ts/test/integration/pg-cross-field-checks-roundtrip.test.ts b/server/typescript/packages/migrate-ts/test/integration/pg-cross-field-checks-roundtrip.test.ts new file mode 100644 index 0000000000..6783592c63 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/integration/pg-cross-field-checks-roundtrip.test.ts @@ -0,0 +1,88 @@ +/** + * Real Postgres: the CHECKs the cross-field validator extensions emit (atLeastOne @max, a + * @condition with every node kind, an int-backed enum member in a condition) apply, and a + * second diff proposes nothing. The diff here runs WITHOUT the expression-canonicalisation + * probe, so this is the fallback normaliser a read-only `verify --db` role gets: Postgres + * rewrites a BETWEEN and re-parenthesises every comparison, and a spelling the normaliser + * cannot match would drift on every run. + * + * Gated on MIGRATE_TS_PG_URL; skips cleanly when unset. + */ + +import { test, expect, beforeAll, afterAll, describe } from "bun:test"; +import { Pool } from "pg"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { introspectPostgres } from "../../src/introspect/postgres.js"; +import { diff } from "../../src/diff/index.js"; +import { emit } from "../../src/emit/index.js"; + +const PG_URL = process.env["MIGRATE_TS_PG_URL"]; +const realDescribe = PG_URL ? describe : describe.skip; +const TABLE = "xfield_checks_rt"; + +const META = JSON.stringify({ "metadata.root": { package: "acme", children: [{ "object.entity": { name: "Note", children: [ + { "source.rdb": { "@table": TABLE } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "a" } }, { "field.long": { name: "b" } }, { "field.long": { name: "c" } }, + { "field.boolean": { name: "flag" } }, + { "field.string": { name: "label" } }, + { "field.enum": { name: "kind", "@values": ["Owned", "Shared"], "@intValueMap": { Owned: 1, Shared: 2 } } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, + { "validator.atLeastOne": { name: "few", "@fields": ["a", "b", "c"], "@max": 2, "@constraintName": "CK_Note_Few" } }, + { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@max": 1, "@constraintName": "CK_Note_One", + "@condition": { op: "eq", left: { field: "kind" }, right: { value: "Owned" } } } }, + { "validator.comparison": { name: "cmp", "@left": "a", "@op": "lt", "@right": "b", "@constraintName": "CK_Note_Cmp", + "@condition": { op: "and", args: [ + { op: "isNotNull", arg: { field: "label" } }, + { op: "not", arg: { op: "eq", left: { field: "flag" }, right: { value: true } } }, + { op: "eq", left: { op: "isNull", arg: { field: "c" } }, right: { field: "flag" } }, + ] } } }, + { "validator.requiredWhen": { name: "rw", "@field": "c", "@when": "label", "@equals": "x", + "@condition": { op: "gte", left: { fn: "coalesce", args: [{ field: "a" }, { field: "b" }] }, right: { value: 10 } } } }, +] } }] } }); + +let k: Kysely>; +let pool: Pool; + +if (PG_URL) { + beforeAll(() => { + pool = new Pool({ connectionString: PG_URL }); + k = new Kysely>({ dialect: new PostgresDialect({ pool }) }); + }); + afterAll(async () => { + await sql.raw(`DROP TABLE IF EXISTS "${TABLE}" CASCADE`).execute(k); + await k.destroy(); + }); +} + +const ours = (changes: readonly unknown[]) => + changes.filter((c) => JSON.stringify(c).includes(TABLE)); + +realDescribe("cross-field CHECK extensions — apply, then re-diff with no probe", () => { + test("every emitted CHECK reads back as itself", async () => { + await sql.raw(`DROP TABLE IF EXISTS "${TABLE}" CASCADE`).execute(k); + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(META)]); + expect(errors.map((e) => e.message)).toEqual([]); + const expected = buildExpectedSchema(root, { dialect: "postgres" }); + const first = await diff({ expected, actual: await introspectPostgres(k), dialect: "postgres" }); + const { up } = emit(ours(first.changes) as typeof first.changes, { dialect: "postgres", expectedSchema: expected }); + for (const stmt of up.split(";").map((s) => s.trim()).filter(Boolean)) await sql.raw(stmt).execute(k); + + const followup = ours((await diff({ expected, actual: await introspectPostgres(k), dialect: "postgres" })).changes); + if (followup.length > 0) for (const c of followup) console.error(" -", JSON.stringify(c)); + expect(followup).toEqual([]); + }); + + test("the guarded rule is enforced only when the condition holds", async () => { + await sql.raw(`DELETE FROM "${TABLE}"`).execute(k); + // kind = Shared (2): the exactly-one rule does not apply, so two present is fine. + await sql.raw(`INSERT INTO "${TABLE}" ("a", "b", "kind") VALUES (1, 2, 2)`).execute(k); + // kind = Owned (1): exactly one of a, b. + await expect(sql.raw(`INSERT INTO "${TABLE}" ("a", "b", "kind") VALUES (1, 2, 1)`).execute(k)).rejects.toThrow(/CK_Note_One/); + await sql.raw(`INSERT INTO "${TABLE}" ("a", "kind") VALUES (1, 1)`).execute(k); + // @max 2: three present is refused. + await expect(sql.raw(`INSERT INTO "${TABLE}" ("a", "b", "c", "kind") VALUES (1, 2, 3, 2)`).execute(k)).rejects.toThrow(/CK_Note_Few/); + }); +}); diff --git a/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts b/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts index 5ac1d01e2e..32dc108ae7 100644 --- a/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/cross-field-check-extensions.test.ts @@ -11,6 +11,8 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { efcoreConventions } from "../../src/schema-conventions.js"; +import { isInvalidCheckNameError } from "../../src/errors.js"; const FIXTURE = join(import.meta.dir, "../../../../../../fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json"); @@ -56,7 +58,8 @@ describe("cross-field CHECK extensions", () => { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); expect(errors).toHaveLength(0); const t = buildExpectedSchema(root, { dialect: "postgres" }).tables[0]!; - expect(t.checks.map((c) => c.expression)).toEqual(['num_nonnulls("a", "b", "c") BETWEEN 1 AND 2']); + // Two comparisons, the way Postgres stores a BETWEEN, so the CHECK reads back unchanged. + expect(t.checks.map((c) => c.expression)).toEqual(['num_nonnulls("a", "b", "c") >= 1 AND num_nonnulls("a", "b", "c") <= 2']); }); test("no @max, no @condition, no @constraintName: unchanged", async () => { @@ -70,4 +73,116 @@ describe("cross-field CHECK extensions", () => { const t = buildExpectedSchema(root, { dialect: "postgres" }).tables[0]!; expect(t.checks).toEqual([{ name: "t_a_atleastone_chk", expression: '"a" IS NOT NULL OR "b" IS NOT NULL' }]); }); + +}); + +/** An entity "T" (table "t") with an id key and the given children, loaded with no errors. */ +async function load(children: unknown[]) { + const doc = { "metadata.root": { package: "acme", children: [{ "object.entity": { name: "T", children: [ + { "source.rdb": { "@table": "t" } }, { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ...children, + ] } }] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors.map((e) => e.message)).toEqual([]); + return root; +} + +async function checksOf(children: unknown[], dialect: "postgres" | "sqlite" = "postgres") { + const t = buildExpectedSchema(await load(children), { dialect }).tables[0]!; + return t.checks.map((c) => c.expression); +} + +const AB = [{ "field.long": { name: "a" } }, { "field.long": { name: "b" } }]; + +describe("@condition rendering", () => { + test("and / or / not / isNull / isNotNull negate by De Morgan, down to the comparisons", async () => { + const condition = { op: "and", args: [{ op: "isNull", arg: { field: "a" } }, { op: "not", arg: { op: "eq", left: { field: "b" }, right: { value: 1 } } }] }; + expect(await checksOf([...AB, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@condition": condition } }])) + .toEqual(['(("a" IS NOT NULL) OR ("b" = 1)) OR ("a" IS NOT NULL OR "b" IS NOT NULL)']); + }); + + test("an isNotNull condition negates to isNull; or negates to and", async () => { + const condition = { op: "or", args: [{ op: "isNotNull", arg: { field: "a" } }, { op: "gt", left: { field: "b" }, right: { value: 2 } }] }; + expect(await checksOf([...AB, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@condition": condition } }])) + .toEqual(['(("a" IS NULL) AND ("b" <= 2)) OR ("a" IS NOT NULL OR "b" IS NOT NULL)']); + }); + + test("coalesce is an operand, not a compound", async () => { + const condition = { op: "eq", left: { fn: "coalesce", args: [{ field: "a" }, { field: "b" }] }, right: { value: 1 } }; + expect(await checksOf([...AB, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@condition": condition } }])) + .toEqual(['(COALESCE("a", "b") <> 1) OR ("a" IS NOT NULL OR "b" IS NOT NULL)']); + }); + + test("a compound comparison operand is parenthesised (IS binds looser than =)", async () => { + const flag = { "field.boolean": { name: "flag" } }; + const condition = { op: "eq", left: { op: "isNull", arg: { field: "a" } }, right: { field: "flag" } }; + expect(await checksOf([...AB, flag, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@condition": condition } }])) + .toEqual(['(("a" IS NULL) <> "flag") OR ("a" IS NOT NULL OR "b" IS NOT NULL)']); + }); + + test("a boolean literal is 1 / 0 on SQLite", async () => { + const flag = { "field.boolean": { name: "flag" } }; + const condition = { op: "eq", left: { field: "flag" }, right: { value: true } }; + expect(await checksOf([...AB, flag, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@condition": condition } }], "sqlite")) + .toEqual(['("flag" <> 1) OR ("a" IS NOT NULL OR "b" IS NOT NULL)']); + }); + + test("an int-backed enum member is compared as its stored integer", async () => { + const kind = { "field.enum": { name: "kind", "@values": ["Owned", "Shared"], "@intValueMap": { Owned: 1, Shared: 2 } } }; + const condition = { op: "eq", left: { field: "kind" }, right: { value: "Owned" } }; + const out = await checksOf([...AB, kind, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@condition": condition } }]); + expect(out).toContain('("kind" <> 1) OR ("a" IS NOT NULL OR "b" IS NOT NULL)'); + }); + + test("requiredWhen and presentIff take a @condition too", async () => { + const kind = { "field.string": { name: "kind" } }; + const condition = { op: "eq", left: { field: "kind" }, right: { value: "x" } }; + const out = await checksOf([...AB, kind, + { "validator.requiredWhen": { name: "rw", "@field": "a", "@when": "b", "@equals": "1", "@condition": condition } }, + { "validator.presentIff": { name: "pi", "@field": "b", "@when": "a", "@equals": "2", "@condition": condition } }, + ]); + expect(out).toEqual([ + `("kind" <> 'x') OR (("b" IS DISTINCT FROM 1) OR ("a" IS NOT NULL))`, + `("kind" <> 'x') OR (("b" IS NOT NULL) = ("a" IS NOT DISTINCT FROM 2))`, + ]); + }); +}); + +describe("declared CHECK names", () => { + const len = (constraintName: string) => ({ "field.string": { name: "code", "@maxLength": 10, children: [ + { "validator.length": { name: "len", "@max": 10, "@constraintName": constraintName } }, + ] } }); + + test("two CHECKs on one table with one declared name are refused", async () => { + const root = await load([...AB, + { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@constraintName": "CK_T_X" } }, + { "validator.comparison": { name: "cmp", "@left": "a", "@op": "lt", "@right": "b", "@constraintName": "CK_T_X" } }, + ]); + let err: unknown; + try { buildExpectedSchema(root, { dialect: "postgres" }); } catch (e) { err = e; } + expect(isInvalidCheckNameError(err)).toBe(true); + expect((err as Error).message).toContain('CHECK "CK_T_X" on table "t" has the same name as another CHECK named "CK_T_X"'); + }); + + test("a declared name equal to the primary key's is refused", async () => { + const root = await load([...AB, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@constraintName": "t_pkey" } }]); + expect(() => buildExpectedSchema(root, { dialect: "postgres" })).toThrow(/has the same name as the primary key/); + }); + + test("a declared name over 63 bytes is refused on Postgres, accepted on SQLite", async () => { + const long = "CK_" + "x".repeat(61); + const root = await load([...AB, { "validator.atLeastOne": { name: "one", "@fields": ["a", "b"], "@constraintName": long } }]); + expect(() => buildExpectedSchema(root, { dialect: "postgres" })).toThrow(/is 64 bytes; Postgres keeps only the first 63/); + expect(buildExpectedSchema(root, { dialect: "sqlite" }).tables[0]!.checks.map((c) => c.name)).toEqual([long]); + }); + + test("a declared name keeps a length CHECK the efcore conventions would skip as redundant", async () => { + const t = buildExpectedSchema(await load([len("CK_T_Code")]), { dialect: "postgres", conventions: efcoreConventions }).tables[0]!; + expect(t.checks).toEqual([{ name: "CK_T_Code", expression: 'length("code") <= 10' }]); + const plain = buildExpectedSchema(await load([{ "field.string": { name: "code", "@maxLength": 10, children: [ + { "validator.length": { name: "len", "@max": 10 } }, + ] } }]), { dialect: "postgres", conventions: efcoreConventions }).tables[0]!; + expect(plain.checks).toEqual([]); + }); }); From 984b0b8471897c977554ce7809ef8b5069b2ac43 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Tue, 3 Nov 2026 09:59:28 -0500 Subject: [PATCH 025/267] feat(field): field.duration, a fixed-length span of time, in every port A new field subtype for an elapsed time, timeout or delay: C# TimeSpan, Java and Kotlin java.time.Duration, Python timedelta, TypeScript string. The column is a Postgres interval, text on SQLite and MySQL. The wire form is an ISO-8601 duration of days, hours, minutes and seconds; every port writes one canonical form (PT1H30M, PT26H, -PT1M30S, PT0S) and refuses years, months, weeks and spans past 256204778 hours (the largest a TimeSpan holds), so any port reads what any port wrote. Shared vectors: fixtures/duration-wire. Postgres 15 refuses a signed ISO-8601 duration as interval input, so a value bound as text and a declared @default use Postgres's own HH:MM:SS spelling, which it returns unchanged (no default drift). A live interval column still modelled as field.string reads as text, as before, so it does not become drift. Filters: eq, ne, in, isNull, canonicalised per dialect; a duration inside a jsonb value object is canonical too. Corpora: field-duration-basic, validation-conformance (13 cases), persistence-conformance AllTypes.durationVal (roundtrip and update scenarios, green on Postgres in every port), contract-conformance all-fields. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 15 + .../references/vocabulary-hygiene.md | 4 + .../skills/metaobjects-authoring/SKILL.md | 1 + docs/CONFORMANCE.md | 7 +- docs/features/field-types.md | 18 +- docs/ports/csharp.md | 12 + .../drizzle-fastify/filter-allowlist.ts | 2 + .../runtime/drizzle-fastify/filter-parser.ts | 10 +- .../drizzle-fastify/filter-value-format.ts | 4 + .../codegen/runtime/duration-wire.ts | 6 + .../codegen/templates/drizzle-schema.ts | 18 +- .../codegen/templates/duration-wire-helper.ts | 196 +++++++++++ .../codegen/templates/field-meta.ts | 5 + .../codegen/templates/filter-allowlist.ts | 4 + .../codegen/templates/inferred-types.ts | 3 + .../codegen/templates/view-decl.ts | 20 +- .../codegen/templates/zod-validators.ts | 28 +- .../drizzle-fastify/filter-allowlist.ts | 2 + .../runtime/drizzle-fastify/filter-parser.ts | 10 +- .../drizzle-fastify/filter-value-format.ts | 4 + .../showcase/codegen/runtime/duration-wire.ts | 6 + .../codegen/templates/drizzle-schema.ts | 18 +- .../codegen/templates/duration-wire-helper.ts | 196 +++++++++++ .../showcase/codegen/templates/field-meta.ts | 5 + .../codegen/templates/filter-allowlist.ts | 4 + .../codegen/templates/inferred-types.ts | 3 + .../showcase/codegen/templates/view-decl.ts | 20 +- .../codegen/templates/zod-validators.ts | 28 +- examples/showcase/site-payload.json | 2 +- .../references/vocabulary-hygiene.md | 4 + .../skills/metaobjects-authoring/SKILL.md | 1 + .../references/vocabulary-hygiene.md | 4 + .../skills/metaobjects-authoring/SKILL.md | 1 + .../references/vocabulary-hygiene.md | 4 + .../skills/metaobjects-authoring/SKILL.md | 1 + .../references/vocabulary-hygiene.md | 4 + .../skills/metaobjects-authoring/SKILL.md | 1 + .../references/vocabulary-hygiene.md | 4 + .../skills/metaobjects-authoring/SKILL.md | 1 + .../field-duration-basic/expected.json | 50 +++ .../input/meta.timers.json | 20 ++ .../expected/openapi.json | 70 +++- .../contract/AllFields.create.schema.json | 5 + .../acme/contract/AllFields.schema.json | 9 + .../contract/AllFields.strict.schema.json | 8 + .../contract/AllFields.update.schema.json | 8 + .../expected/openapi.json | 70 +++- .../contract/AllFields.create.schema.json | 5 + .../acme/contract/AllFields.schema.json | 9 + .../contract/AllFields.strict.schema.json | 8 + .../contract/AllFields.update.schema.json | 8 + .../all-fields/expected/openapi.json | 70 +++- .../contract/AllFields.create.schema.json | 5 + .../acme/contract/AllFields.schema.json | 9 + .../contract/AllFields.strict.schema.json | 8 + .../contract/AllFields.update.schema.json | 8 + .../contract-conformance/all-fields/meta.json | 1 + fixtures/duration-wire/README.md | 29 ++ fixtures/duration-wire/vectors.json | 87 +++++ fixtures/metamodel-docs/expected/INDEX.md | 1 + fixtures/metamodel-docs/expected/providers.md | 5 +- .../metamodel-docs/expected/types/field.md | 33 ++ .../canonical/meta.fitness.json | 1 + .../canonical/schema.mysql.sql | 1 + .../canonical/schema.postgres.sql | 1 + .../canonical/schema.sqlite.sql | 1 + .../persistence-conformance/normalization.md | 1 + .../queries/roundtrip-all-types.yaml | 13 +- .../queries/update-delete-all-types.yaml | 3 + .../registry-conformance/coverage-report.json | 38 ++- .../expected-registry.json | 142 ++++++++ fixtures/validation-conformance/README.md | 11 + fixtures/validation-conformance/cases.json | 15 +- fixtures/validation-conformance/meta.json | 1 + .../runtime-errors.json | 72 +++++ .../DurationWireTests.cs | 288 +++++++++++++++++ .../ReportExportGeneratorTests.cs | 50 ++- .../ValidationConformanceTests.cs | 2 +- .../MetaObjects.Codegen/CSharpNaming.cs | 5 +- .../Generators/DbContextGenerator.cs | 80 ++++- .../Generators/EntityGenerator.cs | 306 ++++++++++++++++++ .../Generators/ExtractorGenerator.cs | 17 +- .../Generators/ReportExportGenerator.cs | 52 ++- .../Generators/RoutesGenerator.cs | 70 ++-- .../MetaObjects.Codegen/HelperRuntime.cs | 4 +- .../MetaObjects.Codegen.csproj | 1 + .../Runtime/DurationWire.cs | 256 +++++++++++++++ .../Runtime/EfCoreFilterDispatch.cs | 10 +- .../Api/DurationWireGeneratedApiTests.cs | 273 ++++++++++++++++ .../Generated/AllTypes.g.cs | 3 + .../Generated/AllTypesNames.g.cs | 3 + .../Generated/AppDbContext.g.cs | 4 + .../Generated/DurationWire.g.cs | 256 +++++++++++++++ .../Runner/EntityRow.cs | 2 +- .../Runner/Normalization.cs | 3 + .../Runner/WriteCoercion.cs | 6 + .../MetaObjects/Core/Field/FieldConstants.cs | 11 + .../MetaObjects/Core/Query/QueryConstants.cs | 3 + server/csharp/MetaObjects/CoreTypes.cs | 5 +- .../MetaObjects/SpecMetamodel/field.json | 8 + .../exposed1x/Exposed1xRoundTripTest.kt | 19 ++ server/java/codegen-kotlin/pom.xml | 1 + .../generator/kotlin/GeneratorRegistry.kt | 9 +- .../kotlin/KotlinDurationWireEmitter.kt | 211 ++++++++++++ .../generator/kotlin/KotlinEntityGenerator.kt | 29 ++ .../kotlin/KotlinExposedTableGenerator.kt | 143 ++++++++ .../kotlin/KotlinReportExportGenerator.kt | 44 ++- .../kotlin/KotlinSpringControllerGenerator.kt | 34 +- .../generator/kotlin/KotlinTypeMapper.kt | 30 ++ .../kotlin/KotlinDurationWireTest.kt | 184 +++++++++++ .../kotlin/KotlinExposedTableGeneratorTest.kt | 39 +++ .../KotlinM2mTraversalCompileRunTest.kt | 7 +- .../kotlin/KotlinReportExportGeneratorTest.kt | 61 ++++ .../generator/kotlin/KotlinTypeMapperTest.kt | 16 + server/java/codegen-spring/pom.xml | 3 + .../generator/GeneratorRegistry.java | 6 +- .../generator/spring/SpringDtoGenerator.java | 69 +++- .../spring/SpringGeneratorSupport.java | 35 ++ .../spring/SpringOutputParserGenerator.java | 11 + .../spring/SpringReportExportGenerator.java | 61 +++- .../generator/spring/SpringTypeMapper.java | 5 + .../spring/SpringValueObjectGenerator.java | 10 + .../spring/runtime/CanonicalDuration.java | 130 ++++++++ .../CanonicalDurationDeserializer.java | 50 +++ .../runtime/CanonicalDurationSerializer.java | 34 ++ .../GeneratedScalarExtractLockStepTest.java | 2 +- .../SpringDurationWireCompileRunTest.java | 177 ++++++++++ .../SpringReportExportDurationCellTest.java | 26 ++ .../spring/SpringTypeMapperTest.java | 14 + .../spring/runtime/DurationWireTest.java | 107 ++++++ .../integration/kotlin/Normalization.kt | 2 + .../kotlin/QueryScenarioConformanceTest.kt | 11 + .../integration/kotlin/QueryScenarioRunner.kt | 6 + .../kotlin/tables/AllTypesTable.kt | 5 + .../kotlin/tables/MetaDurationColumnType.kt | 38 +++ .../integration/QueryScenarioTests.java | 13 +- .../integration/RoundtripWriter.java | 6 + .../mojo/EjectRuntimeRoundTripTest.java | 9 +- .../metaobjects/mojo/EjectSupportTest.java | 3 +- .../com/metaobjects/field/DurationField.java | 77 +++++ .../com/metaobjects/field/DurationWire.java | 250 ++++++++++++++ .../field/FieldTypesMetaDataProvider.java | 1 + .../java/com/metaobjects/query/FilterOps.java | 4 + .../field/DurationWireVectorsTest.java | 120 +++++++ .../manager/db/codec/JdbcCodecs.java | 50 +++ .../manager/db/driver/PostgresDriver.java | 19 ++ .../db/codec/JdbcCodecRoundTripTest.java | 51 +++ .../metaobjects/codegen/generator_registry.py | 4 +- .../codegen/generators/entity_model.py | 53 ++- .../generators/filter_allowlist_generator.py | 4 +- .../codegen/generators/router_generator.py | 30 +- .../codegen/runtime/decimal_wire.py | 33 +- .../codegen/runtime/duration_wire.py | 225 +++++++++++++ .../codegen/runtime/fr010_field_mapping.py | 2 + .../codegen/runtime/shared_predicates.py | 11 + .../src/metaobjects/codegen/type_map.py | 5 + .../metaobjects/loader/validation_passes.py | 6 +- .../meta/core/field/field_constants.py | 8 + .../metaobjects/meta/core/field/meta_field.py | 3 + .../python/src/metaobjects/runtime/dialect.py | 26 +- .../src/metaobjects/runtime/object_manager.py | 107 +++++- .../metaobjects/runtime/validator_runner.py | 7 + .../src/metaobjects/spec_metamodel/field.json | 8 + .../tests/codegen/test_duration_codegen.py | 163 ++++++++++ .../codegen/test_validation_conformance.py | 26 +- .../python/tests/integration/normalization.py | 9 +- .../tests/runtime/test_duration_wire.py | 104 ++++++ .../runtime/test_object_manager_duration.py | 225 +++++++++++++ .../tests/runtime/test_validator_runner.py | 26 ++ .../packages/codegen-ts/src/column-mapper.ts | 41 ++- .../codegen-ts/src/contract/field-schema.ts | 27 ++ .../codegen-ts/src/cube/cube-members.ts | 7 +- .../src/prisma/build-prisma-schema.ts | 12 + .../src/templates/drizzle-schema.ts | 18 +- .../src/templates/duration-wire-helper.ts | 196 +++++++++++ .../codegen-ts/src/templates/field-meta.ts | 5 + .../src/templates/filter-allowlist.ts | 4 + .../src/templates/fr010-field-mapping.ts | 3 + .../src/templates/inferred-types.ts | 3 + .../codegen-ts/src/templates/output-parser.ts | 3 + .../codegen-ts/src/templates/view-decl.ts | 20 +- .../src/templates/zod-validators.ts | 28 +- .../codegen-ts/test/column-mapper.test.ts | 31 +- .../test/contract/contract-behaviours.test.ts | 13 +- .../duration-json-schema-pattern.test.ts | 49 +++ .../test/cube/build-cube-model.test.ts | 1 + .../test/drizzle-duration-column.test.ts | 169 ++++++++++ .../test/duration-wire-helper.test.ts | 156 +++++++++ .../output-parser-subtype-coverage.test.ts | 7 +- .../test/prisma/prisma-schema.test.ts | 15 + .../test/templates/zod-validators.test.ts | 17 +- .../test/zod-validators-execution.test.ts | 29 +- .../src/canonical-schema-mysql.ts | 1 + .../metadata/src/core/field/duration-wire.ts | 176 ++++++++++ .../src/core/field/field-constants.ts | 7 + .../core/field/field-definition.embedded.ts | 8 + .../metadata/src/core/field/meta-field.ts | 4 + .../src/core/query/query-constants.ts | 6 +- .../typescript/packages/metadata/src/index.ts | 1 + .../field-definition-completeness.test.ts | 4 +- .../packages/migrate-ts/src/diff/index.ts | 25 +- .../packages/migrate-ts/src/emit/postgres.ts | 1 + .../packages/migrate-ts/src/emit/sqlite.ts | 1 + .../migrate-ts/src/expected-schema.ts | 26 +- .../migrate-ts/src/introspect/postgres.ts | 1 + .../packages/migrate-ts/src/sql-type.ts | 3 + .../integration/pg-duration-roundtrip.test.ts | 106 ++++++ .../src/drizzle-fastify/filter-allowlist.ts | 2 + .../src/drizzle-fastify/filter-parser.ts | 10 +- .../drizzle-fastify/filter-value-format.ts | 4 + .../packages/runtime-ts/src/duration-wire.ts | 6 + .../packages/runtime-ts/src/object-manager.ts | 16 +- .../packages/runtime-ts/src/query-builder.ts | 33 +- .../packages/runtime-ts/src/type-coercer.ts | 78 ++++- .../runtime-ts/src/validator-runner.ts | 16 +- .../test/duration-wire-vectors.test.ts | 75 +++++ .../test/object-manager-duration.test.ts | 75 +++++ .../src/templates/drizzle-schema.ts | 18 +- .../src/templates/duration-wire-helper.ts | 196 +++++++++++ .../src/templates/field-meta.ts | 5 + .../src/templates/filter-allowlist.ts | 4 + .../src/templates/inferred-types.ts | 3 + .../src/templates/view-decl.ts | 20 +- .../src/templates/zod-validators.ts | 28 +- site-reference/index.html | 5 + site-reference/providers.html | 5 +- site-reference/types/field.html | 150 +++++++++ spec/metamodel/field.json | 8 + 229 files changed, 8321 insertions(+), 199 deletions(-) create mode 100644 examples/advanced-modeling/codegen/runtime/duration-wire.ts create mode 100644 examples/advanced-modeling/codegen/templates/duration-wire-helper.ts create mode 100644 examples/showcase/codegen/runtime/duration-wire.ts create mode 100644 examples/showcase/codegen/templates/duration-wire-helper.ts create mode 100644 fixtures/conformance/field-duration-basic/expected.json create mode 100644 fixtures/conformance/field-duration-basic/input/meta.timers.json create mode 100644 fixtures/duration-wire/README.md create mode 100644 fixtures/duration-wire/vectors.json create mode 100644 server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs create mode 100644 server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/Generated/DurationWire.g.cs create mode 100644 server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireTest.kt create mode 100644 server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDuration.java create mode 100644 server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDurationDeserializer.java create mode 100644 server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDurationSerializer.java create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringDurationWireCompileRunTest.java create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringReportExportDurationCellTest.java create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/runtime/DurationWireTest.java create mode 100644 server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/MetaDurationColumnType.kt create mode 100644 server/java/metadata/src/main/java/com/metaobjects/field/DurationField.java create mode 100644 server/java/metadata/src/main/java/com/metaobjects/field/DurationWire.java create mode 100644 server/java/metadata/src/test/java/com/metaobjects/field/DurationWireVectorsTest.java create mode 100644 server/python/src/metaobjects/codegen/runtime/duration_wire.py create mode 100644 server/python/tests/codegen/test_duration_codegen.py create mode 100644 server/python/tests/runtime/test_duration_wire.py create mode 100644 server/python/tests/runtime/test_object_manager_duration.py create mode 100644 server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts create mode 100644 server/typescript/packages/codegen-ts/test/contract/duration-json-schema-pattern.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts create mode 100644 server/typescript/packages/metadata/src/core/field/duration-wire.ts create mode 100644 server/typescript/packages/migrate-ts/test/integration/pg-duration-roundtrip.test.ts create mode 100644 server/typescript/packages/runtime-ts/src/duration-wire.ts create mode 100644 server/typescript/packages/runtime-ts/test/duration-wire-vectors.test.ts create mode 100644 server/typescript/packages/runtime-ts/test/object-manager-duration.test.ts create mode 100644 server/typescript/packages/test-generators/src/templates/duration-wire-helper.ts diff --git a/AGENTS.md b/AGENTS.md index 68abde0b54..876d2175ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (436 fixtures; 36 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (437 fixtures; 37 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 91bc316ba3..f59acb350b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,21 @@ here.** ### Added +- **`field.duration`: a fixed-length span of time, in every port.** `TimeSpan` in C#, + `java.time.Duration` in Java and Kotlin, `timedelta` in Python, and a string in TypeScript; + a Postgres `interval` column, text on SQLite and MySQL. The wire form is an ISO-8601 duration + of days, hours, minutes and seconds, and every port writes the same canonical form (`PT1H30M`, + `PT26H`, `-PT1M30S`, `PT0S`); years, months and weeks are refused. Postgres does not accept a + signed ISO-8601 duration as input, so a value bound as text, and a declared `@default`, use + its own `HH:MM:SS` spelling, which it returns unchanged. Filters: `eq`, `ne`, `in`, `isNull`. + Shared vectors in `fixtures/duration-wire/`; see `docs/features/field-types.md`. A span is at + most 256204778 hours (the largest a .NET `TimeSpan` holds) in every port. + - An owned (ejected) generator copy from before this release does not know `field.duration`: + re-eject it (`meta eject --force`, or merge) before a model uses one. Models without a + duration are unaffected. + - A live Postgres `interval` column modelled as a `field.string`, the only way to model one + until now, is still read as text by `meta migrate` and `meta verify`, so it does not become + drift. Change it to `field.duration` to get the native column and type. - **CHECK names, conditions and "exactly one" from validators.** `@constraintName` on a validator that generates a CHECK (`numeric`, `length`, `regex` and the cross-field four), and on a `field.enum` for its membership CHECK, names the CHECK `meta migrate` diff --git a/agent-context/skills/metaobjects-audit/references/vocabulary-hygiene.md b/agent-context/skills/metaobjects-audit/references/vocabulary-hygiene.md index 0457d764eb..bad20b4e25 100644 --- a/agent-context/skills/metaobjects-audit/references/vocabulary-hygiene.md +++ b/agent-context/skills/metaobjects-audit/references/vocabulary-hygiene.md @@ -39,6 +39,10 @@ such, surfaced in the roadmap, but **non-failing** (the code works; the form is URL validation) — a distinct native type + behavior is a subtype, not a validated string. - A `field.string` that **holds an IP address** → recommend **`field.inet`** (native IP type; Postgres `inet` column). +- A `field.string` (or a CLR/JVM type override) that **holds a time span** (`TimeSpan`, an + `interval` column, "seconds until…") → recommend **`field.duration`** (native duration type; + Postgres `interval` column; ISO-8601 on the wire). Not a calendar span: months and years + are not durations. **Custom-provider vocabulary (adopters who register their own types/attrs):** check new/custom vocab against the ADR-0037 procedure (advisory) — e.g. *a custom subtype diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md index ad11e13b60..479ef57fb9 100644 --- a/agent-context/skills/metaobjects-authoring/SKILL.md +++ b/agent-context/skills/metaobjects-authoring/SKILL.md @@ -245,6 +245,7 @@ Reach for these before inventing anything. When no row fits, run the decision pr | Open JSON, no reader narrows it | `field.string` + `@dbColumnType: jsonb` | the LAST rung — see "A JSON column" | | URL / URI | `field.uri` | native `URI`/`Uri`; `text` column; strict absolute-URI validation (add `@lenient: true` to store any string) — a real native type + behavior, so a subtype (not a validated string) | | IP address | `field.inet` | native IP type; Postgres `inet` column; strict IPv4/IPv6-literal validation (add `@lenient: true` for a plain-string `text` column) | +| Elapsed time / timeout / delay | `field.duration` | native `TimeSpan`/`Duration`/`timedelta`; Postgres `interval` column; ISO-8601 on the wire (`PT1H30M`). Not for a calendar span ("every 3 months"): that is an int and a unit. Never a string or a count of seconds | | Validated plain string (email / hostname) | `field.string` + `@stringFormat` | `@stringFormat: email` or `@stringFormat: hostname` — idiomatic per-port validation; don't hand-write the `validator.regex` | Four rules behind those rows, in short (full text: `references/choosing-a-shape.md`): diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index d753e82668..3b52efc789 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 436 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 437 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -38,6 +38,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 59 (53 query + 6 migration) | all 59; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 53 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | | [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 119 (31 core + 10 tph + 9 m2m + 5 jsonb + 2 write-through + 2 secret-fields + 12 projection + 37 report + 11 decimal) | ✓ (Fastify reference + generated lane); `report/` and `decimal/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/` and `decimal/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/` and `decimal/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/` and `decimal/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/` and `decimal/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | +| [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file (parse, refused, Postgres text read and write) | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | | [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | @@ -286,7 +287,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker. ## Fixture-to-doc mapping -### `fixtures/conformance/` — metamodel loader + canonical serializer (436) +### `fixtures/conformance/` — metamodel loader + canonical serializer (437) | Fixture prefix | Feature doc | |---|---| @@ -612,7 +613,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 436 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 437 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 030eb300f4..72dc593707 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -24,14 +24,15 @@ across ports — a `field.currency` is integer minor units everywhere; a | `field.uuid` | `string` | `UUID` | `UUID` | `Guid` | `UUID` | `uuid` | | `field.uri` | `string` | `java.net.URI` | `java.net.URI` | `Uri` | `AnyUrl` | `text` | | `field.inet` | `string` | `InetAddress` | `InetAddress` | `IPAddress` | `IPvAnyAddress` | `inet` | +| `field.duration` | `string` (ISO-8601) | `java.time.Duration` | `java.time.Duration` | `TimeSpan` | `timedelta` | `interval` | | `field.enum` | union + `z.enum` | `Enum` | `enum class` | `enum` | `Literal` inline, `Enum` with `UPPER_CASE` members when shared by `extends` | `varchar` + `CHECK` | | `field.object` | nested type | nested class | nested data class | nested class | nested Pydantic model | per `@storage` | | `field.map` | `Record` | `Map` | `Map` | `Dictionary` | `dict[str, V]` | `jsonb` | -That is the whole registered vocabulary — 17 concrete subtypes. `field.base` is an +That is the whole registered vocabulary — 18 concrete subtypes. `field.base` is an abstract registry anchor, never authored (`ERR_ABSTRACT_SUBTYPE_AUTHORED`). -Four rows need a footnote: +Five rows need a footnote: - **`field.decimal`** is exact in every port's own type. TypeScript's type is a string. Postgres and MySQL keep the declared `numeric(@precision, @scale)` exactly; SQLite and D1 have @@ -48,6 +49,19 @@ Four rows need a footnote: which has none (the same reason `field.uuid` is a `string` there). `@lenient: true` degrades both to a plain string with no validator, and takes the `inet` column down to `text`. +- **`field.duration`** is a fixed-length span: days, hours, minutes and seconds. A calendar + span ("every 3 months") is not one, because a month has no fixed length: model it as an int + and a unit. On the wire it is an ISO-8601 duration. Every port writes one canonical form, + `[-]PT[nH][nM][n[.f]S]`: hours are never folded into days (`PT26H`), there are at most six + fractional digits, and zero is `PT0S`. Every port reads that form and also a leading day + count (`P1DT2H`). Years, months and weeks are refused, and so are lowercase designators and + fractional hours. The column is a Postgres `interval` and text elsewhere, where it holds the + canonical form, so equal spans are equal strings. Filters take `eq`, `ne`, `in` and + `isNull`; range filters are not offered yet, because a text column cannot order the + strings. For the same reason a `sort` on a duration orders by span on Postgres but by + text on SQLite and MySQL (`PT10S` before `PT9S`). The + rule and its cross-port vectors are in + [`fixtures/duration-wire/`](../../fixtures/duration-wire/). - **`field.map`** is the typed dict: string keys, and a value type set by exactly one of `@valueType` (a scalar subtype) or `@objectRef` (a value object) — `V` above. It is one jsonb column holding the JSON object; `isArray` does not apply, so no port wraps the map diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 01a0b3687e..c775647d13 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -368,6 +368,18 @@ generator copies `DecimalWire.cs` and `DecimalRangeEndpointFilter.cs`. Do not st attributes or delete `DecimalWire.g.cs` to change the output: they also check input. Set `wire` and regenerate. +A `field.duration` is a `TimeSpan` carrying `[DurationWire.Iso]`, which reads and writes the +ISO-8601 form every port shares (`PT1H30M`) instead of System.Text.Json's `01:30:00`. Npgsql maps +it to an `interval` column; on any other provider a value converter stores the canonical string. +`DurationWire.g.cs` is emitted once per namespace that has a duration, and an owned `routes` +generator also copies `DurationWire.cs`. + +One limit is Npgsql's, not the generated code's: EF reads an `interval` through Npgsql's own +`TimeSpan` conversion, which (as of Npgsql 8.0.5) refuses a positive month part but silently drops +a negative month or year part (`'-1 mons'` reads as `PT0S`) and wraps a day count past `TimeSpan`'s +range. No MetaObjects writer stores either, so only a row written by hand can hold one; the other +ports refuse it on read. + ### `Names` — the physical names, as constants `names` is opt-in — list `new MetaObjects.Codegen.Generators.NamesGenerator()` in diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts index 386b10e1e4..e349d9cf03 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-allowlist.ts @@ -15,6 +15,7 @@ import { FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, + FIELD_SUBTYPE_DURATION, type FilterOp, } from "@metaobjectsdev/metadata"; export { FILTER_OPS, OPS_BY_SUBTYPE, opsForSubType, type FilterOp }; @@ -33,6 +34,7 @@ export const FILTER_VALUE_FORMATS = [ FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, + FIELD_SUBTYPE_DURATION, ] as const; export type FilterValueFormat = (typeof FILTER_VALUE_FORMATS)[number]; diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts index c4b3066f5d..4a438c3e9c 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts @@ -15,8 +15,9 @@ import { ANY_TEMPORAL_EXPECTED, FORMAT_EXPECTED, PLUS_OFFSET_HINT, looksLikeUnencodedPlusOffset, matchesAnyTemporal, matchesFormat, utcIsoIfZoned, utcIsoInstant, } from "./filter-value-format.js"; -import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; +import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; import { canonicalDecimal } from "../decimal-wire.js"; +import { formatDuration, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -344,6 +345,13 @@ function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: stri if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; return dialect === "sqlite" ? Number(canonical) : canonical; } + // A duration bound is spelled the way the column stores it: the canonical string on a text + // column (SQLite, MySQL), so `PT90M` equals a stored `PT1H30M`; the interval spelling on + // Postgres, which compares spans and refuses a signed ISO-8601 duration. + if (rule.format === FIELD_SUBTYPE_DURATION) { + const micros = parseDurationLiteral(s) as bigint; + return dialect === "sqlite" || dialect === "mysql" ? formatDuration(micros) : formatPostgresInterval(micros); + } // A timestamp bound is compared in the same UTC spelling the generated schemas store: // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. // not @localTime) reads a zoneless or date-only bound as UTC, as its write schema does — diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts index 5def0974f6..39ee917ec5 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts @@ -17,9 +17,11 @@ import { FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, + FIELD_SUBTYPE_DURATION, } from "@metaobjectsdev/metadata"; import type { FilterValueFormat } from "./filter-allowlist.js"; import { canonicalDecimal } from "../decimal-wire.js"; +import { parseDurationLiteral } from "../duration-wire.js"; const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; const TIME_RE = /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?$/; @@ -48,6 +50,7 @@ const CHECKS: Readonly boolean>> = { [FIELD_SUBTYPE_TIMESTAMP]: isTimestamp, [FIELD_SUBTYPE_UUID]: (s) => UUID_RE.test(s), [FIELD_SUBTYPE_DECIMAL]: (s) => canonicalDecimal(s) !== undefined, + [FIELD_SUBTYPE_DURATION]: (s) => parseDurationLiteral(s) !== undefined, }; /** The `expected` member of the `invalid_filter_value` envelope, per format. */ @@ -57,6 +60,7 @@ export const FORMAT_EXPECTED: Readonly> = { [FIELD_SUBTYPE_TIMESTAMP]: "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", [FIELD_SUBTYPE_UUID]: "uuid (8-4-4-4-12 hex)", [FIELD_SUBTYPE_DECIMAL]: "decimal number (digits, optional fraction, optional exponent)", + [FIELD_SUBTYPE_DURATION]: "duration (ISO 8601, e.g. PT1H30M; no years, months or weeks)", }; /** `expected` for a temporal rule that does not say WHICH temporal format it is. */ diff --git a/examples/advanced-modeling/codegen/runtime/duration-wire.ts b/examples/advanced-modeling/codegen/runtime/duration-wire.ts new file mode 100644 index 0000000000..dc820cd628 --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/duration-wire.ts @@ -0,0 +1,6 @@ +// The field.duration wire rule lives in @metaobjectsdev/metadata (shared with migrate-ts); +// re-exported here so the runtime's callers import it beside the decimal wire helpers. +export { + DURATION_PATTERN, DURATION_RE, parseDurationLiteral, formatDuration, formatPostgresInterval, + canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, +} from "@metaobjectsdev/metadata"; diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index 93e85d56a0..74df06cb0d 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -18,7 +18,7 @@ import { import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { crossEntitySpecifier, valueObjectModuleSpecifier } from "@metaobjectsdev/codegen-ts/engine"; import { - mapColumnType, PG_IDENTITY_CAPABLE_FNS, + mapColumnType, PG_IDENTITY_CAPABLE_FNS, DURATION_COLUMN_FN, type ColumnSpec, type EnumIntCustomType, } from "@metaobjectsdev/codegen-ts/engine"; import { tableNameFromEntity } from "@metaobjectsdev/codegen-ts/engine"; @@ -28,6 +28,7 @@ import { } from "@metaobjectsdev/codegen-ts/engine"; import { resolveTableSchema } from "@metaobjectsdev/metadata"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; +import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; @@ -46,7 +47,8 @@ export function renderDrizzleSchema( obj: MetaObject, ctx: RenderContext, /** - * OUT param: the int-backed-enum codec const names this table DECLARES. A caller that + * OUT param: the local column-codec const names this table DECLARES (int-backed enums, and + * the duration codec). A caller that * emits another artifact referencing the same codecs into the SAME module — entity-file's * write-through replica view — passes a set here and hands it to that emitter, which then * references the consts instead of re-declaring them. A duplicate module-scope `const` is @@ -211,6 +213,8 @@ export function renderDrizzleSchema( // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by // const name so a shared enum used by two fields of the SAME entity emits once. const enumIntTypes = new Map(); + // The field.duration codec: one declaration serves every duration column of the table. + let usesDurationCodec = false; for (const child of obj.fields()) { // #213 — a derived (origin-bearing) field is read-only, materialized on the // read (view) side, NOT a column on the entity's write table (FR-024 §7). @@ -225,6 +229,7 @@ export function renderDrizzleSchema( if (spec.enumIntCustomType !== undefined) { enumIntTypes.set(spec.enumIntCustomType.fnConstName, spec.enumIntCustomType); } + if (spec.durationCustomType !== undefined) usesDurationCodec = true; const fieldDocs = renderDocsFor(child); const columnLine = renderColumn(spec, columnNameExpr(child, spec.dbName), child, ctx, isPk, pkGeneration, fkInfo, isComposite, pkg, obj.name); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); @@ -244,6 +249,7 @@ export function renderDrizzleSchema( if (spec.enumIntCustomType !== undefined) { enumIntTypes.set(spec.enumIntCustomType.fnConstName, spec.enumIntCustomType); } + if (spec.durationCustomType !== undefined) usesDurationCodec = true; const fieldDocs = renderDocsFor(child); const columnLine = renderColumn( spec, columnNameExpr(child, spec.dbName), child, ctx, false, undefined, fkMap.get(child.name), isComposite, pkg, obj.name, true, @@ -403,9 +409,11 @@ ${joinCode(columnLines, { on: ",\n", trim: false })} .map((t) => renderEnumIntCustomType(t, importModule)); if (declaredEnumIntCodecs !== undefined) { for (const name of enumIntTypes.keys()) declaredEnumIntCodecs.add(name); + if (usesDurationCodec) declaredEnumIntCodecs.add(DURATION_COLUMN_FN); } - const blocks: Code[] = [...enumIntBlocks, tableBlock]; + const durationBlocks = usesDurationCodec ? [renderDurationCustomType(dialect, importModule)] : []; + const blocks: Code[] = [...durationBlocks, ...enumIntBlocks, tableBlock]; if (relationsBlock !== null) blocks.push(relationsBlock); return blocks.length === 1 ? blocks[0]! : joinCode(blocks, { on: "\n" }); } @@ -518,7 +526,9 @@ function renderColumn( const fnSym = spec.enumIntCustomType !== undefined ? spec.enumIntCustomType.fnConstName - : imp(`${spec.fnName}@${spec.importModule}`); + : spec.durationCustomType !== undefined + ? spec.durationCustomType.fnConstName + : imp(`${spec.fnName}@${spec.importModule}`); let baseCall: Code; if (spec.fnOptions !== undefined && Object.keys(spec.fnOptions).length > 0) { diff --git a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts new file mode 100644 index 0000000000..77267db3f7 --- /dev/null +++ b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts @@ -0,0 +1,196 @@ +// The wire rule for a field.duration, as text a generated model module carries as local code. +// Generated model code imports nothing from MetaObjects, so the rule is emitted, not imported; +// metadata/src/core/field/duration-wire.ts holds the same rule and both are held to +// fixtures/duration-wire/vectors.json (test/duration-wire-helper.test.ts evaluates the text +// emitted here against them). +// +// Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left +// out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. +// The emitted code holds a span as whole seconds plus microseconds (two JS numbers of one sign), +// so it needs no bigint and is exact for any span below 2^53 seconds. + +import { code, imp, type Code } from "@metaobjectsdev/codegen-ts/engine"; +import { DURATION_PATTERN } from "@metaobjectsdev/metadata"; +import type { Dialect } from "@metaobjectsdev/codegen-ts/engine"; +import { DURATION_COLUMN_FN } from "@metaobjectsdev/codegen-ts/engine"; + +/** The accepted ISO-8601 duration form as a JS regex literal — the metadata's own pattern. */ +export const DURATION_REGEX_LITERAL = `/${DURATION_PATTERN}/`; + +/** The Zod expression that accepts a field.duration as sent (and as read back): the accepted form. */ +export const ZOD_DURATION_EXPR = `z.string().regex(${DURATION_REGEX_LITERAL})`; + +export const DURATION_WRITE_HELPER = "durationWrite"; + +/** The Zod expression of a duration WRITE field: the accepted form, rewritten to the canonical one, + * so equal spans are stored as equal strings on every dialect. */ +export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; + +/** The largest span a field.duration holds, in whole seconds: 256204778 hours, the largest whole + * hour a .NET TimeSpan holds (fixtures/duration-wire). Every port refuses one microsecond more, so + * a value one port accepts every port can read. It also bounds the emitted arithmetic: 9.2e11 + * seconds is far below 2^53, so seconds and microseconds stay exact JS integers and never format + * in exponent notation. */ +export const DURATION_MAX_SECONDS = 256204778 * 3600; + +/** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. + * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ +const ISO_PARTS_SOURCE = "/^([-+])?P(?!$)(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d{1,9}))?S)?)?$/"; + +/** Lines formatting a span of `s` whole seconds plus `us` microseconds (one sign) canonically. */ +const ISO_FORMAT_LINES = [ + " const neg = s < 0 || us < 0;", + " const a = Math.abs(s);", + " const f = Math.abs(us);", + " const h = Math.floor(a / 3600);", + " const m = Math.floor((a % 3600) / 60);", + " const sec = a % 60;", + ' let out = "PT";', + ' if (h > 0) out += h + "H";', + ' if (m > 0) out += m + "M";', + ' if (sec > 0 || f > 0) out += sec + (f > 0 ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', + ' if (out === "PT") return "PT0S";', + ' return neg ? "-" + out : out;', +]; + +/** Lines matching `text` against the accepted form: `p` (null when it is not one), then `mag` whole + * seconds and `frac` microseconds of the span's magnitude. Read only after a null check on `p`. */ +const ISO_MATCH_LINES = [ + ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, + " const mag = p === null ? 0 : Number(p[2] ?? 0) * 86400 + Number(p[3] ?? 0) * 3600 + Number(p[4] ?? 0) * 60 + Number(p[5] ?? 0);", + ' const frac = p === null ? 0 : Number((p[6] ?? "").padEnd(6, "0").slice(0, 6));', +]; + +export const DURATION_WRITE_HELPER_DECL = [ + "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", + " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", + " * fractional digits (truncated), one leading \"-\" for a negative span. A span past 256204778 hours", + " * (the bound every port holds) is a validation issue. Generated. */", + `function ${DURATION_WRITE_HELPER}(text: string, ctx: z.RefinementCtx): string {`, + ...ISO_MATCH_LINES, + " if (p === null) return text;", + ` if (mag > ${DURATION_MAX_SECONDS} || (mag === ${DURATION_MAX_SECONDS} && frac > 0)) {`, + ' ctx.addIssue({ code: "custom", message: "Duration out of range: at most 256204778 hours" });', + " return z.NEVER;", + " }", + ' const s = p[1] === "-" ? -mag : mag;', + ' const us = p[1] === "-" ? -frac : frac;', + ...ISO_FORMAT_LINES, + "}", +].join("\n"); + +/** The physical column type a duration column's `customType` declares, per dialect: the + * Postgres-native interval; TEXT on SQLite; VARCHAR(64) on MySQL (the persistence corpus's + * canonical schemas, and what `meta migrate` writes). */ +export function durationColumnDataType(dialect: Dialect): string { + return dialect === "postgres" ? "interval" : dialect === "mysql" ? "varchar(64)" : "text"; +} + +/** + * The body of the duration column's declaration, around the `customType` reference (which the + * caller supplies as an import). `[before, after]`: `before + customType + after` is the whole + * declaration. Exported so a test can evaluate the exact text a generated module carries. + * + * - `toDriver` binds what the column holds: on Postgres the interval spelling `[-]HH:MM:SS[.f]` + * (Postgres refuses a signed ISO-8601 duration as interval input, and returns a value written + * this way in exactly this spelling); on SQLite and MySQL the canonical ISO-8601 string, so equal + * spans are equal strings. It takes the value in either spelling — an ISO-8601 duration (what the + * generated write schema hands it), or the Postgres interval text runtime-ts already binds a + * filter operand or a write in — and throws for anything else. + * - `fromDriver` reads what the driver returns — ISO-8601 text, Postgres interval text in the + * default `IntervalStyle`, or a node-postgres interval object — as the canonical ISO-8601 form. + * An interval with a year or month part is not a fixed-length span: reading one throws. + */ +export function durationColumnDeclParts(dialect: Dialect): [string, string] { + const bindPostgres = dialect === "postgres"; + const before = [ + "/** A field.duration column. Binds " + (bindPostgres + ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration)," + : "the canonical ISO-8601 duration,"), + " * reads any interval back as the canonical ISO-8601 duration, and refuses an interval with a", + " * year or month part. Generated. */", + `const ${DURATION_COLUMN_FN} = (() => {`, + " const MICROS = 1000000;", + ` const MAX_SECONDS = ${DURATION_MAX_SECONDS};`, + " // A span normalised to one sign, refused past 256204778 hours (the bound every port holds).", + " const span = (s: number, us: number): [number, number] => {", + " s += Math.trunc(us / MICROS);", + " us %= MICROS;", + " if (s > 0 && us < 0) {", + " s -= 1;", + " us += MICROS;", + " } else if (s < 0 && us > 0) {", + " s += 1;", + " us -= MICROS;", + " }", + " const a = Math.abs(s);", + " if (!(a < MAX_SECONDS || (a === MAX_SECONDS && us === 0))) {", + ' throw new Error("a field.duration holds at most 256204778 hours (one microsecond more is refused)");', + " }", + " return [s, us];", + " };", + " const iso = (text: string): [number, number] | undefined => {", + ...ISO_MATCH_LINES.map((l) => " " + l), + " if (p === null) return undefined;", + ' return p[1] === "-" ? [-mag, -frac] : [mag, frac];', + " };", + " const isoText = ([s, us]: [number, number]): string => {", + ...ISO_FORMAT_LINES.map((l) => " " + l), + " };", + " const pgText = ([s, us]: [number, number]): string => {", + " const neg = s < 0 || us < 0;", + " const a = Math.abs(s);", + " const f = Math.abs(us);", + ' const two = (n: number): string => String(n).padStart(2, "0");', + ' let out = two(Math.floor(a / 3600)) + ":" + two(Math.floor((a % 3600) / 60)) + ":" + two(a % 60);', + ' if (f > 0) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', + ' return neg ? "-" + out : out;', + " };", + " const notFixed = (v: unknown): Error =>", + ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', + " const read = (v: unknown): [number, number] => {", + ' if (typeof v === "string") {', + " const fromIso = iso(v);", + " if (fromIso !== undefined) return span(fromIso[0], fromIso[1]);", + " const p = v.length === 0 ? null", + " : /^(?:([-+]?\\d+) years? ?)?(?:([-+]?\\d+) mons? ?)?(?:([-+]?\\d+) days? ?)?(?:([-+])?(\\d+):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?)?$/.exec(v);", + ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', + " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", + ' const t = p[5] === undefined ? 0 : Number(p[5]) * 3600 + Number(p[6]) * 60 + Number(p[7]);', + ' const tu = Number((p[8] ?? "").padEnd(6, "0"));', + ' const sign = p[4] === "-" ? -1 : 1;', + " return span(Number(p[3] ?? 0) * 86400 + sign * t, sign * tu);", + " }", + ' if (v !== null && typeof v === "object") {', + " const o = v as Record;", + " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", + " const whole = (n: number | undefined): number => Math.trunc(n ?? 0);", + " return span(", + " whole(o.days) * 86400 + whole(o.hours) * 3600 + whole(o.minutes) * 60 + whole(o.seconds),", + " Math.round((o.milliseconds ?? 0) * 1000),", + " );", + " }", + ' throw new Error("not a field.duration value: " + JSON.stringify(v));', + " };", + " return ", + ].join("\n"); + const after = [ + "<{ data: string; driverData: string }>({", + ` dataType: () => ${JSON.stringify(durationColumnDataType(dialect))},`, + ` toDriver: (value) => ${bindPostgres ? "pgText" : "isoText"}(read(value)),`, + " fromDriver: (value) => isoText(read(value)),", + " });", + "})();", + ].join("\n"); + return [before, after]; +} + +/** A duration column's Drizzle `customType` declaration, emitted ahead of the table or view that + * uses it (once per module — see enum-int-codec.ts for why the order and the once matter). */ +export function renderDurationCustomType(dialect: Dialect, importModule: string): Code { + const customTypeSym = imp(`customType@${importModule}`); + const [before, after] = durationColumnDeclParts(dialect); + return code` +${before}${customTypeSym}${after} +`; +} diff --git a/examples/advanced-modeling/codegen/templates/field-meta.ts b/examples/advanced-modeling/codegen/templates/field-meta.ts index 6182a31306..72549fd876 100644 --- a/examples/advanced-modeling/codegen/templates/field-meta.ts +++ b/examples/advanced-modeling/codegen/templates/field-meta.ts @@ -22,6 +22,7 @@ import { FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, + FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_OBJECT, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_STRING_FORMAT, @@ -43,6 +44,7 @@ import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; import { zodEnumExpr } from "./zod-enum.js"; import { viewForContext } from "@metaobjectsdev/codegen-ts/engine"; import { ZOD_INET_EXPR } from "./net-regex.js"; +import { ZOD_DURATION_EXPR } from "./duration-wire-helper.js"; // --------------------------------------------------------------------------- // inferViewKind @@ -140,6 +142,9 @@ export function zodTypeFor(field: MetaField, timestampMode: "date" | "string" = // (v4 or v6 literal). Zod-version-agnostic regex union (Zod 4 removed // `z.string().ip()`); see net-regex.ts. @lenient → a plain string. return field.attr(FIELD_ATTR_LENIENT) === true ? "z.string()" : ZOD_INET_EXPR; + case FIELD_SUBTYPE_DURATION: + // An ISO-8601 duration string; the column codec reads every row in the canonical form. + return ZOD_DURATION_EXPR; case FIELD_SUBTYPE_BOOLEAN: return "z.boolean()"; case FIELD_SUBTYPE_DATE: diff --git a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts index 4a0cd087fd..ec7c195b7c 100644 --- a/examples/advanced-modeling/codegen/templates/filter-allowlist.ts +++ b/examples/advanced-modeling/codegen/templates/filter-allowlist.ts @@ -13,6 +13,7 @@ import { FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_CURRENCY, FIELD_SUBTYPE_UUID, + FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_ENUM, FIELD_ATTR_LOCAL_TIME, opsForField, @@ -70,6 +71,9 @@ const VALUE_FORMAT_SUBTYPES = new Set([ FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_DECIMAL, + // An ISO-8601 duration: runtime-ts refuses a value that is not one, and the column codec binds + // the dialect's spelling of it. + FIELD_SUBTYPE_DURATION, ]); /** Subtypes whose values are whole numbers — `field.currency` is integer minor units. */ diff --git a/examples/advanced-modeling/codegen/templates/inferred-types.ts b/examples/advanced-modeling/codegen/templates/inferred-types.ts index 1eec56f318..4b87f2f9bc 100644 --- a/examples/advanced-modeling/codegen/templates/inferred-types.ts +++ b/examples/advanced-modeling/codegen/templates/inferred-types.ts @@ -27,6 +27,7 @@ import { FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, + FIELD_SUBTYPE_DURATION, FIELD_ATTR_REQUIRED, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_VALUE_TYPE, @@ -215,6 +216,8 @@ const SCALAR_TS_BY_SUBTYPE: Record = { // type, same as uuid). Other ports bind to their native URI/IP type. [FIELD_SUBTYPE_URI]: "string", [FIELD_SUBTYPE_INET]: "string", + // field.duration is an ISO-8601 duration string: TS has no native duration type. + [FIELD_SUBTYPE_DURATION]: "string", [FIELD_SUBTYPE_INT]: "number", [FIELD_SUBTYPE_LONG]: "number", [FIELD_SUBTYPE_DOUBLE]: "number", diff --git a/examples/advanced-modeling/codegen/templates/view-decl.ts b/examples/advanced-modeling/codegen/templates/view-decl.ts index da4a523058..eec5e9ed44 100644 --- a/examples/advanced-modeling/codegen/templates/view-decl.ts +++ b/examples/advanced-modeling/codegen/templates/view-decl.ts @@ -14,8 +14,9 @@ import { type MetaField, FIELD_SUBTYPE_OBJECT, FIELD_ATTR_OBJECT_REF, } from "@metaobjectsdev/metadata"; import type { ColumnNamingStrategy } from "@metaobjectsdev/codegen-ts/engine"; -import { mapColumnType, type EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; +import { mapColumnType, DURATION_COLUMN_FN, type EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; +import { renderDurationCustomType } from "./duration-wire-helper.js"; import { zodTypeFor } from "./field-meta.js"; import { columnExpr, type ObjectNames } from "@metaobjectsdev/codegen-ts/engine"; @@ -25,7 +26,8 @@ export interface ViewDeclOpts { /** Drives the timestamp column TS type (Date vs string) in the view declaration. */ readonly timestampMode: "date" | "string"; /** - * Int-backed-enum codec const names ALREADY declared in the module this view lands in. + * Local column-codec const names (int-backed enums, the duration codec) ALREADY declared in + * the module this view lands in. * A write-through entity's table and its replica view share one file, and both reference * the same codecs — so the view references these by name and declares only what the table * did not (a derived field's codec, which the write table omits). Absent = the view owns @@ -88,6 +90,8 @@ function viewColumnLine( opts: ViewDeclOpts, /** Codecs this view needs, collected for the caller to DECLARE — see below. */ enumIntTypes: Map, + /** The duration codec's name, when a column needs it — declared by the caller, as above. */ + usesDuration: Set, ): Code { const { dialect, columnNamingStrategy, timestampMode } = opts; const spec = mapColumnType(f, dialect, columnNamingStrategy, timestampMode); @@ -99,10 +103,14 @@ function viewColumnLine( if (spec.enumIntCustomType !== undefined) { enumIntTypes.set(spec.enumIntCustomType.fnConstName, spec.enumIntCustomType); } + // The field.duration codec is a local const too; collected under its name, declared once. + if (spec.durationCustomType !== undefined) usesDuration.add(spec.durationCustomType.fnConstName); const colSym = spec.enumIntCustomType !== undefined ? spec.enumIntCustomType.fnConstName - : imp(`${spec.fnName}@${spec.importModule}`); + : spec.durationCustomType !== undefined + ? spec.durationCustomType.fnConstName + : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 ? `, ${JSON.stringify(spec.fnOptions)}` @@ -164,7 +172,8 @@ export function renderExistingViewDecl( const { viewFn, core: viewModule } = dialectModule(opts.dialect); const viewSym = imp(`${viewFn}@${viewModule}`); const enumIntTypes = new Map(); - const viewColumnLines = fields.map((f) => viewColumnLine(f, opts, enumIntTypes)); + const usesDuration = new Set(); + const viewColumnLines = fields.map((f) => viewColumnLine(f, opts, enumIntTypes, usesDuration)); const viewNameExpr = typeof viewName === "string" ? code`${JSON.stringify(viewName)}` : viewName; // @schema — a view lands in a schema exactly as a table does, and migrate qualifies the @@ -188,6 +197,9 @@ export function renderExistingViewDecl( .filter((t) => alreadyDeclared === undefined || !alreadyDeclared.has(t.fnConstName)) .sort((a, b) => a.fnConstName.localeCompare(b.fnConstName)) .map((t) => renderEnumIntCustomType(t, viewModule)); + if (usesDuration.has(DURATION_COLUMN_FN) && (alreadyDeclared === undefined || !alreadyDeclared.has(DURATION_COLUMN_FN))) { + enumIntBlocks.unshift(renderDurationCustomType(opts.dialect, viewModule)); + } const viewBlock = code` // View declaration — Drizzle uses this for typed SELECT queries. diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts index ea4945feae..1edf2ab40b 100644 --- a/examples/advanced-modeling/codegen/templates/zod-validators.ts +++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts @@ -17,7 +17,7 @@ import { FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DECIMAL, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID, - FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, + FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, FIELD_SUBTYPE_DURATION, VALIDATOR_SUBTYPE_REQUIRED, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX, VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_ARRAY, IDENTITY_ATTR_FIELDS, IDENTITY_ATTR_GENERATION, @@ -45,6 +45,7 @@ import { } from "./date-time-regex.js"; import { renderDocsFor } from "./jsdoc.js"; import { DECIMAL_WRITE_HELPER_DECL, zodDecimalWriteExpr } from "./decimal-wire-helper.js"; +import { DURATION_WRITE_HELPER_DECL, ZOD_DURATION_EXPR, ZOD_DURATION_WRITE_EXPR } from "./duration-wire-helper.js"; import { sharedEnumForField } from "@metaobjectsdev/codegen-ts/engine"; import { sharedEnumImportSpecifier } from "@metaobjectsdev/codegen-ts/engine"; import { sharedEnumZodConstName } from "./enums-file.js"; @@ -83,6 +84,13 @@ function decimalHelperSince(since: number): string { return decimalWriteUses > since ? `${DECIMAL_WRITE_HELPER_DECL}\n\n` : ""; } +// The same device for the duration write rule (duration-wire-helper.ts). +let durationWriteUses = 0; + +function durationHelperSince(since: number): string { + return durationWriteUses > since ? `${DURATION_WRITE_HELPER_DECL}\n\n` : ""; +} + /** True when this object declares at least one @autoSet timestamp field * (onCreate or onUpdate). Drives whether codegen emits the #203 @@ -269,6 +277,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co const z = imp("z@zod"); const utcUsesBefore = utcTimestampUses; const decimalUsesBefore = decimalWriteUses; + const durationUsesBefore = durationWriteUses; const autoGenPkFields = autoGenPkFieldNames(obj); const assignedPkFields = assignedPkFieldNames(obj); const tphPin = tphDiscriminatorPin(obj); @@ -320,7 +329,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co const docsPrefix = docs ? `${docs}\n` : ""; return code` -${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ +${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${durationHelperSince(durationUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ ${joinCode(insertFieldLines, { on: ",\n" })} }); `; @@ -429,6 +438,7 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code const z = imp("z@zod"); const utcUsesBefore = utcTimestampUses; const decimalUsesBefore = decimalWriteUses; + const durationUsesBefore = durationWriteUses; const autoGenPkFields = autoGenPkFieldNames(obj); const pkFields = primaryKeyFieldNames(obj); const assignedPkFields = assignedPkFieldNames(obj); @@ -552,7 +562,7 @@ export type ${objName}CreatePreserving = ${z}.input boolean>> = { [FIELD_SUBTYPE_TIMESTAMP]: isTimestamp, [FIELD_SUBTYPE_UUID]: (s) => UUID_RE.test(s), [FIELD_SUBTYPE_DECIMAL]: (s) => canonicalDecimal(s) !== undefined, + [FIELD_SUBTYPE_DURATION]: (s) => parseDurationLiteral(s) !== undefined, }; /** The `expected` member of the `invalid_filter_value` envelope, per format. */ @@ -57,6 +60,7 @@ export const FORMAT_EXPECTED: Readonly> = { [FIELD_SUBTYPE_TIMESTAMP]: "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", [FIELD_SUBTYPE_UUID]: "uuid (8-4-4-4-12 hex)", [FIELD_SUBTYPE_DECIMAL]: "decimal number (digits, optional fraction, optional exponent)", + [FIELD_SUBTYPE_DURATION]: "duration (ISO 8601, e.g. PT1H30M; no years, months or weeks)", }; /** `expected` for a temporal rule that does not say WHICH temporal format it is. */ diff --git a/examples/showcase/codegen/runtime/duration-wire.ts b/examples/showcase/codegen/runtime/duration-wire.ts new file mode 100644 index 0000000000..dc820cd628 --- /dev/null +++ b/examples/showcase/codegen/runtime/duration-wire.ts @@ -0,0 +1,6 @@ +// The field.duration wire rule lives in @metaobjectsdev/metadata (shared with migrate-ts); +// re-exported here so the runtime's callers import it beside the decimal wire helpers. +export { + DURATION_PATTERN, DURATION_RE, parseDurationLiteral, formatDuration, formatPostgresInterval, + canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, +} from "@metaobjectsdev/metadata"; diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index 93e85d56a0..74df06cb0d 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -18,7 +18,7 @@ import { import type { RenderContext } from "@metaobjectsdev/codegen-ts/engine"; import { crossEntitySpecifier, valueObjectModuleSpecifier } from "@metaobjectsdev/codegen-ts/engine"; import { - mapColumnType, PG_IDENTITY_CAPABLE_FNS, + mapColumnType, PG_IDENTITY_CAPABLE_FNS, DURATION_COLUMN_FN, type ColumnSpec, type EnumIntCustomType, } from "@metaobjectsdev/codegen-ts/engine"; import { tableNameFromEntity } from "@metaobjectsdev/codegen-ts/engine"; @@ -28,6 +28,7 @@ import { } from "@metaobjectsdev/codegen-ts/engine"; import { resolveTableSchema } from "@metaobjectsdev/metadata"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; +import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; @@ -46,7 +47,8 @@ export function renderDrizzleSchema( obj: MetaObject, ctx: RenderContext, /** - * OUT param: the int-backed-enum codec const names this table DECLARES. A caller that + * OUT param: the local column-codec const names this table DECLARES (int-backed enums, and + * the duration codec). A caller that * emits another artifact referencing the same codecs into the SAME module — entity-file's * write-through replica view — passes a set here and hands it to that emitter, which then * references the consts instead of re-declaring them. A duplicate module-scope `const` is @@ -211,6 +213,8 @@ export function renderDrizzleSchema( // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by // const name so a shared enum used by two fields of the SAME entity emits once. const enumIntTypes = new Map(); + // The field.duration codec: one declaration serves every duration column of the table. + let usesDurationCodec = false; for (const child of obj.fields()) { // #213 — a derived (origin-bearing) field is read-only, materialized on the // read (view) side, NOT a column on the entity's write table (FR-024 §7). @@ -225,6 +229,7 @@ export function renderDrizzleSchema( if (spec.enumIntCustomType !== undefined) { enumIntTypes.set(spec.enumIntCustomType.fnConstName, spec.enumIntCustomType); } + if (spec.durationCustomType !== undefined) usesDurationCodec = true; const fieldDocs = renderDocsFor(child); const columnLine = renderColumn(spec, columnNameExpr(child, spec.dbName), child, ctx, isPk, pkGeneration, fkInfo, isComposite, pkg, obj.name); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); @@ -244,6 +249,7 @@ export function renderDrizzleSchema( if (spec.enumIntCustomType !== undefined) { enumIntTypes.set(spec.enumIntCustomType.fnConstName, spec.enumIntCustomType); } + if (spec.durationCustomType !== undefined) usesDurationCodec = true; const fieldDocs = renderDocsFor(child); const columnLine = renderColumn( spec, columnNameExpr(child, spec.dbName), child, ctx, false, undefined, fkMap.get(child.name), isComposite, pkg, obj.name, true, @@ -403,9 +409,11 @@ ${joinCode(columnLines, { on: ",\n", trim: false })} .map((t) => renderEnumIntCustomType(t, importModule)); if (declaredEnumIntCodecs !== undefined) { for (const name of enumIntTypes.keys()) declaredEnumIntCodecs.add(name); + if (usesDurationCodec) declaredEnumIntCodecs.add(DURATION_COLUMN_FN); } - const blocks: Code[] = [...enumIntBlocks, tableBlock]; + const durationBlocks = usesDurationCodec ? [renderDurationCustomType(dialect, importModule)] : []; + const blocks: Code[] = [...durationBlocks, ...enumIntBlocks, tableBlock]; if (relationsBlock !== null) blocks.push(relationsBlock); return blocks.length === 1 ? blocks[0]! : joinCode(blocks, { on: "\n" }); } @@ -518,7 +526,9 @@ function renderColumn( const fnSym = spec.enumIntCustomType !== undefined ? spec.enumIntCustomType.fnConstName - : imp(`${spec.fnName}@${spec.importModule}`); + : spec.durationCustomType !== undefined + ? spec.durationCustomType.fnConstName + : imp(`${spec.fnName}@${spec.importModule}`); let baseCall: Code; if (spec.fnOptions !== undefined && Object.keys(spec.fnOptions).length > 0) { diff --git a/examples/showcase/codegen/templates/duration-wire-helper.ts b/examples/showcase/codegen/templates/duration-wire-helper.ts new file mode 100644 index 0000000000..77267db3f7 --- /dev/null +++ b/examples/showcase/codegen/templates/duration-wire-helper.ts @@ -0,0 +1,196 @@ +// The wire rule for a field.duration, as text a generated model module carries as local code. +// Generated model code imports nothing from MetaObjects, so the rule is emitted, not imported; +// metadata/src/core/field/duration-wire.ts holds the same rule and both are held to +// fixtures/duration-wire/vectors.json (test/duration-wire-helper.test.ts evaluates the text +// emitted here against them). +// +// Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left +// out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. +// The emitted code holds a span as whole seconds plus microseconds (two JS numbers of one sign), +// so it needs no bigint and is exact for any span below 2^53 seconds. + +import { code, imp, type Code } from "@metaobjectsdev/codegen-ts/engine"; +import { DURATION_PATTERN } from "@metaobjectsdev/metadata"; +import type { Dialect } from "@metaobjectsdev/codegen-ts/engine"; +import { DURATION_COLUMN_FN } from "@metaobjectsdev/codegen-ts/engine"; + +/** The accepted ISO-8601 duration form as a JS regex literal — the metadata's own pattern. */ +export const DURATION_REGEX_LITERAL = `/${DURATION_PATTERN}/`; + +/** The Zod expression that accepts a field.duration as sent (and as read back): the accepted form. */ +export const ZOD_DURATION_EXPR = `z.string().regex(${DURATION_REGEX_LITERAL})`; + +export const DURATION_WRITE_HELPER = "durationWrite"; + +/** The Zod expression of a duration WRITE field: the accepted form, rewritten to the canonical one, + * so equal spans are stored as equal strings on every dialect. */ +export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; + +/** The largest span a field.duration holds, in whole seconds: 256204778 hours, the largest whole + * hour a .NET TimeSpan holds (fixtures/duration-wire). Every port refuses one microsecond more, so + * a value one port accepts every port can read. It also bounds the emitted arithmetic: 9.2e11 + * seconds is far below 2^53, so seconds and microseconds stay exact JS integers and never format + * in exponent notation. */ +export const DURATION_MAX_SECONDS = 256204778 * 3600; + +/** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. + * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ +const ISO_PARTS_SOURCE = "/^([-+])?P(?!$)(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d{1,9}))?S)?)?$/"; + +/** Lines formatting a span of `s` whole seconds plus `us` microseconds (one sign) canonically. */ +const ISO_FORMAT_LINES = [ + " const neg = s < 0 || us < 0;", + " const a = Math.abs(s);", + " const f = Math.abs(us);", + " const h = Math.floor(a / 3600);", + " const m = Math.floor((a % 3600) / 60);", + " const sec = a % 60;", + ' let out = "PT";', + ' if (h > 0) out += h + "H";', + ' if (m > 0) out += m + "M";', + ' if (sec > 0 || f > 0) out += sec + (f > 0 ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', + ' if (out === "PT") return "PT0S";', + ' return neg ? "-" + out : out;', +]; + +/** Lines matching `text` against the accepted form: `p` (null when it is not one), then `mag` whole + * seconds and `frac` microseconds of the span's magnitude. Read only after a null check on `p`. */ +const ISO_MATCH_LINES = [ + ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, + " const mag = p === null ? 0 : Number(p[2] ?? 0) * 86400 + Number(p[3] ?? 0) * 3600 + Number(p[4] ?? 0) * 60 + Number(p[5] ?? 0);", + ' const frac = p === null ? 0 : Number((p[6] ?? "").padEnd(6, "0").slice(0, 6));', +]; + +export const DURATION_WRITE_HELPER_DECL = [ + "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", + " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", + " * fractional digits (truncated), one leading \"-\" for a negative span. A span past 256204778 hours", + " * (the bound every port holds) is a validation issue. Generated. */", + `function ${DURATION_WRITE_HELPER}(text: string, ctx: z.RefinementCtx): string {`, + ...ISO_MATCH_LINES, + " if (p === null) return text;", + ` if (mag > ${DURATION_MAX_SECONDS} || (mag === ${DURATION_MAX_SECONDS} && frac > 0)) {`, + ' ctx.addIssue({ code: "custom", message: "Duration out of range: at most 256204778 hours" });', + " return z.NEVER;", + " }", + ' const s = p[1] === "-" ? -mag : mag;', + ' const us = p[1] === "-" ? -frac : frac;', + ...ISO_FORMAT_LINES, + "}", +].join("\n"); + +/** The physical column type a duration column's `customType` declares, per dialect: the + * Postgres-native interval; TEXT on SQLite; VARCHAR(64) on MySQL (the persistence corpus's + * canonical schemas, and what `meta migrate` writes). */ +export function durationColumnDataType(dialect: Dialect): string { + return dialect === "postgres" ? "interval" : dialect === "mysql" ? "varchar(64)" : "text"; +} + +/** + * The body of the duration column's declaration, around the `customType` reference (which the + * caller supplies as an import). `[before, after]`: `before + customType + after` is the whole + * declaration. Exported so a test can evaluate the exact text a generated module carries. + * + * - `toDriver` binds what the column holds: on Postgres the interval spelling `[-]HH:MM:SS[.f]` + * (Postgres refuses a signed ISO-8601 duration as interval input, and returns a value written + * this way in exactly this spelling); on SQLite and MySQL the canonical ISO-8601 string, so equal + * spans are equal strings. It takes the value in either spelling — an ISO-8601 duration (what the + * generated write schema hands it), or the Postgres interval text runtime-ts already binds a + * filter operand or a write in — and throws for anything else. + * - `fromDriver` reads what the driver returns — ISO-8601 text, Postgres interval text in the + * default `IntervalStyle`, or a node-postgres interval object — as the canonical ISO-8601 form. + * An interval with a year or month part is not a fixed-length span: reading one throws. + */ +export function durationColumnDeclParts(dialect: Dialect): [string, string] { + const bindPostgres = dialect === "postgres"; + const before = [ + "/** A field.duration column. Binds " + (bindPostgres + ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration)," + : "the canonical ISO-8601 duration,"), + " * reads any interval back as the canonical ISO-8601 duration, and refuses an interval with a", + " * year or month part. Generated. */", + `const ${DURATION_COLUMN_FN} = (() => {`, + " const MICROS = 1000000;", + ` const MAX_SECONDS = ${DURATION_MAX_SECONDS};`, + " // A span normalised to one sign, refused past 256204778 hours (the bound every port holds).", + " const span = (s: number, us: number): [number, number] => {", + " s += Math.trunc(us / MICROS);", + " us %= MICROS;", + " if (s > 0 && us < 0) {", + " s -= 1;", + " us += MICROS;", + " } else if (s < 0 && us > 0) {", + " s += 1;", + " us -= MICROS;", + " }", + " const a = Math.abs(s);", + " if (!(a < MAX_SECONDS || (a === MAX_SECONDS && us === 0))) {", + ' throw new Error("a field.duration holds at most 256204778 hours (one microsecond more is refused)");', + " }", + " return [s, us];", + " };", + " const iso = (text: string): [number, number] | undefined => {", + ...ISO_MATCH_LINES.map((l) => " " + l), + " if (p === null) return undefined;", + ' return p[1] === "-" ? [-mag, -frac] : [mag, frac];', + " };", + " const isoText = ([s, us]: [number, number]): string => {", + ...ISO_FORMAT_LINES.map((l) => " " + l), + " };", + " const pgText = ([s, us]: [number, number]): string => {", + " const neg = s < 0 || us < 0;", + " const a = Math.abs(s);", + " const f = Math.abs(us);", + ' const two = (n: number): string => String(n).padStart(2, "0");', + ' let out = two(Math.floor(a / 3600)) + ":" + two(Math.floor((a % 3600) / 60)) + ":" + two(a % 60);', + ' if (f > 0) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', + ' return neg ? "-" + out : out;', + " };", + " const notFixed = (v: unknown): Error =>", + ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', + " const read = (v: unknown): [number, number] => {", + ' if (typeof v === "string") {', + " const fromIso = iso(v);", + " if (fromIso !== undefined) return span(fromIso[0], fromIso[1]);", + " const p = v.length === 0 ? null", + " : /^(?:([-+]?\\d+) years? ?)?(?:([-+]?\\d+) mons? ?)?(?:([-+]?\\d+) days? ?)?(?:([-+])?(\\d+):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?)?$/.exec(v);", + ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', + " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", + ' const t = p[5] === undefined ? 0 : Number(p[5]) * 3600 + Number(p[6]) * 60 + Number(p[7]);', + ' const tu = Number((p[8] ?? "").padEnd(6, "0"));', + ' const sign = p[4] === "-" ? -1 : 1;', + " return span(Number(p[3] ?? 0) * 86400 + sign * t, sign * tu);", + " }", + ' if (v !== null && typeof v === "object") {', + " const o = v as Record;", + " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", + " const whole = (n: number | undefined): number => Math.trunc(n ?? 0);", + " return span(", + " whole(o.days) * 86400 + whole(o.hours) * 3600 + whole(o.minutes) * 60 + whole(o.seconds),", + " Math.round((o.milliseconds ?? 0) * 1000),", + " );", + " }", + ' throw new Error("not a field.duration value: " + JSON.stringify(v));', + " };", + " return ", + ].join("\n"); + const after = [ + "<{ data: string; driverData: string }>({", + ` dataType: () => ${JSON.stringify(durationColumnDataType(dialect))},`, + ` toDriver: (value) => ${bindPostgres ? "pgText" : "isoText"}(read(value)),`, + " fromDriver: (value) => isoText(read(value)),", + " });", + "})();", + ].join("\n"); + return [before, after]; +} + +/** A duration column's Drizzle `customType` declaration, emitted ahead of the table or view that + * uses it (once per module — see enum-int-codec.ts for why the order and the once matter). */ +export function renderDurationCustomType(dialect: Dialect, importModule: string): Code { + const customTypeSym = imp(`customType@${importModule}`); + const [before, after] = durationColumnDeclParts(dialect); + return code` +${before}${customTypeSym}${after} +`; +} diff --git a/examples/showcase/codegen/templates/field-meta.ts b/examples/showcase/codegen/templates/field-meta.ts index 6182a31306..72549fd876 100644 --- a/examples/showcase/codegen/templates/field-meta.ts +++ b/examples/showcase/codegen/templates/field-meta.ts @@ -22,6 +22,7 @@ import { FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, + FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_OBJECT, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_STRING_FORMAT, @@ -43,6 +44,7 @@ import { enumValues } from "@metaobjectsdev/codegen-ts/engine"; import { zodEnumExpr } from "./zod-enum.js"; import { viewForContext } from "@metaobjectsdev/codegen-ts/engine"; import { ZOD_INET_EXPR } from "./net-regex.js"; +import { ZOD_DURATION_EXPR } from "./duration-wire-helper.js"; // --------------------------------------------------------------------------- // inferViewKind @@ -140,6 +142,9 @@ export function zodTypeFor(field: MetaField, timestampMode: "date" | "string" = // (v4 or v6 literal). Zod-version-agnostic regex union (Zod 4 removed // `z.string().ip()`); see net-regex.ts. @lenient → a plain string. return field.attr(FIELD_ATTR_LENIENT) === true ? "z.string()" : ZOD_INET_EXPR; + case FIELD_SUBTYPE_DURATION: + // An ISO-8601 duration string; the column codec reads every row in the canonical form. + return ZOD_DURATION_EXPR; case FIELD_SUBTYPE_BOOLEAN: return "z.boolean()"; case FIELD_SUBTYPE_DATE: diff --git a/examples/showcase/codegen/templates/filter-allowlist.ts b/examples/showcase/codegen/templates/filter-allowlist.ts index 4a0cd087fd..ec7c195b7c 100644 --- a/examples/showcase/codegen/templates/filter-allowlist.ts +++ b/examples/showcase/codegen/templates/filter-allowlist.ts @@ -13,6 +13,7 @@ import { FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_CURRENCY, FIELD_SUBTYPE_UUID, + FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_ENUM, FIELD_ATTR_LOCAL_TIME, opsForField, @@ -70,6 +71,9 @@ const VALUE_FORMAT_SUBTYPES = new Set([ FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_DECIMAL, + // An ISO-8601 duration: runtime-ts refuses a value that is not one, and the column codec binds + // the dialect's spelling of it. + FIELD_SUBTYPE_DURATION, ]); /** Subtypes whose values are whole numbers — `field.currency` is integer minor units. */ diff --git a/examples/showcase/codegen/templates/inferred-types.ts b/examples/showcase/codegen/templates/inferred-types.ts index 1eec56f318..4b87f2f9bc 100644 --- a/examples/showcase/codegen/templates/inferred-types.ts +++ b/examples/showcase/codegen/templates/inferred-types.ts @@ -27,6 +27,7 @@ import { FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, + FIELD_SUBTYPE_DURATION, FIELD_ATTR_REQUIRED, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_VALUE_TYPE, @@ -215,6 +216,8 @@ const SCALAR_TS_BY_SUBTYPE: Record = { // type, same as uuid). Other ports bind to their native URI/IP type. [FIELD_SUBTYPE_URI]: "string", [FIELD_SUBTYPE_INET]: "string", + // field.duration is an ISO-8601 duration string: TS has no native duration type. + [FIELD_SUBTYPE_DURATION]: "string", [FIELD_SUBTYPE_INT]: "number", [FIELD_SUBTYPE_LONG]: "number", [FIELD_SUBTYPE_DOUBLE]: "number", diff --git a/examples/showcase/codegen/templates/view-decl.ts b/examples/showcase/codegen/templates/view-decl.ts index da4a523058..eec5e9ed44 100644 --- a/examples/showcase/codegen/templates/view-decl.ts +++ b/examples/showcase/codegen/templates/view-decl.ts @@ -14,8 +14,9 @@ import { type MetaField, FIELD_SUBTYPE_OBJECT, FIELD_ATTR_OBJECT_REF, } from "@metaobjectsdev/metadata"; import type { ColumnNamingStrategy } from "@metaobjectsdev/codegen-ts/engine"; -import { mapColumnType, type EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; +import { mapColumnType, DURATION_COLUMN_FN, type EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; +import { renderDurationCustomType } from "./duration-wire-helper.js"; import { zodTypeFor } from "./field-meta.js"; import { columnExpr, type ObjectNames } from "@metaobjectsdev/codegen-ts/engine"; @@ -25,7 +26,8 @@ export interface ViewDeclOpts { /** Drives the timestamp column TS type (Date vs string) in the view declaration. */ readonly timestampMode: "date" | "string"; /** - * Int-backed-enum codec const names ALREADY declared in the module this view lands in. + * Local column-codec const names (int-backed enums, the duration codec) ALREADY declared in + * the module this view lands in. * A write-through entity's table and its replica view share one file, and both reference * the same codecs — so the view references these by name and declares only what the table * did not (a derived field's codec, which the write table omits). Absent = the view owns @@ -88,6 +90,8 @@ function viewColumnLine( opts: ViewDeclOpts, /** Codecs this view needs, collected for the caller to DECLARE — see below. */ enumIntTypes: Map, + /** The duration codec's name, when a column needs it — declared by the caller, as above. */ + usesDuration: Set, ): Code { const { dialect, columnNamingStrategy, timestampMode } = opts; const spec = mapColumnType(f, dialect, columnNamingStrategy, timestampMode); @@ -99,10 +103,14 @@ function viewColumnLine( if (spec.enumIntCustomType !== undefined) { enumIntTypes.set(spec.enumIntCustomType.fnConstName, spec.enumIntCustomType); } + // The field.duration codec is a local const too; collected under its name, declared once. + if (spec.durationCustomType !== undefined) usesDuration.add(spec.durationCustomType.fnConstName); const colSym = spec.enumIntCustomType !== undefined ? spec.enumIntCustomType.fnConstName - : imp(`${spec.fnName}@${spec.importModule}`); + : spec.durationCustomType !== undefined + ? spec.durationCustomType.fnConstName + : imp(`${spec.fnName}@${spec.importModule}`); const optsArg = spec.fnOptions && Object.keys(spec.fnOptions).length > 0 ? `, ${JSON.stringify(spec.fnOptions)}` @@ -164,7 +172,8 @@ export function renderExistingViewDecl( const { viewFn, core: viewModule } = dialectModule(opts.dialect); const viewSym = imp(`${viewFn}@${viewModule}`); const enumIntTypes = new Map(); - const viewColumnLines = fields.map((f) => viewColumnLine(f, opts, enumIntTypes)); + const usesDuration = new Set(); + const viewColumnLines = fields.map((f) => viewColumnLine(f, opts, enumIntTypes, usesDuration)); const viewNameExpr = typeof viewName === "string" ? code`${JSON.stringify(viewName)}` : viewName; // @schema — a view lands in a schema exactly as a table does, and migrate qualifies the @@ -188,6 +197,9 @@ export function renderExistingViewDecl( .filter((t) => alreadyDeclared === undefined || !alreadyDeclared.has(t.fnConstName)) .sort((a, b) => a.fnConstName.localeCompare(b.fnConstName)) .map((t) => renderEnumIntCustomType(t, viewModule)); + if (usesDuration.has(DURATION_COLUMN_FN) && (alreadyDeclared === undefined || !alreadyDeclared.has(DURATION_COLUMN_FN))) { + enumIntBlocks.unshift(renderDurationCustomType(opts.dialect, viewModule)); + } const viewBlock = code` // View declaration — Drizzle uses this for typed SELECT queries. diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts index ea4945feae..1edf2ab40b 100644 --- a/examples/showcase/codegen/templates/zod-validators.ts +++ b/examples/showcase/codegen/templates/zod-validators.ts @@ -17,7 +17,7 @@ import { FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DECIMAL, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_UUID, - FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, + FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, FIELD_SUBTYPE_DURATION, VALIDATOR_SUBTYPE_REQUIRED, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX, VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_ARRAY, IDENTITY_ATTR_FIELDS, IDENTITY_ATTR_GENERATION, @@ -45,6 +45,7 @@ import { } from "./date-time-regex.js"; import { renderDocsFor } from "./jsdoc.js"; import { DECIMAL_WRITE_HELPER_DECL, zodDecimalWriteExpr } from "./decimal-wire-helper.js"; +import { DURATION_WRITE_HELPER_DECL, ZOD_DURATION_EXPR, ZOD_DURATION_WRITE_EXPR } from "./duration-wire-helper.js"; import { sharedEnumForField } from "@metaobjectsdev/codegen-ts/engine"; import { sharedEnumImportSpecifier } from "@metaobjectsdev/codegen-ts/engine"; import { sharedEnumZodConstName } from "./enums-file.js"; @@ -83,6 +84,13 @@ function decimalHelperSince(since: number): string { return decimalWriteUses > since ? `${DECIMAL_WRITE_HELPER_DECL}\n\n` : ""; } +// The same device for the duration write rule (duration-wire-helper.ts). +let durationWriteUses = 0; + +function durationHelperSince(since: number): string { + return durationWriteUses > since ? `${DURATION_WRITE_HELPER_DECL}\n\n` : ""; +} + /** True when this object declares at least one @autoSet timestamp field * (onCreate or onUpdate). Drives whether codegen emits the #203 @@ -269,6 +277,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co const z = imp("z@zod"); const utcUsesBefore = utcTimestampUses; const decimalUsesBefore = decimalWriteUses; + const durationUsesBefore = durationWriteUses; const autoGenPkFields = autoGenPkFieldNames(obj); const assignedPkFields = assignedPkFieldNames(obj); const tphPin = tphDiscriminatorPin(obj); @@ -320,7 +329,7 @@ export function renderInsertSchemaOnly(obj: MetaObject, ctx?: RenderContext): Co const docsPrefix = docs ? `${docs}\n` : ""; return code` -${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ +${utcTimestampHelperSince(utcUsesBefore)}${decimalHelperSince(decimalUsesBefore)}${durationHelperSince(durationUsesBefore)}${docsPrefix}export const ${insertSchemaName} = ${z}.object({ ${joinCode(insertFieldLines, { on: ",\n" })} }); `; @@ -429,6 +438,7 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code const z = imp("z@zod"); const utcUsesBefore = utcTimestampUses; const decimalUsesBefore = decimalWriteUses; + const durationUsesBefore = durationWriteUses; const autoGenPkFields = autoGenPkFieldNames(obj); const pkFields = primaryKeyFieldNames(obj); const assignedPkFields = assignedPkFieldNames(obj); @@ -552,7 +562,7 @@ export type ${objName}CreatePreserving = ${z}.inputH][M][[.]S]`: hours are never folded into days, + zero components are left out, zero is `PT0S`, there are at most six fractional digits (the + precision of a Postgres `interval`; more are truncated toward zero, never rounded), and a + negative duration has one leading `-`. A day (`D`) is exactly 24 hours. The magnitude is at + most 256204778 hours (about 29,000 years), the largest whole hour a .NET `TimeSpan` holds, + so a value one port accepts every port can read; one microsecond more is refused. +- **`refused`**: input that is not a duration. Years, months and weeks are refused because a + calendar span has no fixed length. So are lowercase designators, fractional hours or minutes, + a comma decimal separator, per-component signs, out-of-order components and whitespace. +- **`postgres`**: the text a Postgres `interval` column returns under the default + `IntervalStyle` (`postgres`), and its canonical form. A port reading through a driver that + hands back a native value (Npgsql `TimeSpan`, a JDBC `PGInterval`) checks the same rule + against that value. +- **`postgresRefused`**: an interval with a year or month part is not a duration; reading one + is an error, never a guess at the length of a month. So is an interval past the 256204778-hour + bound. +- **`postgresText`**: a canonical duration and its Postgres interval spelling, `[-]HH:MM:SS[.f]` + with unbounded hours and no day part. Postgres refuses an ISO-8601 duration with a leading sign + (`-PT1M30S` is "invalid input syntax for type interval"), so a port that binds a duration to + Postgres as TEXT uses this spelling, and so does `meta migrate` for a declared `@default`. An + interval written this way is returned in exactly this spelling, so a default never drifts and a + value reads back as it was written. A port whose driver binds a native type (Npgsql `TimeSpan`, + a JDBC `PGInterval`, a Python `timedelta`) does not need it. diff --git a/fixtures/duration-wire/vectors.json b/fixtures/duration-wire/vectors.json new file mode 100644 index 0000000000..ef20e238e4 --- /dev/null +++ b/fixtures/duration-wire/vectors.json @@ -0,0 +1,87 @@ +{ + "$comment": "The field.duration wire rule. Each port's production duration helper must pass every vector; see README.md.", + "parse": [ + { "in": "PT1H30M", "out": "PT1H30M" }, + { "in": "PT90M", "out": "PT1H30M" }, + { "in": "PT5400S", "out": "PT1H30M" }, + { "in": "P1D", "out": "PT24H" }, + { "in": "P1DT2H", "out": "PT26H" }, + { "in": "P10DT0.5S", "out": "PT240H0.5S" }, + { "in": "PT1.5S", "out": "PT1.5S" }, + { "in": "PT0.000001S", "out": "PT0.000001S" }, + { "in": "PT1.123456789S", "out": "PT1.123456S" }, + { "in": "PT1.100S", "out": "PT1.1S" }, + { "in": "PT1H5S", "out": "PT1H5S" }, + { "in": "PT0S", "out": "PT0S" }, + { "in": "P0D", "out": "PT0S" }, + { "in": "-PT0S", "out": "PT0S" }, + { "in": "+PT2M", "out": "PT2M" }, + { "in": "-PT90S", "out": "-PT1M30S" }, + { "in": "-P1DT1H", "out": "-PT25H" }, + { "in": "PT0.0000001S", "out": "PT0S" }, + { "in": "PT876000H", "out": "PT876000H" }, + { "in": "PT256204778H", "out": "PT256204778H" }, + { "in": "-P10675199DT2H", "out": "-PT256204778H" } + ], + "refused": [ + "", + "P", + "PT", + "P1DT", + "P1Y", + "P1M", + "P1W", + "P1Y2M3D", + "pt1h", + "PT1.5H", + "PT1,5S", + "PT1.S", + "PT.5S", + "PT1.1234567890S", + "1:30:00", + "PT1H 30M", + " PT1H", + "PT-1H", + "--PT1H", + "PT1M1H", + "PT256204778H0.000001S", + "PT256204779H", + "P10675200D", + "-PT256204779H" + ], + "postgres": [ + { "in": "01:30:00", "out": "PT1H30M" }, + { "in": "00:00:00", "out": "PT0S" }, + { "in": "00:00:01.5", "out": "PT1.5S" }, + { "in": "00:00:00.000001", "out": "PT0.000001S" }, + { "in": "-00:01:30", "out": "-PT1M30S" }, + { "in": "26:00:00", "out": "PT26H" }, + { "in": "1 day", "out": "PT24H" }, + { "in": "1 day 02:00:00", "out": "PT26H" }, + { "in": "3 days", "out": "PT72H" }, + { "in": "-1 days", "out": "-PT24H" }, + { "in": "-1 days +02:00:00", "out": "-PT22H" }, + { "in": "1 day -01:00:00", "out": "PT23H" }, + { "in": "876000:00:00", "out": "PT876000H" }, + { "in": "256204778:00:00", "out": "PT256204778H" } + ], + "postgresRefused": [ + "1 year", + "2 mons", + "1 year 2 mons 3 days 04:05:06", + "1 mon 00:00:01", + "abc", + "256204779:00:00", + "10675200 days" + ], + "postgresText": [ + { "in": "PT1H30M", "out": "01:30:00" }, + { "in": "PT0S", "out": "00:00:00" }, + { "in": "PT1.5S", "out": "00:00:01.5" }, + { "in": "PT0.000001S", "out": "00:00:00.000001" }, + { "in": "-PT1M30S", "out": "-00:01:30" }, + { "in": "PT26H", "out": "26:00:00" }, + { "in": "-PT26H0.5S", "out": "-26:00:00.5" }, + { "in": "PT876000H", "out": "876000:00:00" } + ] +} diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 46ff01d311..7292ec4dc0 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -34,6 +34,7 @@ children and the cardinality of that subtype. Documentation attributes | `field.date` | Calendar date (no time-of-day). Binds to the native date/temporal type; DB column is DATE. | [types/field.md#fielddate](types/field.md#fielddate) | | `field.decimal` | Precision-exact decimal (use @precision/@scale). Native TS binding is string (lossless); DB column is NUMERIC(p,s); the wire form is a string. Classified DATA_TYPE_STRING so an exact decimal is never silently rounded through a double. | [types/field.md#fielddecimal](types/field.md#fielddecimal) | | `field.double` | Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/number type; DB column is DOUBLE PRECISION. Not for money — use field.currency or field.decimal. | [types/field.md#fielddouble](types/field.md#fielddouble) | +| `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. | [types/field.md#fieldduration](types/field.md#fieldduration) | | `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. | [types/field.md#fieldenum](types/field.md#fieldenum) | | `field.float` | Single-precision floating point. Binds to the native double/number type (TS has no distinct float); DB column is REAL. Not for money. | [types/field.md#fieldfloat](types/field.md#fieldfloat) | | `field.inet` | An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IPv4-or-IPv6 literal validator (a Zod regex union in TS — z.string().ip() was removed in Zod 4 — native IP-type parsing in the other ports); add @lenient to bind a plain string with no validator. v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4\|ipv6 value-constraint. | [types/field.md#fieldinet](types/field.md#fieldinet) | diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index a3d721d3c1..460e8d0c3c 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -13,7 +13,7 @@ provider owns. This is the ownership lens over the same vocabulary Core metaobjects metamodel types and subtypes. -**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.currency` +**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.currency` **Contributes attributes:** @@ -65,6 +65,7 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `field.date`: `@autoSet`, `@column`, `@db.indexed`, `@dbColumnType` - `field.decimal`: `@column`, `@db.indexed`, `@dbColumnType` - `field.double`: `@column`, `@db.indexed`, `@dbColumnType` +- `field.duration`: `@column`, `@db.indexed`, `@dbColumnType` - `field.enum`: `@column`, `@constraintName`, `@db.indexed`, `@dbColumnType` - `field.float`: `@column`, `@db.indexed`, `@dbColumnType` - `field.inet`: `@column`, `@db.indexed`, `@dbColumnType` @@ -108,6 +109,7 @@ Prompt / AI + serialization domain — @xmlText / @example / @instruction field - `field.date`: `@example`, `@instruction`, `@xmlText` - `field.decimal`: `@example`, `@instruction`, `@xmlText` - `field.double`: `@example`, `@instruction`, `@xmlText` +- `field.duration`: `@example`, `@instruction`, `@xmlText` - `field.enum`: `@coerceDefault`, `@enumAlias`, `@enumDoc`, `@example`, `@instruction`, `@normalize`, `@xmlText` - `field.float`: `@example`, `@instruction`, `@xmlText` - `field.inet`: `@example`, `@instruction`, `@xmlText` @@ -134,6 +136,7 @@ UI/query-surface domain — @filterable / @sortable / @sortableDefaultOrder fiel - `field.date`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` - `field.decimal`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` - `field.double`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` +- `field.duration`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` - `field.enum`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` - `field.float`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` - `field.inet`: `@filterable`, `@formExclude`, `@sortable`, `@sortableDefaultOrder` diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index a6181d7fde..6145b3aae4 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -214,6 +214,39 @@ Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/nu - `validator.*` — 0..* - `view.*` — 0..* +### field.duration + +A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. + +**Owning provider:** metaobjects-core-types + +**When to use:** A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span ("every 3 months") is not a duration: model it as an int and a unit. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | +| `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | +| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | +| `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | +| `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | +| `@formExclude` | boolean | no | | | metaobjects-ui | When true, the field is omitted from generated forms, and the generated create, PATCH and PUT routes ignore a value sent for it (reads of it are unchanged); inert on fields for which no form is generated (e.g. projection/derived fields). | +| `@instruction` | string | no | | | metaobjects-prompt | FR-010: a short instruction for this field, shown in the generated output-format prompt fragment. | +| `@mutability` | string | no | | `readWrite`, `writeOnce`, `readOnly` | metaobjects-core-types | FR-037 R1: who may write this field, and when. 'readWrite' (the default when absent) — the caller may set it on create and change it on update. 'writeOnce' — the caller sets it on create; it is excluded from the update shape thereafter, so a value presented on PATCH is ignored rather than rejected. 'readOnly' — nobody writes it: codegen emits no setter / writable property, the persistence layer skips the column on INSERT/UPDATE, and Zod/Pydantic/class-validator schemas omit it from input variants; the value is populated by the database (computed column, default expression, trigger), by replication, or by another external owner. The three are mutually exclusive modes of ONE axis — who may write, and when — so the illegal pair is unrepresentable and inheritance has a total order: a subtype may TIGHTEN an inherited mode (readWrite < writeOnce < readOnly) and never loosen it (ERR_MUTABILITY_DOWNGRADE). Pairing a non-readWrite mode with @autoSet is ERR_MUTABILITY_AUTOSET_CONFLICT: @autoSet already says the SERVER supplies the value, which is a different axis from who may write it. | +| `@required` | boolean | no | | | metaobjects-core-types | When true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction. | +| `@sortable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD sort allowlists. Inherits from @filterable by default; set false to opt out. | +| `@sortableDefaultOrder` | string | no | | `asc`, `desc` | metaobjects-ui | Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'. | +| `@unique` | boolean | no | | | metaobjects-core-types | When true, the field gets a column-level UNIQUE constraint. | +| `@xmlText` | boolean | no | | | metaobjects-prompt | When true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json. | + +**Allowed children** + +- `origin.*` — 0..* +- `validator.*` — 0..* +- `view.*` — 0..* + ### field.enum String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. diff --git a/fixtures/persistence-conformance/canonical/meta.fitness.json b/fixtures/persistence-conformance/canonical/meta.fitness.json index 12dbeb55ab..cd2aa0a35c 100644 --- a/fixtures/persistence-conformance/canonical/meta.fitness.json +++ b/fixtures/persistence-conformance/canonical/meta.fitness.json @@ -347,6 +347,7 @@ { "field.uri": { "name": "uriVal", "@required": true } }, { "field.inet": { "name": "inetVal", "@required": true } }, { "field.inet": { "name": "inet6Val", "@required": true } }, + { "field.duration": { "name": "durationVal" } }, { "field.object": { "name": "settings", "@objectRef": "Settings", "@storage": "jsonb" } }, { "field.object": { "name": "labels", "@objectRef": "Label", "@storage": "jsonb", "isArray": true } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "uuid" } }, diff --git a/fixtures/persistence-conformance/canonical/schema.mysql.sql b/fixtures/persistence-conformance/canonical/schema.mysql.sql index 8d2a314303..0aeada6a40 100644 --- a/fixtures/persistence-conformance/canonical/schema.mysql.sql +++ b/fixtures/persistence-conformance/canonical/schema.mysql.sql @@ -102,6 +102,7 @@ CREATE TABLE `all_types` ( `uriVal` VARCHAR(255) NOT NULL, `inetVal` VARCHAR(45) NOT NULL, `inet6Val` VARCHAR(45) NOT NULL, + `durationVal` VARCHAR(64), `settings` JSON, `labels` JSON ); diff --git a/fixtures/persistence-conformance/canonical/schema.postgres.sql b/fixtures/persistence-conformance/canonical/schema.postgres.sql index 3631a660ad..a5a9bd9317 100644 --- a/fixtures/persistence-conformance/canonical/schema.postgres.sql +++ b/fixtures/persistence-conformance/canonical/schema.postgres.sql @@ -132,6 +132,7 @@ CREATE TABLE "all_types" ( "uriVal" TEXT NOT NULL, "inetVal" INET NOT NULL, "inet6Val" INET NOT NULL, + "durationVal" INTERVAL, "settings" JSONB, "labels" JSONB, CONSTRAINT "all_types_pkey" PRIMARY KEY ("id"), diff --git a/fixtures/persistence-conformance/canonical/schema.sqlite.sql b/fixtures/persistence-conformance/canonical/schema.sqlite.sql index c7cc934302..2a1615c334 100644 --- a/fixtures/persistence-conformance/canonical/schema.sqlite.sql +++ b/fixtures/persistence-conformance/canonical/schema.sqlite.sql @@ -133,6 +133,7 @@ CREATE TABLE "all_types" ( "uriVal" TEXT NOT NULL, "inetVal" TEXT NOT NULL, "inet6Val" TEXT NOT NULL, + "durationVal" TEXT, "settings" TEXT, "labels" TEXT, CONSTRAINT "all_types_enumVal_chk" CHECK ("enumVal" IN ('LOW', 'MEDIUM', 'HIGH')), diff --git a/fixtures/persistence-conformance/normalization.md b/fixtures/persistence-conformance/normalization.md index ee9fadf4ee..e467925fb3 100644 --- a/fixtures/persistence-conformance/normalization.md +++ b/fixtures/persistence-conformance/normalization.md @@ -38,6 +38,7 @@ byte equality check. | `TIMESTAMP` | string `"YYYY-MM-DDTHH:MM:SS[.fff]"` | `"2026-05-25T10:30:00"` (no Z) | | `TIMESTAMPTZ` | string `"YYYY-MM-DDTHH:MM:SS[.fff]Z"` | `"2026-05-25T14:30:00Z"` (UTC always) | | `UUID` | string (lowercase canonical) | `"550e8400-e29b-41d4-a716-446655440000"` | +| `INTERVAL` (`field.duration`) | string (canonical ISO-8601 duration, [`fixtures/duration-wire`](../duration-wire/)) | `"PT24H0.5S"` | | `JSON`, `JSONB` | re-serialized with **sorted keys** | `{"a": 1, "b": 2}` not `{"b": 2, "a": 1}` | | `BYTEA` | base64 string | `"aGVsbG8="` | | `NULL` | JSON `null` | | diff --git a/fixtures/persistence-conformance/queries/roundtrip-all-types.yaml b/fixtures/persistence-conformance/queries/roundtrip-all-types.yaml index 93ff84047d..31ccf6024d 100644 --- a/fixtures/persistence-conformance/queries/roundtrip-all-types.yaml +++ b/fixtures/persistence-conformance/queries/roundtrip-all-types.yaml @@ -15,7 +15,7 @@ description: | string / int / long / double / float / decimal / boolean / date / time / timestamp / timestamp(tz) / currency / enum / uuid / - uri / inet (IPv4 + IPv6) / object(@objectRef, jsonb storage) + uri / inet (IPv4 + IPv6) / duration / object(@objectRef, jsonb storage) Tricky wire cases asserted here: - decimal: exact, canonical (no trailing zeros) → "123.456". @@ -26,6 +26,11 @@ description: | precision loss — a port routing these through a JS number / 32-bit int / double corrupts the low bits and fails. - uuid: written upper-case, reads back lowercase-canonical. + - duration: written in an accepted ISO-8601 form, read back canonical + (fixtures/duration-wire): a day folds into hours (`P1DT0.5S` -> `PT24H0.5S`) + and a negative span carries one leading sign (`-PT90S` -> `-PT1M30S`). + Postgres refuses a signed ISO duration as interval input, so this also + proves each port binds the value in a form Postgres reads. - id (uuid PK): NOT supplied on insert; gen_random_uuid() fills it, the runtime returns it, and the read-back is by that generated PK — so a server-generated PK is exercised on the write path too. @@ -77,6 +82,7 @@ queries: uriVal: "https://example.com/a/b?q=1" inetVal: "192.168.1.1" inet6Val: "2001:db8::1" + durationVal: "P1DT0.5S" settings: { theme: "dark", notify: true, retries: 3 } # array-of-VO stored as JSONB (field.object @isArray @storage:jsonb). Element # order is preserved; each element's keys are sorted on read (like settings). @@ -102,6 +108,7 @@ queries: uriVal: "https://example.com/a/b?q=1" inetVal: "192.168.1.1" inet6Val: "2001:db8::1" + durationVal: "PT24H0.5S" settings: { notify: true, retries: 3, theme: "dark" } labels: - { key: "alpha", weight: 10 } @@ -129,6 +136,7 @@ queries: uriVal: "urn:isbn:0451450523" inetVal: "10.0.0.5" inet6Val: "fe80::1" + durationVal: "-PT90S" settings: { theme: "light", notify: false, retries: 0 } # empty array-of-VO: an empty JSON array must round-trip as [] (distinct from null). labels: [] @@ -151,6 +159,7 @@ queries: uriVal: "urn:isbn:0451450523" inetVal: "10.0.0.5" inet6Val: "fe80::1" + durationVal: "-PT1M30S" settings: { notify: false, retries: 0, theme: "light" } labels: [] @@ -190,6 +199,7 @@ queries: # Authored in the long (uncompressed) form; Postgres returns the canonical # compressed form, so the expected read-back is `2001:db8::8a2e:370:7334`. inet6Val: "2001:0db8:0000:0000:0000:8a2e:0370:7334" + durationVal: "PT876000H" settings: { theme: "dark", notify: true, retries: 9 } labels: - { key: "solo", weight: 99 } @@ -212,6 +222,7 @@ queries: uriVal: "https://example.org/path#frag" inetVal: "255.255.255.255" inet6Val: "2001:db8::8a2e:370:7334" + durationVal: "PT876000H" settings: { notify: true, retries: 9, theme: "dark" } labels: - { key: "solo", weight: 99 } diff --git a/fixtures/persistence-conformance/queries/update-delete-all-types.yaml b/fixtures/persistence-conformance/queries/update-delete-all-types.yaml index 35edbcfe3b..7eff2f9059 100644 --- a/fixtures/persistence-conformance/queries/update-delete-all-types.yaml +++ b/fixtures/persistence-conformance/queries/update-delete-all-types.yaml @@ -80,6 +80,7 @@ queries: uriVal: "https://example.com/after?x=1" inetVal: "192.168.10.20" inet6Val: "2001:db8::dead:beef" + durationVal: "PT2700S" settings: { theme: "dark", notify: true, retries: 7 } expect: id: "22222222-2222-4222-8222-222222222222" @@ -101,6 +102,7 @@ queries: uriVal: "https://example.com/after?x=1" inetVal: "192.168.10.20" inet6Val: "2001:db8::dead:beef" + durationVal: "PT45M" settings: { notify: true, retries: 7, theme: "dark" } # labels (array-of-VO jsonb) is neither seeded nor updated here → reads back null. labels: null @@ -130,6 +132,7 @@ queries: uriVal: "https://example.com/after?x=1" inetVal: "192.168.10.20" inet6Val: "2001:db8::dead:beef" + durationVal: "PT45M" settings: { notify: true, retries: 7, theme: "dark" } # labels (array-of-VO jsonb) is neither seeded nor updated here → reads back null. labels: null diff --git a/fixtures/registry-conformance/coverage-report.json b/fixtures/registry-conformance/coverage-report.json index cfc33e9c8c..ac4931549c 100644 --- a/fixtures/registry-conformance/coverage-report.json +++ b/fixtures/registry-conformance/coverage-report.json @@ -1,6 +1,6 @@ { - "registeredSubTypeCount": 65, - "exercisedSubTypeCount": 55, + "registeredSubTypeCount": 66, + "exercisedSubTypeCount": 58, "untestedSubTypes": [ "attr.boolean", "attr.class", @@ -9,9 +9,7 @@ "attr.filter", "attr.int", "attr.intMap", - "attr.long", - "validator.presentIff", - "validator.requiredWhen" + "attr.long" ], "untestedAttrsByExercisedSubType": [ { @@ -92,6 +90,24 @@ "xmlText" ] }, + { + "key": "field.duration", + "untestedAttrs": [ + "column", + "db.indexed", + "dbColumnType", + "default", + "example", + "filterable", + "formExclude", + "instruction", + "mutability", + "sortable", + "sortableDefaultOrder", + "unique", + "xmlText" + ] + }, { "key": "field.enum", "untestedAttrs": [ @@ -342,12 +358,24 @@ "since" ] }, + { + "key": "validator.presentIff", + "untestedAttrs": [ + "constraintName" + ] + }, { "key": "validator.regex", "untestedAttrs": [ "max", "min" ] + }, + { + "key": "validator.requiredWhen", + "untestedAttrs": [ + "constraintName" + ] } ] } diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 94c79b6d58..e81411218b 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1024,6 +1024,148 @@ } ] }, + { + "type": "field", + "subType": "duration", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit.", + "attrs": [ + { + "name": "column", + "valueType": "string", + "isArray": false, + "required": false, + "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." + }, + { + "name": "db.indexed", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." + }, + { + "name": "dbColumnType", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "uuid", + "jsonb" + ], + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + }, + { + "name": "default", + "valueType": null, + "isArray": false, + "required": false, + "description": "Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue()." + }, + { + "name": "example", + "valueType": "string", + "isArray": false, + "required": false, + "description": "FR-010: an example value for this field, shown in the generated output-format prompt fragment." + }, + { + "name": "filterable", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer)." + }, + { + "name": "formExclude", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, the field is omitted from generated forms, and the generated create, PATCH and PUT routes ignore a value sent for it (reads of it are unchanged); inert on fields for which no form is generated (e.g. projection/derived fields)." + }, + { + "name": "instruction", + "valueType": "string", + "isArray": false, + "required": false, + "description": "FR-010: a short instruction for this field, shown in the generated output-format prompt fragment." + }, + { + "name": "mutability", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "readWrite", + "writeOnce", + "readOnly" + ], + "description": "FR-037 R1: who may write this field, and when. 'readWrite' (the default when absent) — the caller may set it on create and change it on update. 'writeOnce' — the caller sets it on create; it is excluded from the update shape thereafter, so a value presented on PATCH is ignored rather than rejected. 'readOnly' — nobody writes it: codegen emits no setter / writable property, the persistence layer skips the column on INSERT/UPDATE, and Zod/Pydantic/class-validator schemas omit it from input variants; the value is populated by the database (computed column, default expression, trigger), by replication, or by another external owner. The three are mutually exclusive modes of ONE axis — who may write, and when — so the illegal pair is unrepresentable and inheritance has a total order: a subtype may TIGHTEN an inherited mode (readWrite < writeOnce < readOnly) and never loosen it (ERR_MUTABILITY_DOWNGRADE). Pairing a non-readWrite mode with @autoSet is ERR_MUTABILITY_AUTOSET_CONFLICT: @autoSet already says the SERVER supplies the value, which is a different axis from who may write it." + }, + { + "name": "required", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction." + }, + { + "name": "sortable", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, the field is exposed in generated CRUD sort allowlists. Inherits from @filterable by default; set false to opt out." + }, + { + "name": "sortableDefaultOrder", + "valueType": "string", + "isArray": false, + "required": false, + "allowedValues": [ + "asc", + "desc" + ], + "description": "Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'." + }, + { + "name": "unique", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, the field gets a column-level UNIQUE constraint." + }, + { + "name": "xmlText", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "When true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json." + } + ], + "children": [ + { + "childType": "origin", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + }, + { + "childType": "validator", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + }, + { + "childType": "view", + "childSubType": "*", + "childName": "*", + "min": 0, + "max": null + } + ] + }, { "type": "field", "subType": "enum", diff --git a/fixtures/validation-conformance/README.md b/fixtures/validation-conformance/README.md index 0bb31d696b..72f93ff2c2 100644 --- a/fixtures/validation-conformance/README.md +++ b/fixtures/validation-conformance/README.md @@ -152,6 +152,17 @@ So the rule is: Python fuses both (Pydantic construct-or-`ValidationError`); the Java/Kotlin/C# runners wrap the bind step so a native-parse failure maps to `valid=false`. +## `field.duration` accepted form + +`Account.holdFor` (`field.duration`, OPTIONAL) pins the duration accept/reject verdicts. ACCEPT an +ISO-8601 duration of days, hours, minutes and seconds (`PT1H30M`, `P1DT2H`, `-PT30S`, `PT0.5S`, +`PT0S`). REJECT a calendar span (`P1M`, `P1Y`, `P2W`), a clock form (`1:30:00`), a fractional hour +(`PT1.5H`), lowercase designators, a `T` with no component (`PT`), and a span past the +256204778-hour bound (`PT256204779H`). The full rule, with the +canonical form every port writes, is in [`fixtures/duration-wire/`](../duration-wire/); a port +that binds a native duration type (`TimeSpan`, `java.time.Duration`, `timedelta`) still refuses +what that type's own parser would accept beyond this form. + ## Run-time runners (TypeScript and Python) Two ports also ship a metadata-driven **run-time** runner that needs no generated code: diff --git a/fixtures/validation-conformance/cases.json b/fixtures/validation-conformance/cases.json index 2f65ea2514..a09f1dacba 100644 --- a/fixtures/validation-conformance/cases.json +++ b/fixtures/validation-conformance/cases.json @@ -109,6 +109,19 @@ { "name": "lenient-inet-accepts-valid", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "reportedIp": "10.0.0.1" }, "expectValid": true }, { "name": "assigned-pk-present", "entity": "Ledger", "payload": { "code": "L-1", "label": "ok" }, "expectValid": true }, - { "name": "assigned-pk-missing", "entity": "Ledger", "payload": { "label": "ok" }, "expectValid": false } + { "name": "assigned-pk-missing", "entity": "Ledger", "payload": { "label": "ok" }, "expectValid": false }, + { "name": "duration-accept-hours-minutes", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT1H30M" }, "expectValid": true }, + { "name": "duration-accept-days", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P1DT2H" }, "expectValid": true }, + { "name": "duration-accept-negative", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "-PT30S" }, "expectValid": true }, + { "name": "duration-accept-fraction", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT0.5S" }, "expectValid": true }, + { "name": "duration-accept-zero", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT0S" }, "expectValid": true }, + { "name": "duration-reject-months", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P1M" }, "expectValid": false }, + { "name": "duration-reject-years", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P1Y" }, "expectValid": false }, + { "name": "duration-reject-weeks", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P2W" }, "expectValid": false }, + { "name": "duration-reject-clock", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "1:30:00" }, "expectValid": false }, + { "name": "duration-reject-fractional-hours", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT1.5H" }, "expectValid": false }, + { "name": "duration-reject-lowercase", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "pt1h" }, "expectValid": false }, + { "name": "duration-reject-empty-time", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT" }, "expectValid": false }, + { "name": "duration-reject-too-long", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT256204779H" }, "expectValid": false } ] } diff --git a/fixtures/validation-conformance/meta.json b/fixtures/validation-conformance/meta.json index a8a4daf79d..3f696a5c98 100644 --- a/fixtures/validation-conformance/meta.json +++ b/fixtures/validation-conformance/meta.json @@ -28,6 +28,7 @@ { "field.inet": { "name": "sourceIp" } }, { "field.uri": { "name": "citationUrl", "@lenient": true } }, { "field.inet": { "name": "reportedIp", "@lenient": true } }, + { "field.duration": { "name": "holdFor" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] }}, diff --git a/fixtures/validation-conformance/runtime-errors.json b/fixtures/validation-conformance/runtime-errors.json index 1f70ea54ca..5aefbc0c5c 100644 --- a/fixtures/validation-conformance/runtime-errors.json +++ b/fixtures/validation-conformance/runtime-errors.json @@ -207,6 +207,78 @@ "rule": "required", "message": "'code' is required" } + ], + "duration-reject-months": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "P1M" + } + ], + "duration-reject-years": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "P1Y" + } + ], + "duration-reject-weeks": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "P2W" + } + ], + "duration-reject-clock": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "1:30:00" + } + ], + "duration-reject-fractional-hours": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "PT1.5H" + } + ], + "duration-reject-lowercase": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "pt1h" + } + ], + "duration-reject-empty-time": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "PT" + } + ], + "duration-reject-too-long": [ + { + "field": "holdFor", + "rule": "format", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "expected": "duration", + "received": "PT256204779H" + } ] } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs new file mode 100644 index 0000000000..c9550abcc9 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs @@ -0,0 +1,288 @@ +// field.duration — the C# half of the duration wire rule, gated against the shared vectors in +// fixtures/duration-wire/vectors.json. No database: the production wire helper +// (Runtime/DurationWire.cs, the SAME text the entity generator emits into every generated project) +// runs every vector, and the emitted text is proven identical to it. The Postgres vectors (what an +// interval column reads back as, through Npgsql's native TimeSpan) are gated against a live +// database in MetaObjects.IntegrationTests/DurationPostgresTests. + +using System.Reflection; +using System.Text.Json; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen.Generators; +using MetaObjects.Codegen.Runtime; +using MetaObjects.Core.Query; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; +using static MetaObjects.Core.Field.FieldConstants; + +namespace MetaObjects.Codegen.Tests; + +public class DurationWireTests +{ + private static JsonElement Vectors() => + JsonDocument.Parse(File.ReadAllText(Path.Combine( + CorpusPaths.RepoRoot(), "fixtures", "duration-wire", "vectors.json"))).RootElement; + + public static TheoryData ParseVectors() + { + var data = new TheoryData(); + foreach (var v in Vectors().GetProperty("parse").EnumerateArray()) + data.Add(v.GetProperty("in").GetString()!, v.GetProperty("out").GetString()!); + return data; + } + + public static TheoryData RefusedVectors() + { + var data = new TheoryData(); + foreach (var v in Vectors().GetProperty("refused").EnumerateArray()) data.Add(v.GetString()!); + return data; + } + + public sealed class Holder + { + [DurationWire.Iso] public TimeSpan Span { get; set; } + [DurationWire.Iso] public TimeSpan? Maybe { get; set; } + [DurationWire.Iso] public IList Many { get; set; } = new List(); + } + + [Theory, MemberData(nameof(ParseVectors))] + public void An_accepted_duration_parses_to_its_canonical_form(string input, string canonical) + { + Assert.True(DurationWire.TryParse(input, out var span), $"'{input}' was refused"); + Assert.Equal(canonical, DurationWire.Format(span)); + Assert.Equal(canonical, DurationWire.Canonical(input)); + // The canonical form is a fixed point. + Assert.Equal(canonical, DurationWire.Format(DurationWire.Parse(canonical))); + } + + [Theory, MemberData(nameof(ParseVectors))] + public void A_property_reads_the_accepted_form_and_writes_the_canonical_one(string input, string canonical) + { + var h = JsonSerializer.Deserialize($"{{\"Span\":\"{input}\",\"Maybe\":\"{input}\",\"Many\":[\"{input}\"]}}")!; + Assert.Equal($"{{\"Span\":\"{canonical}\",\"Maybe\":\"{canonical}\",\"Many\":[\"{canonical}\"]}}", JsonSerializer.Serialize(h)); + } + + [Theory, MemberData(nameof(RefusedVectors))] + public void A_refused_value_is_not_a_duration(string input) + { + Assert.False(DurationWire.TryParse(input, out _)); + Assert.Null(DurationWire.Canonical(input)); + Assert.Throws(() => DurationWire.Parse(input)); + var json = JsonSerializer.Serialize(input); + Assert.ThrowsAny(() => JsonSerializer.Deserialize($"{{\"Span\":{json}}}")); + Assert.ThrowsAny(() => JsonSerializer.Deserialize($"{{\"Maybe\":{json}}}")); + Assert.ThrowsAny(() => JsonSerializer.Deserialize($"{{\"Many\":[{json}]}}")); + } + + [Theory] + [InlineData("1")] // a number is not a duration + [InlineData("true")] + [InlineData("{}")] + [InlineData("\"01:30:00\"")] // System.Text.Json's own TimeSpan form + [InlineData("\"PT99999999999999999999H\"")] // past what a TimeSpan holds: refused, not wrapped + public void A_non_duration_token_is_refused(string json) => + Assert.ThrowsAny(() => JsonSerializer.Deserialize($"{{\"Span\":{json}}}")); + + [Fact] + public void Null_crosses_as_null_and_a_tick_below_a_microsecond_truncates_toward_zero() + { + Assert.Null(JsonSerializer.Deserialize("{\"Maybe\":null}")!.Maybe); + Assert.Contains("\"Maybe\":null", JsonSerializer.Serialize(new Holder())); + Assert.Equal("PT0S", DurationWire.Format(TimeSpan.FromTicks(9))); + Assert.Equal("PT0S", DurationWire.Format(TimeSpan.FromTicks(-9))); + Assert.Equal("PT0.000001S", DurationWire.Format(TimeSpan.FromTicks(19))); + Assert.Equal("-PT0.000001S", DurationWire.Format(TimeSpan.FromTicks(-19))); + Assert.Equal("-PT1M30S", DurationWire.Format(TimeSpan.FromSeconds(-90))); + } + + [Fact] + public void The_magnitude_is_bounded_at_256204778_hours_exactly_on_parse_and_on_write() + { + var max = TimeSpan.FromHours(DurationWire.MaxHours); + Assert.Equal("PT256204778H", DurationWire.Format(max)); + Assert.Equal("-PT256204778H", DurationWire.Format(-max)); + // A tick below a microsecond over the bound truncates back onto it; one microsecond over is refused. + Assert.Equal("PT256204778H", DurationWire.Format(max + TimeSpan.FromTicks(9))); + Assert.Throws(() => DurationWire.Format(max + TimeSpan.FromTicks(10))); + Assert.Throws(() => DurationWire.Format(-max - TimeSpan.FromTicks(10))); + Assert.Throws(() => DurationWire.Format(TimeSpan.MaxValue)); + Assert.Throws(() => DurationWire.Format(TimeSpan.MinValue)); + Assert.False(DurationWire.InRange(TimeSpan.MaxValue)); + Assert.True(DurationWire.InRange(-max)); + Assert.True(DurationWire.TryParse("PT256204777H59M59.999999S", out _)); + Assert.False(DurationWire.TryParse("PT256204778H0.000001S", out _)); + // A value past the bound is refused by the property converter on the way out, too. + Assert.ThrowsAny(() => JsonSerializer.Serialize(new Holder { Span = TimeSpan.MaxValue })); + } + + // ---- filter operands ---------------------------------------------------------------------- + + public sealed class Row { public TimeSpan Wait { get; set; } public TimeSpan? Grace { get; set; } } + + private static FilterParseResult Check(string field, string op, object value) => + EfCoreFilterDispatch.Validate(FilterParseResult.Ok([new FilterPredicate(field, op, value)])); + + [Theory] + [InlineData("wait", "eq", "P1M")] + [InlineData("wait", "eq", "01:30:00")] + [InlineData("grace", "ne", "pt1h")] + [InlineData("grace", "eq", "")] + public void A_malformed_duration_operand_is_invalid_filter_value_naming_the_field(string field, string op, string operand) + { + var r = Check(field, op, operand); + Assert.Equal("invalid_filter_value", r.ErrorEnvelope); + Assert.Equal(field, r.Field); + } + + [Fact] + public void A_good_duration_operand_passes_and_an_in_list_is_checked_element_wise() + { + Assert.Null(Check("wait", "eq", "PT90M").ErrorEnvelope); + Assert.Null(Check("grace", "ne", "-P1DT0.5S").ErrorEnvelope); + Assert.Null(Check("wait", "in", new List { "PT1H", "P2D" }).ErrorEnvelope); + Assert.Equal("invalid_filter_value", Check("wait", "in", new List { "PT1H", "P1Y" }).ErrorEnvelope); + } + + [Fact] + public void A_duration_filters_on_the_identity_band() + { + Assert.Equal(["eq", "ne", "in", "isNull"], QueryConstants.OpsForSubType(FIELD_SUBTYPE_DURATION)); + } + + // ---- generated code ------------------------------------------------------------------------- + + private const string Model = """ + { "metadata.root": { "package": "acme::ops", "children": [ + { "object.value": { "name": "Window", "children": [ + { "field.duration": { "name": "length", "@required": true } }, + { "field.duration": { "name": "slack" } }, + { "field.duration": { "name": "steps", "isArray": true } } + ]}}, + { "object.value": { "name": "Limits", "children": [ + { "field.duration": { "name": "cap" } }, + { "field.duration": { "name": "marks", "isArray": true } } + ]}}, + { "object.entity": { "name": "Timer", "children": [ + { "source.rdb": { "@table": "timers" } }, + { "field.long": { "name": "id" } }, + { "field.duration": { "name": "timeout", "@required": true, "@default": "PT90M" } }, + { "field.duration": { "name": "grace", "@filterable": true } }, + { "field.duration": { "name": "backoff", "isArray": true } }, + { "field.object": { "name": "window", "@objectRef": "Window", "@storage": "jsonb" } }, + { "field.object": { "name": "limits", "@objectRef": "Limits", "@storage": "flattened" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}} + ]}} + """; + + private static List Emit() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "duration-model.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = Path.Combine(Path.GetTempPath(), "unused-duration"), Namespace = "Acme.Ops" }, + }; + return new IGenerator[] { new EntityGenerator(), new DbContextGenerator(), new FilterAllowlistGenerator(), new RoutesGenerator() } + .SelectMany(g => g.Generate(ctx)).ToList(); + } + + private static Assembly Compile(IEnumerable files) + { + var trees = files.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)); + var comp = CSharpCompilation.Create("duration_" + Guid.NewGuid().ToString("N"), trees, + DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + using var ms = new MemoryStream(); + var emit = comp.Emit(ms); + Assert.True(emit.Success, string.Join("\n", emit.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error))); + return Assembly.Load(ms.ToArray()); + } + + [Fact] + public void The_emitted_helper_is_the_production_helper_with_only_the_namespace_changed() + { + var emitted = Emit().Single(f => f.Path == "DurationWire.g.cs"); + var production = File.ReadAllText(Path.Combine( + CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.Codegen", "Runtime", "DurationWire.cs")).Replace("\r\n", "\n"); + Assert.Equal(production.Replace("namespace MetaObjects.Codegen.Runtime;", "namespace Acme.Ops;"), emitted.Content.Replace("\r\n", "\n")); + } + + [Fact] + public void A_duration_is_a_TimeSpan_with_the_wire_converter_an_interval_on_Postgres_and_text_elsewhere() + { + var files = Emit(); + var timer = files.Single(f => f.Path == "Timer.g.cs").Content; + Assert.Contains(" [DurationWire.Iso]\n public TimeSpan Timeout { get; set; } = DurationWire.Parse(\"PT90M\");", timer.Replace("\r\n", "\n")); + Assert.Contains("public TimeSpan? Grace { get; set; }", timer); + Assert.Contains("public IList Backoff { get; set; } = new List();", timer); + Assert.DoesNotContain("using MetaObjects", timer); + + var window = files.Single(f => f.Path == "Window.g.cs").Content; + Assert.Contains("[DurationWire.Iso]", window); + + var ctx = files.Single(f => f.Path == "AppDbContext.g.cs").Content.Replace("\r\n", "\n"); + Assert.Contains( + " if (Database.ProviderName == \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + + " modelBuilder.Entity().Property(x => x.Timeout).HasColumnType(\"interval\");\n" + + " else\n" + + " modelBuilder.Entity().Property(x => x.Timeout).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + "v => global::Acme.Ops.DurationWire.Format(v), v => global::Acme.Ops.DurationWire.Parse(v)));", + ctx); + Assert.Contains( + " if (Database.ProviderName != \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + + " modelBuilder.Entity().PrimitiveCollection(x => x.Backoff).ElementType().HasConversion(", + ctx); + // A duration member of a jsonb value object is stored as its canonical string on every provider. + Assert.Contains("b.Property(p => p.Length).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(", ctx); + Assert.Contains("b.PrimitiveCollection(p => p.Steps).ElementType().HasConversion(", ctx); + // ...and a duration member of a FLATTENED value object takes the top-level column mapping: + // native on Postgres, the canonical-string converter elsewhere. + Assert.Contains( + " b.Property(p => p.Cap).HasColumnName(\"limits_cap\");\n" + + " if (Database.ProviderName != \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + + " b.Property(p => p.Cap).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + "v => global::Acme.Ops.DurationWire.Format(v), v => global::Acme.Ops.DurationWire.Parse(v)));", + ctx); + Assert.Contains( + " if (Database.ProviderName != \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + + " b.PrimitiveCollection(p => p.Marks).ElementType().HasConversion(", + ctx); + + var allowlist = files.Single(f => f.Path == "TimerFilterAllowlist.g.cs").Content; + Assert.Contains("[\"grace\"] = new(System.StringComparer.Ordinal) { \"eq\", \"ne\", \"in\", \"isNull\" },", allowlist); + + // The PATCH merge reads a duration through the wire helper, not System.Text.Json's own form. + var routes = files.Single(f => f.Path == "TimerRoutes.g.cs").Content; + Assert.Contains("if (clr == typeof(System.TimeSpan))", routes); + Assert.Contains("DurationWire.TryParseElement(prop.Value, out var __dur)", routes); + } + + [Fact] + public void The_generated_entity_compiles_and_crosses_json_in_the_canonical_form() + { + var asm = Compile(Emit()); + var timer = asm.GetType("Acme.Ops.Timer")!; + + var fresh = Activator.CreateInstance(timer)!; + Assert.Equal(TimeSpan.FromMinutes(90), timer.GetProperty("Timeout")!.GetValue(fresh)); // @default + + var row = JsonSerializer.Deserialize( + "{\"Id\":1,\"Timeout\":\"P1DT2H\",\"Grace\":\"-PT90S\",\"Backoff\":[\"PT1S\",\"PT0.5S\"],\"Window\":{\"length\":\"PT5400S\",\"steps\":[\"P1D\"]}}", + timer)!; + var json = JsonSerializer.Serialize(row, timer); + Assert.Contains("\"Timeout\":\"PT26H\"", json); + Assert.Contains("\"Grace\":\"-PT1M30S\"", json); + Assert.Contains("\"Backoff\":[\"PT1S\",\"PT0.5S\"]", json); + // A value object's members cross under their metadata (camelCase) names. + Assert.Contains("\"length\":\"PT1H30M\"", json); + Assert.Contains("\"slack\":null", json); + Assert.Contains("\"steps\":[\"PT24H\"]", json); + + Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Timeout\":\"01:30:00\"}", timer)); + Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Grace\":\"P1M\"}", timer)); + Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Backoff\":[\"P1W\"]}", timer)); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs index 2c3fe6fe11..de02d50045 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs @@ -35,9 +35,25 @@ public class ReportExportGeneratorTests ] } } """; - private static MetaRoot Load() + // The same shop with a field.duration dimension on the served report. + private const string DurationModel = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.entity": { "name": "Line", "children": [ + { "source.rdb": { "@table": "lines" } }, + { "field.long": { "name": "id", "@required": true } }, + { "field.duration": { "name": "wait" } }, + { "identity.primary": { "name": "id", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "wait", "@of": "Line.wait" } }, + { "measure.aggregate": { "name": "lines", "@agg": "count", "@of": "Line.id" } } + ] } }, + { "object.report": { "name": "WaitTotals", "@from": "Line", "@dimensions": ["wait"], "@measures": ["lines"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_wait_totals" } } ] } } + ] } } + """; + + private static MetaRoot Load(string model = Model) { - var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "meta.shop.json")]); + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "meta.shop.json")]); Assert.True(r.Errors.Count == 0, string.Join("\n", r.Errors.Select(e => e.Message))); return r.Root; } @@ -130,9 +146,9 @@ public static string Xml(object?[][] rows, string[] cols) } """; - private static MethodInfo[] Compile(ReportExportGenerator gen, string? decimals = null) + private static MethodInfo[] Compile(ReportExportGenerator gen, string? decimals = null, string model = Model) { - var root = Load(); + var root = Load(model); if (decimals == "string") root.WireFormat = new WireFormat(DecimalWireForm.String, NullMemberForm.Native); var writer = gen.Generate(Ctx(root)).Single(f => f.Path == "ReportExportWriter.g.cs").Content; var tpa = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator) @@ -150,6 +166,32 @@ private static MethodInfo[] Compile(ReportExportGenerator gen, string? decimals private static string Csv(MethodInfo[] h, object?[][] rows, params string[] cols) => (string)h[0].Invoke(null, [rows, cols, null])!; private static string Xml(MethodInfo[] h, object?[][] rows, params string[] cols) => (string)h[1].Invoke(null, [rows, cols])!; + private static string Writer(string model) => + new ReportExportGenerator().Generate(Ctx(Load(model))).Single(f => f.Path == "ReportExportWriter.g.cs").Content; + + // field.duration: the writer of a model with no duration column is the writer from before + // durations existed, byte for byte (the hash of that writer for this model, pinned). + [Fact] + public void The_writer_of_a_model_without_a_duration_column_is_unchanged() + { + var writer = Writer(Model); + Assert.DoesNotContain("TimeSpan ts", writer); + Assert.DoesNotContain("duration", writer, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("@DURATION", writer); + var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(writer.Replace("\r\n", "\n")))); + Assert.Equal("78913C645BB9D25C334F2285C210D0192510618A63C564AA7833C8AEA4A0B5AF", hash); + } + + [Fact] + public void A_duration_column_is_written_in_its_canonical_form_and_never_guarded() + { + Assert.Contains("case TimeSpan ts: return new(Duration(ts), false);", Writer(DurationModel)); + var h = Compile(new ReportExportGenerator(), model: DurationModel); + Assert.Equal("w\r\nPT26H\r\n-PT1M30S\r\nPT0.5S\r\nPT0S\r\n\r\n", + Csv(h, [[TimeSpan.FromHours(26)], [TimeSpan.FromSeconds(-90)], [TimeSpan.FromMilliseconds(500)], [TimeSpan.FromTicks(5)], [null]], "w")); + Assert.Contains("-PT1M30S", Xml(h, [[TimeSpan.FromSeconds(-90)]], "w")); + } + [Fact] public void Csv_quotes_ends_every_record_with_crlf_and_guards_text_cells_only() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs index b2724518e0..baed0b406b 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs @@ -48,7 +48,7 @@ public static IEnumerable Cases() [Fact] public void Discovers_all_validation_conformance_cases() { - Assert.Equal(42, Cases().Count()); + Assert.Equal(55, Cases().Count()); } [Theory] diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 5ef4e0f22a..c6c1c60c8f 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -213,11 +213,14 @@ public static class CSharpNaming // the Postgres-native inet type). Both are string-backed on the wire. [FIELD_SUBTYPE_URI] = "Uri", [FIELD_SUBTYPE_INET] = "IPAddress", + // field.duration binds to the native System.TimeSpan value type (DB column is the + // Postgres-native interval, text elsewhere); string-backed (ISO-8601) on the wire. + [FIELD_SUBTYPE_DURATION] = "TimeSpan", }; /// Value types that take a ? suffix when nullable (vs. reference types). private static readonly HashSet ValueTypes = new(StringComparer.Ordinal) - { "int", "long", "double", "float", "decimal", "bool", "DateOnly", "TimeOnly", "DateTime", "DateTimeOffset", "Guid" }; + { "int", "long", "double", "float", "decimal", "bool", "DateOnly", "TimeOnly", "DateTime", "DateTimeOffset", "Guid", "TimeSpan" }; /// /// ADR-0036 Wave 3 — the CANONICAL hostname matcher for @stringFormat: hostname, diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index fb78d00bd4..addc0531fa 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -151,6 +151,8 @@ public virtual IEnumerable Generate(GenContext ctx) // creates (ADR-0015). foreach (var f in p.Fields().Where(f => f.SubType == FIELD_SUBTYPE_MAP)) modelLines.Add(MapJsonbConfig(name, p, f, ctx)); + // A duration column on a view reads through the same provider-dependent mapping. + AddDurationConfig(name, p, p.Fields(), ctx, modelLines); } foreach (var e in objects.Where(o => o.IsEntity() && !o.IsReadOnlyProjection())) { @@ -1087,10 +1089,53 @@ private void EmitFieldTypeConfig( $" modelBuilder.Entity<{className}>().Property(x => x.{prop}).HasColumnType(\"inet\");"); } + // field.duration — a System.TimeSpan. Npgsql maps it to the native `interval` (and an array + // to `interval[]`), reading an interval with a month or year part as an error. Every other + // provider stores the canonical ISO-8601 string in a text column (the TS-owned SQLite / MySQL + // schemas), through the entity namespace's DurationWire; EF's own TimeSpan text ("01:30:00") + // would not be the cross-port form, and MySQL's `time` cannot hold more than 838 hours. + AddDurationConfig(className, entity, fieldList, ctx, modelLines); + foreach (var f in fieldList.Where(f => !f.ResolvedIsArray() && f.DbColumnType is not null)) if (DbColumnTypeConfig(className, f) is { } cfg) modelLines.Add(cfg); } + // field.duration — a System.TimeSpan. Npgsql maps it to the native `interval` (and an array + // to `interval[]`), reading an interval with a month or year part as an error. Every other + // provider stores the canonical ISO-8601 string in a text column (the TS-owned SQLite / MySQL + // schemas), through the entity namespace's DurationWire; EF's own TimeSpan text ("01:30:00") + // would not be the cross-port form, and MySQL's `time` cannot hold more than 838 hours. + private static void AddDurationConfig( + string className, MetaObject entity, IEnumerable fields, GenContext ctx, List modelLines) + { + foreach (var f in fields.Where(f => f.SubType == FIELD_SUBTYPE_DURATION && f.DbColumnType is null)) + { + var prop = CSharpNaming.Pascal(f.Name); + var converter = DurationConverter(entity, ctx); + var npgsql = f.ResolvedIsArray() + ? null + : $" modelBuilder.Entity<{className}>().Property(x => x.{prop}).HasColumnType(\"interval\");"; + var text = f.ResolvedIsArray() + ? $" modelBuilder.Entity<{className}>().PrimitiveCollection(x => x.{prop}).ElementType().HasConversion({converter});" + : $" modelBuilder.Entity<{className}>().Property(x => x.{prop}).HasConversion({converter});"; + modelLines.Add(npgsql is null + ? $" if (Database.ProviderName != \"{NpgsqlProviderName}\")\n{text}" + : $" if (Database.ProviderName == \"{NpgsqlProviderName}\")\n{npgsql}\n else\n{text}"); + } + } + + // A TimeSpan <-> canonical ISO-8601 string converter, through the DurationWire the entity + // generator emits into OWNER's namespace (owner has a duration field, so it has one). + private static string DurationConverter(MetaObject owner, GenContext ctx) + { + var ns = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(owner), owner.Name, fallbackContext: owner.Name); + return "new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + $"v => global::{ns}.DurationWire.Format(v), v => global::{ns}.DurationWire.Parse(v))"; + } + + // The EF Core provider name Npgsql registers (DbContext.Database.ProviderName). + private const string NpgsqlProviderName = "Npgsql.EntityFrameworkCore.PostgreSQL"; + // True when a value object declares a field.map, or holds a value object that does. private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet seen) { @@ -1258,6 +1303,30 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s continue; } + // A `field.duration` member: the migration flattens it to an `interval` column on + // Postgres (Npgsql maps the TimeSpan natively) and a text column elsewhere, which holds + // the canonical ISO-8601 string — the same provider-dependent mapping a top-level + // duration takes (AddDurationConfig). Without the converter EF would write its own + // "01:30:00" there and fail to read another port's "PT1H30M". + if (nf.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(nf) is null) + { + var dprop = CSharpNaming.Pascal(nf.Name); + var converter = DurationConverter(vo, ctx); + if (nf.ResolvedIsArray()) + { + sb.AppendLine($" b.PrimitiveCollection(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); + sb.AppendLine($" if (Database.ProviderName != \"{NpgsqlProviderName}\")"); + sb.AppendLine($" b.PrimitiveCollection(p => p.{dprop}).ElementType().HasConversion({converter});"); + } + else + { + sb.AppendLine($" b.Property(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); + sb.AppendLine($" if (Database.ProviderName != \"{NpgsqlProviderName}\")"); + sb.AppendLine($" b.Property(p => p.{dprop}).HasConversion({converter});"); + } + continue; + } + var isScalar = CSharpNaming.ScalarFor(nf.SubType) is not null; var isEnum = nf.SubType == FIELD_SUBTYPE_ENUM && !nf.ResolvedIsArray(); if (!isScalar && !isEnum) @@ -1301,7 +1370,6 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s /// private static List JsonEnumConversions(MetaObject vo, GenContext ctx, string builder = "b") { - _ = ctx; var lines = new List(); foreach (var nf in vo.Fields()) { @@ -1317,6 +1385,16 @@ private static List JsonEnumConversions(MetaObject vo, GenContext ctx, s : $" {builder}.Property(p => p.{prop}).HasConversion(v => v == null ? null : v.Value.ToString(\"0.############################\", System.Globalization.CultureInfo.InvariantCulture), s => s == null ? (decimal?)null : decimal.Parse(s, System.Globalization.CultureInfo.InvariantCulture));"); continue; } + // A duration member of a JSON document is stored as its canonical ISO-8601 string (the + // wire form), not as EF's own TimeSpan text ("01:30:00"), on every provider. + if (nf.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(nf) is null) + { + var converter = DurationConverter(vo, ctx); + lines.Add(nf.ResolvedIsArray() + ? $" {builder}.PrimitiveCollection(p => p.{prop}).ElementType().HasConversion({converter});" + : $" {builder}.Property(p => p.{prop}).HasConversion({converter});"); + continue; + } if (nf.SubType != FIELD_SUBTYPE_ENUM) continue; // ADR-0039: resolving — array-ness is inheritable via extends. lines.Add(nf.ResolvedIsArray() diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 810c3c78e7..cae663d7ad 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -197,6 +197,12 @@ public virtual IEnumerable Generate(GenContext ctx) var decimalNamespaces = HelperNamespaces(mapped.Concat(unmappedShapes).Concat(valueObjects).Where(HasDecimalWireField), ctx); foreach (var ns in decimalNamespaces) files.Add(EmitDecimalWireFile(ns, HelperFileName("DecimalWire", ns, decimalNamespaces))); + + // field.duration — the duration wire helper, ONCE per namespace that has a duration + // property (the same shape sets the decimal helper is seeded from). + var durationNamespaces = HelperNamespaces(mapped.Concat(unmappedShapes).Concat(valueObjects).Where(HasDurationField), ctx); + foreach (var ns in durationNamespaces) + files.Add(EmitDurationWireFile(ns, HelperFileName("DurationWire", ns, durationNamespaces))); return files; } @@ -623,6 +629,7 @@ protected virtual string TphSubtypeScalarProperty( arr.AppendLine($" [Column({CSharpNaming.ColumnRef(entity, field, strategy, includeNames)})]"); AppendArrayValidatorAttributes(arr, field); AppendDecimalConverterAttribute(arr, field, nullable: false, _wire); + AppendDurationConverterAttribute(arr, field); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection. if (IsDecimalWireField(field) && !CSharpNaming.IsRequired(entity, field)) @@ -640,6 +647,7 @@ protected virtual string TphSubtypeScalarProperty( AppendNumericValidatorAttributes(sb, field); var required = CSharpNaming.IsRequired(entity, field); AppendDecimalConverterAttribute(sb, field, nullable: !required, _wire); + AppendDurationConverterAttribute(sb, field); var nullable = required ? "" : "?"; // Mirrors ScalarProperty's own initializer handling (its non-TPH sibling): a // literal-safe @default (bool/int/long/double/float/decimal/string) wins over the @@ -1383,6 +1391,287 @@ public override void Write(Utf8JsonWriter writer, IList value, JsonSeri private static EmittedFile EmitDecimalWireFile(string ns, string fileName) => new(fileName, DecimalWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n"); + // field.duration — the duration wire form (fixtures/duration-wire/). This text is the + // Runtime/DurationWire.cs source with its namespace as __NS__; DurationWireTests gates the two + // byte-for-byte after the namespace swap. It lives HERE (not read from the HelperRuntime + // resource) so an ejected EntityGenerator stays self-contained, the way DecimalWire's is. + private const string DurationWireSourceTemplate = """ +// +// DurationWire — the wire form of a field.duration: a fixed-length span of time, a TimeSpan in C#. +// +// On the wire a duration is an ISO-8601 duration STRING. Every port writes the canonical form +// `[-]PT[H][M][[.]S]`: hours never folded into days, zero components left out, zero +// as `PT0S`, at most six fractional digits (a Postgres interval's precision; a TimeSpan's 100 ns +// ticks below that are truncated toward zero), one leading `-` for a negative span. Every port +// reads that form plus a leading day count (`nD`, exactly 24 hours), an optional `+`, and up to +// nine fractional digits. Years, months and weeks are refused: a calendar span has no fixed +// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. The magnitude is +// bounded at 256204778 hours, the largest whole hour a TimeSpan holds, in every port: a longer span +// is refused on parse and on write, never wrapped or rounded. The rule and its cross-port vectors +// are in fixtures/duration-wire/. +// +// ONE source, two homes. This file is the package's production helper (the filter dispatcher +// parses its operands through it). The entity generator emits the SAME text, with only the +// namespace changed, as `DurationWire.g.cs` into every namespace that has a duration property, +// so the `[DurationWire.Iso]` on each property resolves inside the generated project and the +// generated entity code imports nothing from MetaObjects (CLAUDE.md). DurationWireTests gates +// the two texts byte-for-byte. Keep this file free of references to anything but the BCL. + +#nullable enable +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace __NS__; + +/// The canonical wire form of a duration: format, parse, and the System.Text.Json converters. +public static class DurationWire +{ + /// The accepted form, as a regular expression (the cross-port statement of the rule; this helper parses it by hand). + public const string Pattern = @"^[-+]?P(?!$)([0-9]+D)?(T(?=[0-9])([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]{1,9})?S)?)?$"; + + private const long MicrosPerSecond = 1_000_000L; + private const long MicrosPerMinute = 60L * MicrosPerSecond; + private const long MicrosPerHour = 60L * MicrosPerMinute; + private const long MicrosPerDay = 24L * MicrosPerHour; + private const long TicksPerMicro = TimeSpan.TicksPerMillisecond / 1000L; + + /// The largest magnitude a duration may have, in hours (the largest whole hour a TimeSpan holds); every port shares the bound. + public const long MaxHours = 256_204_778L; + + private const long MaxMicros = MaxHours * MicrosPerHour; + + /// True when is within the shared bound (at most hours either way, counted in whole microseconds). + public static bool InRange(TimeSpan value) + { + long micros = value.Ticks / TicksPerMicro; + return micros <= MaxMicros && micros >= -MaxMicros; + } + + /// + /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks + /// truncated toward zero. Throws for a span past the shared bound + /// (), which no port can read. + /// + public static string Format(TimeSpan value) + { + if (!InRange(value)) + throw new OverflowException("field.duration: a span longer than " + MaxHours.ToString(CultureInfo.InvariantCulture) + " hours is not a duration"); + long micros = value.Ticks / TicksPerMicro; // integer division truncates toward zero + bool negative = micros < 0; + long rest = negative ? -micros : micros; + long h = rest / MicrosPerHour; + rest %= MicrosPerHour; + long m = rest / MicrosPerMinute; + rest %= MicrosPerMinute; + long s = rest / MicrosPerSecond; + long frac = rest % MicrosPerSecond; + var sb = new StringBuilder(negative ? "-PT" : "PT"); + if (h > 0) sb.Append(h.ToString(CultureInfo.InvariantCulture)).Append('H'); + if (m > 0) sb.Append(m.ToString(CultureInfo.InvariantCulture)).Append('M'); + if (s > 0 || frac > 0) + { + sb.Append(s.ToString(CultureInfo.InvariantCulture)); + if (frac > 0) sb.Append('.').Append(frac.ToString("D6", CultureInfo.InvariantCulture).TrimEnd('0')); + sb.Append('S'); + } + return micros == 0 ? "PT0S" : sb.ToString(); + } + + /// + /// Parse an ISO-8601 duration in the accepted form (). False for anything + /// else: years, months or weeks, lowercase designators, fractional hours or minutes, a comma, + /// per-component signs, whitespace, out-of-order components, or a span longer than + /// hours (one microsecond over is refused). + /// Fractional seconds past the sixth digit are truncated toward zero. + /// + public static bool TryParse(string? text, out TimeSpan value) + { + value = TimeSpan.Zero; + if (text is null) return false; + int i = 0, n = text.Length; + bool negative = false; + if (i < n && (text[i] == '-' || text[i] == '+')) { negative = text[i] == '-'; i++; } + if (i >= n || text[i] != 'P') return false; + i++; + if (i >= n) return false; // "P" alone has no component + long micros = 0; + try + { + checked + { + // Optional day count. + if (IsDigit(text[i])) + { + long days = ReadDigits(text, ref i); + if (i >= n || text[i] != 'D') return false; + i++; + micros += days * MicrosPerDay; + } + if (i < n) + { + if (text[i] != 'T') return false; + i++; + if (i >= n || !IsDigit(text[i])) return false; // `T` must be followed by a component + int order = 0; // 1 = H, 2 = M, 3 = S: each at most once, in that order + while (i < n) + { + if (!IsDigit(text[i])) return false; + long whole = ReadDigits(text, ref i); + if (i >= n) return false; + if (text[i] == '.') + { + i++; + int fracStart = i; + while (i < n && IsDigit(text[i])) i++; + int digits = i - fracStart; + if (digits < 1 || digits > 9 || i >= n || text[i] != 'S' || order >= 3) return false; + var six = text.Substring(fracStart, Math.Min(digits, 6)).PadRight(6, '0'); + micros += whole * MicrosPerSecond + long.Parse(six, NumberStyles.None, CultureInfo.InvariantCulture); + order = 3; + i++; + continue; + } + int at = text[i] switch { 'H' => 1, 'M' => 2, 'S' => 3, _ => 0 }; + if (at == 0 || at <= order) return false; + order = at; + micros += whole * (at == 1 ? MicrosPerHour : at == 2 ? MicrosPerMinute : MicrosPerSecond); + i++; + } + } + if (micros > MaxMicros) return false; + value = TimeSpan.FromTicks((negative ? -micros : micros) * TicksPerMicro); + } + } + catch (OverflowException) + { + return false; + } + return true; + } + + /// Parse the accepted form, or throw . + public static TimeSpan Parse(string text) => + TryParse(text, out var value) + ? value + : throw new FormatException("not an ISO-8601 duration (such as PT1H30M; no years, months or weeks): " + text); + + /// The canonical form of an accepted ISO-8601 duration, or null when is not one. + public static string? Canonical(string? text) => TryParse(text, out var value) ? Format(value) : null; + + /// An already-parsed JSON value (a PATCH merge reads one property at a time): a string in the accepted form. + public static bool TryParseElement(JsonElement element, out TimeSpan value) + { + value = TimeSpan.Zero; + return element.ValueKind == JsonValueKind.String && TryParse(element.GetString(), out value); + } + + private static bool IsDigit(char c) => c >= '0' && c <= '9'; + + // A run of ASCII digits at i (at least one; the caller checked), advancing i past it. + private static long ReadDigits(string text, ref int i) + { + long v = 0; + while (i < text.Length && IsDigit(text[i])) + { + v = checked(v * 10 + (text[i] - '0')); + i++; + } + return v; + } + + private static TimeSpan ReadOne(ref Utf8JsonReader reader) + { + if (reader.TokenType != JsonTokenType.String || !TryParse(reader.GetString(), out var value)) + throw new JsonException("field.duration: expected an ISO-8601 duration such as PT1H30M (no years, months or weeks)"); + return value; + } + + /// + /// A duration property (TimeSpan, TimeSpan? or IList<TimeSpan>): written as the + /// canonical string, read from a string in the accepted form; anything else is refused. Attached per + /// property, so no host serializer setting can put System.Text.Json's own TimeSpan form on the wire. + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class IsoAttribute : JsonConverterAttribute + { + public override JsonConverter? CreateConverter(Type typeToConvert) + { + if (typeToConvert == typeof(TimeSpan)) return new DurationJsonConverter(); + if (typeToConvert == typeof(TimeSpan?)) return new NullableDurationJsonConverter(); + if (typeToConvert == typeof(IList)) return new DurationListJsonConverter(); + return null; + } + } + + /// A duration property: the canonical string. + public sealed class DurationJsonConverter : JsonConverter + { + public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => ReadOne(ref reader); + + public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) + => writer.WriteStringValue(Format(value)); + } + + /// A nullable duration property: null is JSON null, with the key present. + public sealed class NullableDurationJsonConverter : JsonConverter + { + public override bool HandleNull => true; + + public override TimeSpan? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => reader.TokenType == JsonTokenType.Null ? null : ReadOne(ref reader); + + public override void Write(Utf8JsonWriter writer, TimeSpan? value, JsonSerializerOptions options) + { + if (value is null) writer.WriteNullValue(); + else writer.WriteStringValue(Format(value.Value)); + } + } + + /// An @isArray duration property, typed IList<TimeSpan>: an array of canonical strings. + public sealed class DurationListJsonConverter : JsonConverter> + { + public override IList? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) return null; + if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("field.duration: expected an array of ISO-8601 durations"); + var list = new List(); + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) list.Add(ReadOne(ref reader)); + return list; + } + + public override void Write(Utf8JsonWriter writer, IList value, JsonSerializerOptions options) + { + writer.WriteStartArray(); + foreach (var d in value) writer.WriteStringValue(Format(d)); + writer.WriteEndArray(); + } + } +} +"""; + + private static EmittedFile EmitDurationWireFile(string ns, string fileName) => + new(fileName, DurationWireSourceTemplate.Replace("__NS__", ns, StringComparison.Ordinal) + "\n"); + + // true iff FIELD is a field.duration (single or @isArray): a System.TimeSpan property carrying + // the per-property ISO-8601 converter. + private static bool IsDurationField(MetaField field) => + field.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(field) is null; + + private static bool HasDurationField(MetaObject entity) => entity.Fields().Any(IsDurationField); + + // The per-property converter: System.Text.Json's own TimeSpan form ("01:30:00") is not the wire + // form, and host JSON options cannot drop a property attribute. One attribute serves + // TimeSpan, TimeSpan? and IList. + private static void AppendDurationConverterAttribute(StringBuilder sb, MetaField field) + { + if (IsDurationField(field)) sb.AppendLine(" [DurationWire.Iso]"); + } + // true iff FIELD surfaces as a CLR decimal (single or @isArray) and so carries the // per-property wire converter. A jsonb override keeps the JsonDocument type, not decimal. private static bool IsDecimalWireField(MetaField field) => @@ -1584,6 +1873,7 @@ protected virtual string ScalarProperty( // EF Core 8 on SQLite materializes a primitive collection only through IList (an // ICollection property throws at query compile time), so a scalar array is an IList. AppendDecimalConverterAttribute(arr, field, nullable: false, _wire); + AppendDurationConverterAttribute(arr, field); // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection; a // NON-required value-object array is nullable so a null member is omitted on the wire. @@ -1646,6 +1936,9 @@ protected virtual string ScalarProperty( // ADR-0019 Amendment 1: a decimal crosses JSON as a canonical string. Attached per // property (not through host JsonSerializerOptions) so no host configuration drops it. AppendDecimalConverterAttribute(sb, field, nullable: !nonNull, _wire); + // field.duration: a TimeSpan crosses JSON as its canonical ISO-8601 string, never as + // System.Text.Json's own "01:30:00". + AppendDurationConverterAttribute(sb, field); var type = nonNull ? baseType : baseType + "?"; // A literal-safe @default (bool / integer / floating / string) emits a property @@ -1826,11 +2119,24 @@ protected static string DefaultInitializer(MetaField field, string baseType) return NumericLiteral(raw) is { } f ? $" = {f}f;" : string.Empty; case "decimal": return NumericLiteral(raw) is { } m ? $" = {m}m;" : string.Empty; + // field.duration: an ISO-8601 @default in the accepted form is parsed by the namespace's + // DurationWire (a malformed one emits nothing, as for the other types). + case "TimeSpan": + return raw is string iso && DurationDefaultPattern.IsMatch(iso) + ? $" = DurationWire.Parse(\"{iso}\");" + : string.Empty; default: return string.Empty; } } + // The accepted field.duration form (fixtures/duration-wire/), the gate on a duration @default. + // `\z`, not `$`: .NET's `$` also matches before a trailing newline, which would land in the + // emitted string literal. The magnitude bound is DurationWire.Parse's, checked when it runs. + private static readonly System.Text.RegularExpressions.Regex DurationDefaultPattern = new( + @"^[-+]?P(?!\z)([0-9]+D)?(T(?=[0-9])([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]{1,9})?S)?)?\z", + System.Text.RegularExpressions.RegexOptions.CultureInvariant); + // The invariant string form of a numeric default, or null if it isn't a clean // number (so a malformed @default never injects garbage into the initializer). // Preserves the authored digits (e.g. "5.50") rather than round-tripping. diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs index 635e10348e..15df52c5d2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs @@ -184,20 +184,24 @@ private static string StrictArg(MetaObject owner, MetaField field, GenContext ct string baseType = CSharpNaming.DbColumnTypeClrOverride(field) ?? CSharpNaming.ScalarForField(field) ?? "string"; bool mirrorIsValue = Fr010FieldMapping.ScalarMirrorType(field.SubType) != "string?"; + // A duration parses through the DurationWire the entity generator emits into the POCO's + // own namespace (the POCO has a duration field, so the namespace has one). + string durationWire = "global::" + PackageBindingResolver.Resolve( + ctx.Config, PackageBindingResolver.EffectivePackage(owner), owner.Name, fallbackContext: owner.Name) + ".DurationWire"; if (Fr010FieldMapping.IsArray(field)) { // The POCO's scalar list is never null (an absent array is empty), whatever @required says. string elem = Fr010FieldMapping.ScalarMirrorType(field.SubType); - string x = Convert(mirrorIsValue ? "x!.Value" : "x!", baseType); + string x = Convert(mirrorIsValue ? "x!.Value" : "x!", baseType, durationWire); return $"({m} ?? global::System.Linq.Enumerable.Empty<{elem}>()).Where(x => x is not null).Select(x => {x}).ToList()"; } if (required) - return Convert(mirrorIsValue ? $"{m}!.Value" : $"{m}!", baseType); + return Convert(mirrorIsValue ? $"{m}!.Value" : $"{m}!", baseType, durationWire); // Optional: null stays null. A nullable mirror value maps straight onto a nullable POCO // member of the same type; anything else converts the present value. - string converted = Convert(mirrorIsValue ? $"{m}.Value" : m, baseType); + string converted = Convert(mirrorIsValue ? $"{m}.Value" : m, baseType, durationWire); if (converted == m || converted == $"{m}.Value") return m; string nullable = CSharpNaming.IsValueType(baseType) ? $"({baseType}?)null" : "null"; return $"{m} is null ? {nullable} : {converted}"; @@ -205,10 +209,10 @@ private static string StrictArg(MetaObject owner, MetaField field, GenContext ct /// /// Convert a present mirror value (, already unwrapped for value types) to - /// the POCO member's CLR type. The mirror carries temporal, uuid, uri and inet values as the - /// strings the model wrote; the POCO holds the native types. + /// the POCO member's CLR type. The mirror carries temporal, uuid, uri, inet and duration values + /// as the strings the model wrote; the POCO holds the native types. /// - private static string Convert(string v, string baseType) => baseType switch + private static string Convert(string v, string baseType, string durationWire) => baseType switch { "DateOnly" => $"global::System.DateOnly.Parse({v}, global::System.Globalization.CultureInfo.InvariantCulture)", "TimeOnly" => $"global::System.TimeOnly.Parse({v}, global::System.Globalization.CultureInfo.InvariantCulture)", @@ -217,6 +221,7 @@ private static string StrictArg(MetaObject owner, MetaField field, GenContext ct "Guid" => $"global::System.Guid.Parse({v})", "Uri" => $"new global::System.Uri({v}, global::System.UriKind.RelativeOrAbsolute)", "IPAddress" => $"global::System.Net.IPAddress.Parse({v})", + "TimeSpan" => $"{durationWire}.Parse({v})", "JsonDocument" => $"global::System.Text.Json.JsonDocument.Parse({v})", "float" => $"(float){v}", _ => v, diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index 223d5e3de9..c993e20935 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -80,7 +80,7 @@ public IEnumerable Generate(GenContext ctx) .ToList(); if (served.Count == 0) yield break; - yield return new EmittedFile("ReportExportWriter.g.cs", SharedWriter(ctx)); + yield return new EmittedFile("ReportExportWriter.g.cs", SharedWriter(ctx, HasDurationColumn(served))); foreach (var report in served) yield return new EmittedFile(CSharpNaming.Pascal(report.Name) + "Export.g.cs", ReportModule(report, ctx)); } @@ -133,17 +133,55 @@ private string ReportModule(MetaObject report, GenContext ctx) return sb.ToString(); } - private string SharedWriter(GenContext ctx) + // field.duration — the duration parts of the shared writer, emitted only when a served report has a + // duration column, so the writer of a model without one is byte-identical to the one before + // durations existed. The rule is the generated DurationWire.Format's. + private const string DurationDoc = "a duration as its canonical ISO-8601 string, "; + private const string DurationCase = " case TimeSpan ts: return new(Duration(ts), false);\n"; + private const string DurationMethod = """ + // A field.duration as the wire writes it: the canonical ISO-8601 duration [-]PT[nH][nM][n[.f]S], + // hours never folded into days, at most six fractional digits (sub-microsecond ticks truncated + // toward zero), zero as PT0S. The same rule as the generated DurationWire.Format. + private static string Duration(TimeSpan value) + { + long micros = value.Ticks / 10; + bool negative = micros < 0; + long rest = negative ? -micros : micros; + long h = rest / 3_600_000_000L, m = rest / 60_000_000L % 60, s = rest / 1_000_000L % 60, f = rest % 1_000_000L; + var sb = new StringBuilder(negative ? "-PT" : "PT"); + if (h > 0) sb.Append(h.ToString(CultureInfo.InvariantCulture)).Append('H'); + if (m > 0) sb.Append(m.ToString(CultureInfo.InvariantCulture)).Append('M'); + if (s > 0 || f > 0) + { + sb.Append(s.ToString(CultureInfo.InvariantCulture)); + if (f > 0) sb.Append('.').Append(f.ToString("D6", CultureInfo.InvariantCulture).TrimEnd('0')); + sb.Append('S'); + } + return micros == 0 ? "PT0S" : sb.ToString(); + } + + +"""; + + // True when a served report has a field.duration column (a TimeSpan cell). + private static bool HasDurationColumn(IEnumerable served) => + served.Any(r => r.Fields().Any(f => f.SubType == FIELD_SUBTYPE_DURATION)); + + private string SharedWriter(GenContext ctx, bool durations) { var text = SharedWriterTemplate .Replace("@NAMESPACE@", ctx.Config.Namespace, StringComparison.Ordinal) .Replace("@CSV_BOM@", Literal(CsvBom), StringComparison.Ordinal) .Replace("@DECIMALS_AS_STRING@", Literal(ctx.Root.WireFormat.Decimals == DecimalWireForm.String), StringComparison.Ordinal) - .Replace("@XML_NIL@", Literal(XmlNulls == ReportExportXmlNulls.Nil), StringComparison.Ordinal); + .Replace("@XML_NIL@", Literal(XmlNulls == ReportExportXmlNulls.Nil), StringComparison.Ordinal) + .Replace("@DURATION_DOC@", durations ? DurationDoc : "", StringComparison.Ordinal) + .Replace("@DURATION_CASE@", durations ? DurationCase : "", StringComparison.Ordinal) + .Replace("@DURATION_METHOD@", durations ? DurationMethod : "", StringComparison.Ordinal); return text; } - // The shared writer, verbatim but for the four @TOKENS@. A plain string, not an interpolated + // The shared writer, verbatim but for its @TOKENS@ (the @DURATION_*@ ones are empty without a + // duration column). A plain string, not an interpolated // one: the C# it holds is full of braces. private const string SharedWriterTemplate = """ // @@ -179,7 +217,7 @@ public static class ReportExportWriter private const string XsiNamespace = "http://www.w3.org/2001/XMLSchema-instance"; - /// The wire form of a row property: currency as integer minor units, a date as YYYY-MM-DD, a timestamp as UTC with Z, a boolean as true/false, a null as null. + /// The wire form of a row property: currency as integer minor units, a date as YYYY-MM-DD, a timestamp as UTC with Z, @DURATION_DOC@a boolean as true/false, a null as null. public static ReportExportCell Cell(object? value) { switch (value) @@ -196,7 +234,7 @@ public static ReportExportCell Cell(object? value) case Enum e: return new(e.ToString(), true); case Uri u: return new(u.OriginalString, true); case IPAddress ip: return new(ip.ToString(), false); - case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); +@DURATION_CASE@ case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); case IFormattable f: return new(f.ToString(null, CultureInfo.InvariantCulture), false); default: return new(Convert.ToString(value, CultureInfo.InvariantCulture), true); } @@ -213,7 +251,7 @@ private static string Timestamp(DateTimeOffset value) return utc.ToString(format, CultureInfo.InvariantCulture); } - // The canonical decimal string: plain notation, no trailing fraction zeros, zero as "0". +@DURATION_METHOD@ // The canonical decimal string: plain notation, no trailing fraction zeros, zero as "0". private static string Canonical(decimal value) { var s = value.ToString(CultureInfo.InvariantCulture); diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index f254e8ec63..2114adea9d 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -417,7 +417,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // body carries the derived (view-computed) fields (read-your-writes). AppendCreateHandler(sb, "/" + route, cls, dbSet, requiredKeys, CreatedResult("prefix + \"/" + route + "\"", "input", credentials), voFields, mapVoFields, autoSetFields, - writeThrough ? (readDbSet, pkProp!, route) : null, parseBody: HasDecimalField(entity), + writeThrough ? (readDbSet, pkProp!, route) : null, parseBody: HasDecimalField(entity) || HasDurationField(entity), deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials); // PATCH + PUT share the same handler — TS reference exposes both verbs, and both @@ -454,7 +454,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine(" var entry = db.Entry(existing);"); AppendUpdateAutoSet(sb, autoSetFields); AppendPartialMergeLoop(sb, null, voFields, mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(entity), - deniedFields.Select(f => f.Name).ToList()); + deniedFields.Select(f => f.Name).ToList(), HasDurationField(entity)); AppendSaveChanges(sb); AppendArrayNullClears(sb, voFields, tableRef, pkColumnRef); // #214 — writes target the table; for a write-through entity re-read the row @@ -1195,6 +1195,13 @@ private static bool HasDecimalField(MetaObject entity, HashSet? seen return false; } + // true iff the entity has a field.duration column of its own (a TimeSpan property, so a + // DurationWire copy is emitted into its namespace). Its converter refuses a bad value while the + // body is bound, so, like a decimal, the create route parses the body itself to answer with the + // {error:"validation"} envelope, and the PATCH merge reads the wire form explicitly. + private static bool HasDurationField(MetaObject entity) => + entity.Fields().Any(f => f.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(f) is null); + private static void AppendDecimalRangeGroup(StringBuilder sb) { sb.AppendLine(" IEndpointRouteBuilder mount = app;"); @@ -1233,7 +1240,7 @@ private static void AppendPartialMergeLoop( StringBuilder sb, string? discProp, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetNavs, IReadOnlyList frozenNavs, bool hasDecimal, - IReadOnlyList deniedKeys) + IReadOnlyList deniedKeys, bool hasDuration = false) { // A nullable array-of-VO column that a request clears to null (present-null) can NOT be // NULLed by an owned-nav assignment — EF OwnsMany(...).ToJson writes `[]` for a null @@ -1338,22 +1345,47 @@ private static void AppendPartialMergeLoop( // `DecimalWire` resolves to the copy the entity generator emits into this namespace (the // routes and the entities share it), so the output differs between a packaged and an // ejected generator only in the helper-runtime `using`, as before. - if (hasDecimal) + if (hasDecimal || hasDuration) { sb.AppendLine(" object? __val;"); - sb.AppendLine(" if (clr == typeof(decimal))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (!DecimalWire.TryParseElement(prop.Value, out var __dec) || !DecimalWire.FitsDeclared(existing.GetType(), target.Name, __dec)) return Results.BadRequest(new { error = \"validation\" });"); - sb.AppendLine(" __val = __dec;"); - sb.AppendLine(" }"); - sb.AppendLine(" else if (clr == typeof(System.Collections.Generic.IList))"); - sb.AppendLine(" {"); - sb.AppendLine(" if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) return Results.BadRequest(new { error = \"validation\" });"); - sb.AppendLine(" var __decs = new System.Collections.Generic.List();"); - sb.AppendLine(" foreach (var __el in prop.Value.EnumerateArray())"); - sb.AppendLine(" if (DecimalWire.TryParseElement(__el, out var __d1) && DecimalWire.FitsDeclared(existing.GetType(), target.Name, __d1)) __decs.Add(__d1); else return Results.BadRequest(new { error = \"validation\" });"); - sb.AppendLine(" __val = __decs;"); - sb.AppendLine(" }"); + var arm = "if"; + if (hasDecimal) + { + sb.AppendLine(" if (clr == typeof(decimal))"); + sb.AppendLine(" {"); + sb.AppendLine(" if (!DecimalWire.TryParseElement(prop.Value, out var __dec) || !DecimalWire.FitsDeclared(existing.GetType(), target.Name, __dec)) return Results.BadRequest(new { error = \"validation\" });"); + sb.AppendLine(" __val = __dec;"); + sb.AppendLine(" }"); + sb.AppendLine(" else if (clr == typeof(System.Collections.Generic.IList))"); + sb.AppendLine(" {"); + sb.AppendLine(" if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) return Results.BadRequest(new { error = \"validation\" });"); + sb.AppendLine(" var __decs = new System.Collections.Generic.List();"); + sb.AppendLine(" foreach (var __el in prop.Value.EnumerateArray())"); + sb.AppendLine(" if (DecimalWire.TryParseElement(__el, out var __d1) && DecimalWire.FitsDeclared(existing.GetType(), target.Name, __d1)) __decs.Add(__d1); else return Results.BadRequest(new { error = \"validation\" });"); + sb.AppendLine(" __val = __decs;"); + sb.AppendLine(" }"); + arm = "else if"; + } + // field.duration: a bare TimeSpan deserialized here would take System.Text.Json's own + // "01:30:00" form, not the property's ISO-8601 converter, so the duration arms read the + // wire form through `DurationWire` (the copy the entity generator emits into this + // namespace) and refuse anything else with the validation envelope. + if (hasDuration) + { + sb.AppendLine($" {arm} (clr == typeof(System.TimeSpan))"); + sb.AppendLine(" {"); + sb.AppendLine(" if (!DurationWire.TryParseElement(prop.Value, out var __dur)) return Results.BadRequest(new { error = \"validation\" });"); + sb.AppendLine(" __val = __dur;"); + sb.AppendLine(" }"); + sb.AppendLine(" else if (clr == typeof(System.Collections.Generic.IList))"); + sb.AppendLine(" {"); + sb.AppendLine(" if (prop.Value.ValueKind != System.Text.Json.JsonValueKind.Array) return Results.BadRequest(new { error = \"validation\" });"); + sb.AppendLine(" var __durs = new System.Collections.Generic.List();"); + sb.AppendLine(" foreach (var __el in prop.Value.EnumerateArray())"); + sb.AppendLine(" if (DurationWire.TryParseElement(__el, out var __u1)) __durs.Add(__u1); else return Results.BadRequest(new { error = \"validation\" });"); + sb.AppendLine(" __val = __durs;"); + sb.AppendLine(" }"); + } sb.AppendLine(" else"); sb.AppendLine(" __val = System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts);"); } @@ -1447,7 +1479,7 @@ private static void AppendTphSubtypeRoutes( // VO columns on a TPH subtype are out of scope (Program D §6) — no typed arms. AppendCreateHandler(sb, "/" + subRoute, subCls, dbSet, requiredKeys, CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields, - parseBody: HasDecimalField(st.Entity), + parseBody: HasDecimalField(st.Entity) || HasDurationField(st.Entity), deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials); // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped @@ -1470,7 +1502,7 @@ private static void AppendTphSubtypeRoutes( // ADR-0045 + the 0.19.4 lesson: TPH is a SEPARATE code path per port, so the // per-subtype merge states the same exclusion rather than inheriting it. AppendPartialMergeLoop(sb, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), - deniedFields.Select(f => f.Name).ToList()); + deniedFields.Select(f => f.Name).ToList(), HasDurationField(st.Entity)); AppendSaveChanges(sb); sb.AppendLine($" return {OkResult("existing", credentials)};"); sb.AppendLine(" }"); diff --git a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs index d9e2dee965..e8c26ed74d 100644 --- a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs +++ b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs @@ -56,7 +56,8 @@ public static class HelperRuntime /// routes except Iso8601TimestampConverter.cs, which the host registers to give /// those routes the api contract's timestamp spelling — it serves the same wire, so /// the adopter owns it with them. DecimalWire.cs is the decimal wire form - /// (ADR-0019 Amendment 1): the filter dispatcher parses decimal operands through it. + /// (ADR-0019 Amendment 1): the filter dispatcher parses decimal operands through it, and + /// DurationWire.cs is the field.duration wire form it parses duration operands with. /// ReportExportHttp.cs is the HTTP side of report export: a report list route that /// is built with a report-export generator wired calls it. /// @@ -70,6 +71,7 @@ public static class HelperRuntime "ConstraintErrors.cs", "Iso8601TimestampConverter.cs", "DecimalWire.cs", + "DurationWire.cs", "DecimalRangeEndpointFilter.cs", "ReportExportHttp.cs", ]; diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index 0a9a096a62..c829561da5 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -87,6 +87,7 @@ + diff --git a/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs b/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs new file mode 100644 index 0000000000..1de7a8d9e3 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs @@ -0,0 +1,256 @@ +// +// DurationWire — the wire form of a field.duration: a fixed-length span of time, a TimeSpan in C#. +// +// On the wire a duration is an ISO-8601 duration STRING. Every port writes the canonical form +// `[-]PT[H][M][[.]S]`: hours never folded into days, zero components left out, zero +// as `PT0S`, at most six fractional digits (a Postgres interval's precision; a TimeSpan's 100 ns +// ticks below that are truncated toward zero), one leading `-` for a negative span. Every port +// reads that form plus a leading day count (`nD`, exactly 24 hours), an optional `+`, and up to +// nine fractional digits. Years, months and weeks are refused: a calendar span has no fixed +// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. The magnitude is +// bounded at 256204778 hours, the largest whole hour a TimeSpan holds, in every port: a longer span +// is refused on parse and on write, never wrapped or rounded. The rule and its cross-port vectors +// are in fixtures/duration-wire/. +// +// ONE source, two homes. This file is the package's production helper (the filter dispatcher +// parses its operands through it). The entity generator emits the SAME text, with only the +// namespace changed, as `DurationWire.g.cs` into every namespace that has a duration property, +// so the `[DurationWire.Iso]` on each property resolves inside the generated project and the +// generated entity code imports nothing from MetaObjects (CLAUDE.md). DurationWireTests gates +// the two texts byte-for-byte. Keep this file free of references to anything but the BCL. + +#nullable enable +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace MetaObjects.Codegen.Runtime; + +/// The canonical wire form of a duration: format, parse, and the System.Text.Json converters. +public static class DurationWire +{ + /// The accepted form, as a regular expression (the cross-port statement of the rule; this helper parses it by hand). + public const string Pattern = @"^[-+]?P(?!$)([0-9]+D)?(T(?=[0-9])([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]{1,9})?S)?)?$"; + + private const long MicrosPerSecond = 1_000_000L; + private const long MicrosPerMinute = 60L * MicrosPerSecond; + private const long MicrosPerHour = 60L * MicrosPerMinute; + private const long MicrosPerDay = 24L * MicrosPerHour; + private const long TicksPerMicro = TimeSpan.TicksPerMillisecond / 1000L; + + /// The largest magnitude a duration may have, in hours (the largest whole hour a TimeSpan holds); every port shares the bound. + public const long MaxHours = 256_204_778L; + + private const long MaxMicros = MaxHours * MicrosPerHour; + + /// True when is within the shared bound (at most hours either way, counted in whole microseconds). + public static bool InRange(TimeSpan value) + { + long micros = value.Ticks / TicksPerMicro; + return micros <= MaxMicros && micros >= -MaxMicros; + } + + /// + /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks + /// truncated toward zero. Throws for a span past the shared bound + /// (), which no port can read. + /// + public static string Format(TimeSpan value) + { + if (!InRange(value)) + throw new OverflowException("field.duration: a span longer than " + MaxHours.ToString(CultureInfo.InvariantCulture) + " hours is not a duration"); + long micros = value.Ticks / TicksPerMicro; // integer division truncates toward zero + bool negative = micros < 0; + long rest = negative ? -micros : micros; + long h = rest / MicrosPerHour; + rest %= MicrosPerHour; + long m = rest / MicrosPerMinute; + rest %= MicrosPerMinute; + long s = rest / MicrosPerSecond; + long frac = rest % MicrosPerSecond; + var sb = new StringBuilder(negative ? "-PT" : "PT"); + if (h > 0) sb.Append(h.ToString(CultureInfo.InvariantCulture)).Append('H'); + if (m > 0) sb.Append(m.ToString(CultureInfo.InvariantCulture)).Append('M'); + if (s > 0 || frac > 0) + { + sb.Append(s.ToString(CultureInfo.InvariantCulture)); + if (frac > 0) sb.Append('.').Append(frac.ToString("D6", CultureInfo.InvariantCulture).TrimEnd('0')); + sb.Append('S'); + } + return micros == 0 ? "PT0S" : sb.ToString(); + } + + /// + /// Parse an ISO-8601 duration in the accepted form (). False for anything + /// else: years, months or weeks, lowercase designators, fractional hours or minutes, a comma, + /// per-component signs, whitespace, out-of-order components, or a span longer than + /// hours (one microsecond over is refused). + /// Fractional seconds past the sixth digit are truncated toward zero. + /// + public static bool TryParse(string? text, out TimeSpan value) + { + value = TimeSpan.Zero; + if (text is null) return false; + int i = 0, n = text.Length; + bool negative = false; + if (i < n && (text[i] == '-' || text[i] == '+')) { negative = text[i] == '-'; i++; } + if (i >= n || text[i] != 'P') return false; + i++; + if (i >= n) return false; // "P" alone has no component + long micros = 0; + try + { + checked + { + // Optional day count. + if (IsDigit(text[i])) + { + long days = ReadDigits(text, ref i); + if (i >= n || text[i] != 'D') return false; + i++; + micros += days * MicrosPerDay; + } + if (i < n) + { + if (text[i] != 'T') return false; + i++; + if (i >= n || !IsDigit(text[i])) return false; // `T` must be followed by a component + int order = 0; // 1 = H, 2 = M, 3 = S: each at most once, in that order + while (i < n) + { + if (!IsDigit(text[i])) return false; + long whole = ReadDigits(text, ref i); + if (i >= n) return false; + if (text[i] == '.') + { + i++; + int fracStart = i; + while (i < n && IsDigit(text[i])) i++; + int digits = i - fracStart; + if (digits < 1 || digits > 9 || i >= n || text[i] != 'S' || order >= 3) return false; + var six = text.Substring(fracStart, Math.Min(digits, 6)).PadRight(6, '0'); + micros += whole * MicrosPerSecond + long.Parse(six, NumberStyles.None, CultureInfo.InvariantCulture); + order = 3; + i++; + continue; + } + int at = text[i] switch { 'H' => 1, 'M' => 2, 'S' => 3, _ => 0 }; + if (at == 0 || at <= order) return false; + order = at; + micros += whole * (at == 1 ? MicrosPerHour : at == 2 ? MicrosPerMinute : MicrosPerSecond); + i++; + } + } + if (micros > MaxMicros) return false; + value = TimeSpan.FromTicks((negative ? -micros : micros) * TicksPerMicro); + } + } + catch (OverflowException) + { + return false; + } + return true; + } + + /// Parse the accepted form, or throw . + public static TimeSpan Parse(string text) => + TryParse(text, out var value) + ? value + : throw new FormatException("not an ISO-8601 duration (such as PT1H30M; no years, months or weeks): " + text); + + /// The canonical form of an accepted ISO-8601 duration, or null when is not one. + public static string? Canonical(string? text) => TryParse(text, out var value) ? Format(value) : null; + + /// An already-parsed JSON value (a PATCH merge reads one property at a time): a string in the accepted form. + public static bool TryParseElement(JsonElement element, out TimeSpan value) + { + value = TimeSpan.Zero; + return element.ValueKind == JsonValueKind.String && TryParse(element.GetString(), out value); + } + + private static bool IsDigit(char c) => c >= '0' && c <= '9'; + + // A run of ASCII digits at i (at least one; the caller checked), advancing i past it. + private static long ReadDigits(string text, ref int i) + { + long v = 0; + while (i < text.Length && IsDigit(text[i])) + { + v = checked(v * 10 + (text[i] - '0')); + i++; + } + return v; + } + + private static TimeSpan ReadOne(ref Utf8JsonReader reader) + { + if (reader.TokenType != JsonTokenType.String || !TryParse(reader.GetString(), out var value)) + throw new JsonException("field.duration: expected an ISO-8601 duration such as PT1H30M (no years, months or weeks)"); + return value; + } + + /// + /// A duration property (TimeSpan, TimeSpan? or IList<TimeSpan>): written as the + /// canonical string, read from a string in the accepted form; anything else is refused. Attached per + /// property, so no host serializer setting can put System.Text.Json's own TimeSpan form on the wire. + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class IsoAttribute : JsonConverterAttribute + { + public override JsonConverter? CreateConverter(Type typeToConvert) + { + if (typeToConvert == typeof(TimeSpan)) return new DurationJsonConverter(); + if (typeToConvert == typeof(TimeSpan?)) return new NullableDurationJsonConverter(); + if (typeToConvert == typeof(IList)) return new DurationListJsonConverter(); + return null; + } + } + + /// A duration property: the canonical string. + public sealed class DurationJsonConverter : JsonConverter + { + public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => ReadOne(ref reader); + + public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) + => writer.WriteStringValue(Format(value)); + } + + /// A nullable duration property: null is JSON null, with the key present. + public sealed class NullableDurationJsonConverter : JsonConverter + { + public override bool HandleNull => true; + + public override TimeSpan? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + => reader.TokenType == JsonTokenType.Null ? null : ReadOne(ref reader); + + public override void Write(Utf8JsonWriter writer, TimeSpan? value, JsonSerializerOptions options) + { + if (value is null) writer.WriteNullValue(); + else writer.WriteStringValue(Format(value.Value)); + } + } + + /// An @isArray duration property, typed IList<TimeSpan>: an array of canonical strings. + public sealed class DurationListJsonConverter : JsonConverter> + { + public override IList? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) return null; + if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("field.duration: expected an array of ISO-8601 durations"); + var list = new List(); + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) list.Add(ReadOne(ref reader)); + return list; + } + + public override void Write(Utf8JsonWriter writer, IList value, JsonSerializerOptions options) + { + writer.WriteStartArray(); + foreach (var d in value) writer.WriteStringValue(Format(d)); + writer.WriteEndArray(); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs index bbdd0bcd25..a81349d302 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs @@ -55,7 +55,8 @@ public static IQueryable ApplyFilter( /// (naming the field) instead of an exception out of . /// is substrate-agnostic and cannot know a column's type; this /// is the first place that does. A decimal operand is parsed with the wire grammar - /// () and compared exactly, never through a double. + /// () and compared exactly, never through a double; a + /// duration operand with the duration wire grammar (). /// A failed parse result is returned unchanged. /// public static FilterParseResult Validate(FilterParseResult parsed) @@ -205,6 +206,13 @@ private static Expression> BuildLambda(FilterPredicate p) return DecimalWire.TryParse(raw, out var exact) ? exact : throw new FormatException("not a decimal: " + raw); + // field.duration: an operand is an ISO-8601 duration in the accepted form (no years, + // months or weeks), compared as a span: `PT90M` equals a stored `PT1H30M`. EF binds it as + // an interval on Postgres and through the property's canonical-string converter elsewhere. + if (underlying == typeof(TimeSpan)) + return DurationWire.TryParse(raw, out var span) + ? span + : throw new FormatException("not an ISO-8601 duration: " + raw); return Convert.ChangeType(raw, underlying, CultureInfo.InvariantCulture); } } diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs b/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs new file mode 100644 index 0000000000..a8d9ed7f9e --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs @@ -0,0 +1,273 @@ +// DurationWireGeneratedApiTests — field.duration through the C# generated routes over real HTTP +// bytes, on a model of its own, and the Postgres half of the shared wire vectors +// (fixtures/duration-wire/vectors.json) against a live interval column through Npgsql. +// +// SQLite needs no Docker: a duration there is the canonical ISO-8601 string in a TEXT column, +// through the generated DbContext's value converter. Postgres is the native interval, bound and +// read as a TimeSpan by Npgsql. + +using System.Text; +using System.Text.Json; +using MetaObjects.Codegen.Runtime; +using MetaObjects.IntegrationTests.Runner; +using Npgsql; +using Xunit; + +namespace MetaObjects.IntegrationTests.Api; + +public sealed class DurationWireGeneratedApiTests +{ + private const string Meta = """ + { "metadata.root": { "package": "acme::ops", "children": [ + { "object.value": { "name": "Window", "children": [ + { "field.duration": { "name": "length", "@required": true } }, + { "field.duration": { "name": "slack" } } + ] } }, + { "object.value": { "name": "Limits", "children": [ + { "field.duration": { "name": "cap" } } + ] } }, + { "object.entity": { "name": "Timer", "children": [ + { "source.rdb": { "@table": "timers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "label" } }, + { "field.duration": { "name": "timeout", "@required": true, "@filterable": true } }, + { "field.duration": { "name": "grace", "@filterable": true } }, + { "field.duration": { "name": "backoff", "isArray": true } }, + { "field.object": { "name": "window", "@objectRef": "Window", "@storage": "jsonb" } }, + { "field.object": { "name": "limits", "@objectRef": "Limits", "@storage": "flattened" } }, + { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } + ] } } + ] } } + """; + + private const string SqliteSchema = """CREATE TABLE "timers" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "label" TEXT, "timeout" TEXT NOT NULL, "grace" TEXT, "backoff" TEXT NOT NULL, "window" TEXT, "limits_cap" TEXT)"""; + private const string PgSchema = """CREATE TABLE "timers" ("id" BIGSERIAL PRIMARY KEY, "label" TEXT, "timeout" INTERVAL NOT NULL, "grace" INTERVAL, "backoff" INTERVAL[] NOT NULL, "window" JSONB, "limits_cap" INTERVAL)"""; + + private static async Task Start(ScenarioEngine engine, string conn, bool createSchema = true) + { + if (createSchema) await engine.ExecuteScriptAsync(conn, engine == ScenarioEngine.Sqlite ? SqliteSchema : PgSchema); + var path = Path.Combine(Path.GetTempPath(), "duration-wire-" + Guid.NewGuid().ToString("N") + ".json"); + await File.WriteAllTextAsync(path, Meta); + try { return await GeneratedRoutesServer.StartAsync(path, "MetaObjects.DurationWire.Generated", engine, conn); } + finally { File.Delete(path); } + } + + private static async Task<(int Status, string Body)> Send(HttpClient c, string method, string path, string? json = null) + { + var req = new HttpRequestMessage(new HttpMethod(method), path); + if (json is not null) req.Content = new StringContent(json, Encoding.UTF8, "application/json"); + var res = await c.SendAsync(req); + return ((int)res.StatusCode, await res.Content.ReadAsStringAsync()); + } + + private static string Field(string body, string name) => + JsonDocument.Parse(body).RootElement.GetProperty(name).GetRawText(); + + // The HTTP contract, the same on every engine. + private static async Task Exercise(HttpClient c) + { + // Read the accepted form, answer the canonical one. + var (s1, b1) = await Send(c, "POST", "/api/timers", + """{"label":"a","timeout":"P1DT2H","grace":"-PT90S","backoff":["PT5400S","PT0.5S"],"window":{"length":"PT90M"},"limits":{"cap":"PT7200S"}}"""); + Assert.True(s1 == 201, $"POST: {s1} {b1}"); + Assert.Equal("\"PT26H\"", Field(b1, "timeout")); + Assert.Equal("\"-PT1M30S\"", Field(b1, "grace")); + Assert.Equal("[\"PT1H30M\",\"PT0.5S\"]", Field(b1, "backoff")); + Assert.Contains("\"length\":\"PT1H30M\"", Field(b1, "window")); + Assert.Contains("\"cap\":\"PT2H\"", Field(b1, "limits")); + var (s2, b2) = await Send(c, "POST", "/api/timers", """{"label":"b","timeout":"PT26H","backoff":[]}"""); + Assert.True(s2 == 201, $"POST: {s2} {b2}"); + Assert.Equal("null", Field(b2, "grace")); + + // A read goes back through the column. + var (_, one) = await Send(c, "GET", "/api/timers/1"); + Assert.Equal("\"PT26H\"", Field(one, "timeout")); + Assert.Equal("\"-PT1M30S\"", Field(one, "grace")); + Assert.Equal("[\"PT1H30M\",\"PT0.5S\"]", Field(one, "backoff")); + Assert.Contains("\"length\":\"PT1H30M\"", Field(one, "window")); + Assert.Contains("\"cap\":\"PT2H\"", Field(one, "limits")); + + // Not a duration: 400 validation, never a stored value or a 500. + foreach (var bad in new[] { "\"P1M\"", "\"P1Y\"", "\"P2W\"", "\"01:30:00\"", "\"PT1.5H\"", "\"pt1h\"", "\"PT\"", "90", "true" }) + { + var (st, body) = await Send(c, "POST", "/api/timers", $"{{\"label\":\"x\",\"timeout\":{bad},\"backoff\":[]}}"); + Assert.True(st == 400, $"POST timeout={bad}: expected 400, got {st} {body}"); + Assert.Contains("validation", body); + } + + // PATCH reads the same wire form. + var (sp, bp) = await Send(c, "PATCH", "/api/timers/2", """{"grace":"PT2700S","backoff":["P1D"]}"""); + Assert.True(sp == 200, $"PATCH: {sp} {bp}"); + Assert.Equal("\"PT45M\"", Field(bp, "grace")); + Assert.Equal("[\"PT24H\"]", Field(bp, "backoff")); + foreach (var bad in new[] { "\"P1M\"", "\"01:30:00\"", "90" }) + { + var (sb, bb) = await Send(c, "PATCH", "/api/timers/2", $"{{\"grace\":{bad}}}"); + Assert.True(sb == 400, $"PATCH grace={bad}: expected 400, got {sb} {bb}"); + Assert.Contains("validation", bb); + } + var (sn, bn) = await Send(c, "PATCH", "/api/timers/2", """{"grace":null}"""); + Assert.Equal(200, sn); + Assert.Equal("null", Field(bn, "grace")); + + // A filter operand is a span: PT1560M is the stored PT26H, on a text column too. + var (sf, bf) = await Send(c, "GET", "/api/timers?filter%5Btimeout%5D=PT1560M"); + Assert.Equal(200, sf); + Assert.Contains("\"label\":\"a\"", bf); + Assert.Contains("\"label\":\"b\"", bf); + var (sg, bg) = await Send(c, "GET", "/api/timers?filter%5Bgrace%5D=-PT90S"); + Assert.Equal(200, sg); + Assert.Contains("\"label\":\"a\"", bg); + Assert.DoesNotContain("\"label\":\"b\"", bg); + foreach (var bad in new[] { "P1M", "01:30:00", "abc" }) + { + var (sx, bx) = await Send(c, "GET", $"/api/timers?filter%5Btimeout%5D%5Beq%5D={bad}"); + Assert.True(sx == 400, $"filter operand {bad}: expected 400, got {sx} {bx}"); + Assert.Contains("invalid_filter_value", bx); + Assert.Contains("\"field\":\"timeout\"", bx); + } + } + + [Fact] + public async Task On_sqlite_a_duration_is_the_canonical_string_in_a_text_column() + { + using var db = new SqliteTempDatabase("mo-duration-wire-"); + var conn = $"Data Source={db.FilePath}"; + await using (var server = await Start(ScenarioEngine.Sqlite, conn)) + { + using var c = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + await Exercise(c); + } + + // The column holds one spelling per span: the canonical one. + await using var sql = await ScenarioEngine.Sqlite.OpenConnectionAsync(conn); + await using var cmd = sql.CreateCommand(); + cmd.CommandText = """SELECT "timeout", "grace", "backoff", "window", "limits_cap" FROM "timers" WHERE "id" = 1"""; + await using (var r = await cmd.ExecuteReaderAsync()) + { + Assert.True(await r.ReadAsync()); + Assert.Equal("PT26H", r.GetString(0)); + Assert.Equal("-PT1M30S", r.GetString(1)); + Assert.Equal("[\"PT1H30M\",\"PT0.5S\"]", r.GetString(2)); + Assert.Contains("\"PT1H30M\"", r.GetString(3)); + Assert.Equal("PT2H", r.GetString(4)); // a flattened value object's member too + } + + // A row another port wrote, in the accepted (not canonical) form, reads back canonical. + await ScenarioEngine.Sqlite.ExecuteScriptAsync(conn, + """INSERT INTO "timers" ("label","timeout","backoff","window","limits_cap") VALUES ('other','P1D','["PT90M"]','{"Length":"PT90M","Slack":null}','PT5400S')"""); + await using var again = await Start(ScenarioEngine.Sqlite, conn, createSchema: false); + using var c2 = new HttpClient { BaseAddress = new Uri(again.BaseUrl) }; + var (so, bo) = await Send(c2, "GET", "/api/timers/3"); + Assert.True(so == 200, $"GET other: {so} {bo}"); + Assert.Equal("\"PT24H\"", Field(bo, "timeout")); + Assert.Equal("[\"PT1H30M\"]", Field(bo, "backoff")); + Assert.Contains("\"cap\":\"PT1H30M\"", Field(bo, "limits")); + } + + [Fact] + public async Task On_postgres_a_duration_is_a_native_interval_and_a_month_part_is_refused() + { + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await Start(ScenarioEngine.Postgres, pg.ConnectionString); + using var c = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + await Exercise(c); + + // The column is a span Postgres can compute with. + await using (var sql = new NpgsqlConnection(pg.ConnectionString)) + { + await sql.OpenAsync(); + await using var cmd = new NpgsqlCommand("""SELECT "timeout" = interval '26 hours', "grace" < interval '0' FROM "timers" WHERE "id" = 1""", sql); + await using var r = await cmd.ExecuteReaderAsync(); + Assert.True(await r.ReadAsync()); + Assert.True(r.GetBoolean(0)); + Assert.True(r.GetBoolean(1)); + } + + // An interval with a month part is not a duration: reading one is an error, never a guess. + // ("-1 mons" / "-1 year" are not here: Npgsql misreads them; see NpgsqlMisreads below.) + foreach (var calendar in new[] { "1 mon", "2 years" }) + { + await ScenarioEngine.Postgres.ExecuteScriptAsync(pg.ConnectionString, + "INSERT INTO \"timers\" (\"id\",\"label\",\"timeout\",\"backoff\") VALUES (900,'calendar', interval '" + calendar + "', '{}')"); + var (sm, bm) = await Send(c, "GET", "/api/timers/900"); + Assert.True(sm != 200, $"interval '{calendar}' read as {bm}"); + await ScenarioEngine.Postgres.ExecuteScriptAsync(pg.ConnectionString, """DELETE FROM "timers" WHERE "id" = 900"""); + } + } + + // Intervals Npgsql 8.0.5's native TimeSpan read gets WRONG instead of refusing: it guards the month + // part with `months > 0`, so a negative month or year part is silently dropped ('-1 mons' reads as + // PT0S), and it adds the day part without an overflow check, so '10675200 days' wraps to a negative + // span inside the bound. EF materializes the column through that read, so the generated code + // never sees the interval's parts. Closing it needs host-side Npgsql configuration (or a driver + // fix), not generated code. + private static readonly HashSet NpgsqlMisreads = ["10675200 days", "-1 mons", "-1 year"]; + + private static async Task> Misread(NpgsqlConnection sql, IEnumerable texts) + { + var misread = new List(); + foreach (var text in texts) + { + await using var cmd = new NpgsqlCommand("SELECT @p::interval", sql); + cmd.Parameters.AddWithValue("p", text); + string? read = null; + try { read = DurationWire.Format((TimeSpan)(await cmd.ExecuteScalarAsync())!); } + catch (Exception) { } + if (read is not null) misread.Add($"'{text}' read as {read}"); + } + return misread; + } + + [Fact(Skip = "Npgsql 8.0.5 misreads these intervals (see NpgsqlMisreads); unskip once the read is guarded.")] + public async Task A_negative_month_part_and_a_day_overflow_are_refused_on_read() + { + await using var pg = await PostgresContainer.StartAsync(); + await using var sql = new NpgsqlConnection(pg.ConnectionString); + await sql.OpenAsync(); + var misread = await Misread(sql, NpgsqlMisreads); + Assert.True(misread.Count == 0, string.Join("; ", misread)); + } + + // The `postgres`, `postgresRefused` and `postgresText` vectors, against Npgsql's native TimeSpan. + [Fact] + public async Task The_postgres_vectors_hold_through_npgsqls_native_timespan() + { + var vectors = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine( + CorpusPaths.Repo, "fixtures", "duration-wire", "vectors.json"))).RootElement; + await using var pg = await PostgresContainer.StartAsync(); + await using var sql = new NpgsqlConnection(pg.ConnectionString); + await sql.OpenAsync(); + + // What an interval column reads back as, under the default IntervalStyle, is its canonical form. + foreach (var v in vectors.GetProperty("postgres").EnumerateArray()) + { + var text = v.GetProperty("in").GetString()!; + await using var cmd = new NpgsqlCommand("SELECT @p::interval", sql); + cmd.Parameters.AddWithValue("p", text); + var span = (TimeSpan)(await cmd.ExecuteScalarAsync())!; + Assert.Equal(v.GetProperty("out").GetString(), DurationWire.Format(span)); + } + + // An interval with a year or month part, one past the shared magnitude bound, or text that is + // no interval is refused: by Npgsql's read, or by DurationWire on the way out. The inputs + // Npgsql itself misreads are pinned separately (NpgsqlMisreads). + var refused = vectors.GetProperty("postgresRefused").EnumerateArray().Select(v => v.GetString()!) + .Where(t => !NpgsqlMisreads.Contains(t)); + Assert.Empty(await Misread(sql, refused)); + + // A TimeSpan bound natively is the same span as the Postgres spelling of its canonical form. + foreach (var v in vectors.GetProperty("postgresText").EnumerateArray()) + { + var span = DurationWire.Parse(v.GetProperty("in").GetString()!); + await using var cmd = new NpgsqlCommand("SELECT @p = @q::interval, @q::interval::text", sql); + cmd.Parameters.AddWithValue("p", span); + cmd.Parameters.AddWithValue("q", v.GetProperty("out").GetString()!); + await using var r = await cmd.ExecuteReaderAsync(); + Assert.True(await r.ReadAsync()); + Assert.True(r.GetBoolean(0), $"{v.GetProperty("in").GetString()} bound as a TimeSpan is not {v.GetProperty("out").GetString()}"); + // ...and that spelling is what Postgres writes back for it. + Assert.Equal(v.GetProperty("out").GetString(), r.GetString(1)); + } + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/AllTypes.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/AllTypes.g.cs index f7d31c0263..ae74d0cf81 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/AllTypes.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/AllTypes.g.cs @@ -64,6 +64,9 @@ public enum AllTypesIntEnumVal { DRAFT, PUBLISHED, ARCHIVED } [Required] [JsonConverter(typeof(MetaNetValidation.IPAddressJsonConverter))] public IPAddress Inet6Val { get; set; } = default!; + [Column(AllTypesNames.DurationValColumn)] + [DurationWire.Iso] + public TimeSpan? DurationVal { get; set; } public Settings? Settings { get; set; } public ICollection + + + + + diff --git a/site-reference/providers.html b/site-reference/providers.html index 53b00ae10d..8c5d46c01a 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -51,7 +51,7 @@ INDEX.md lists by type.

    metaobjects-core-types

    Core metaobjects metamodel types and subtypes.

    -

    Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.report, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.currency

    +

    Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.report, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.currency

    Contributes attributes:

    • field.base: @default, @mutability, @required, @unique
    • @@ -100,6 +100,7 @@

      metaobjects-db

    • field.date: @autoSet, @column, @db.indexed, @dbColumnType
    • field.decimal: @column, @db.indexed, @dbColumnType
    • field.double: @column, @db.indexed, @dbColumnType
    • +
    • field.duration: @column, @db.indexed, @dbColumnType
    • field.enum: @column, @constraintName, @db.indexed, @dbColumnType
    • field.float: @column, @db.indexed, @dbColumnType
    • field.inet: @column, @db.indexed, @dbColumnType
    • @@ -138,6 +139,7 @@

      metaobjects-prompt

    • field.date: @example, @instruction, @xmlText
    • field.decimal: @example, @instruction, @xmlText
    • field.double: @example, @instruction, @xmlText
    • +
    • field.duration: @example, @instruction, @xmlText
    • field.enum: @coerceDefault, @enumAlias, @enumDoc, @example, @instruction, @normalize, @xmlText
    • field.float: @example, @instruction, @xmlText
    • field.inet: @example, @instruction, @xmlText
    • @@ -162,6 +164,7 @@

      metaobjects-ui

    • field.date: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • field.decimal: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • field.double: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • +
    • field.duration: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • field.enum: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • field.float: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • field.inet: @filterable, @formExclude, @sortable, @sortableDefaultOrder
    • diff --git a/site-reference/types/field.html b/site-reference/types/field.html index 8da1adb9c1..65c948f69a 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -987,6 +987,156 @@

      field.double

    • validator.* — 0..*
    • view.* — 0..*
    +

    field.duration

    +

    A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.

    +

    Owning provider: metaobjects-core-types

    +

    When to use: A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span ("every 3 months") is not a duration: model it as an int and a unit.

    +

    Attributes

    +
    field.durationA fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.types/field.md#fieldduration
    field.enum String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. types/field.md#fieldenum
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @columnstringnometaobjects-dbPhysical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json).
    @db.indexedbooleannometaobjects-dbWhen true, suppress the @filterable-without-index Loader warning (the field is indexed by other means).
    @dbColumnTypestringnouuid, jsonbmetaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultanynometaobjects-core-typesDefault value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue().
    @examplestringnometaobjects-promptFR-010: an example value for this field, shown in the generated output-format prompt fragment.
    @filterablebooleannometaobjects-uiWhen true, the field is exposed in generated CRUD filter allowlists (Project D filter layer).
    @formExcludebooleannometaobjects-uiWhen true, the field is omitted from generated forms, and the generated create, PATCH and PUT routes ignore a value sent for it (reads of it are unchanged); inert on fields for which no form is generated (e.g. projection/derived fields).
    @instructionstringnometaobjects-promptFR-010: a short instruction for this field, shown in the generated output-format prompt fragment.
    @mutabilitystringnoreadWrite, writeOnce, readOnlymetaobjects-core-typesFR-037 R1: who may write this field, and when. 'readWrite' (the default when absent) — the caller may set it on create and change it on update. 'writeOnce' — the caller sets it on create; it is excluded from the update shape thereafter, so a value presented on PATCH is ignored rather than rejected. 'readOnly' — nobody writes it: codegen emits no setter / writable property, the persistence layer skips the column on INSERT/UPDATE, and Zod/Pydantic/class-validator schemas omit it from input variants; the value is populated by the database (computed column, default expression, trigger), by replication, or by another external owner. The three are mutually exclusive modes of ONE axis — who may write, and when — so the illegal pair is unrepresentable and inheritance has a total order: a subtype may TIGHTEN an inherited mode (readWrite < writeOnce < readOnly) and never loosen it (ERR_MUTABILITY_DOWNGRADE). Pairing a non-readWrite mode with @autoSet is ERR_MUTABILITY_AUTOSET_CONFLICT: @autoSet already says the SERVER supplies the value, which is a different axis from who may write it.
    @requiredbooleannometaobjects-core-typesWhen true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction.
    @sortablebooleannometaobjects-uiWhen true, the field is exposed in generated CRUD sort allowlists. Inherits from @filterable by default; set false to opt out.
    @sortableDefaultOrderstringnoasc, descmetaobjects-uiDirection a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'.
    @uniquebooleannometaobjects-core-typesWhen true, the field gets a column-level UNIQUE constraint.
    @xmlTextbooleannometaobjects-promptWhen true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json.
    +

    Allowed children

    +
      +
    • origin.* — 0..*
    • +
    • validator.* — 0..*
    • +
    • view.* — 0..*
    • +

    field.enum

    String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.

    Owning provider: metaobjects-core-types

    diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index 847f0ea66e..57bb390cbe 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -184,6 +184,14 @@ "children": [ { "type": "attr", "subType": "boolean", "name": "lenient", "min": 0, "max": 1, "description": "#234: opt this field out of strict well-formedness enforcement. When true, codegen binds a plain string (no URL/IP validator, no native URI/InetAddress type; field.inet uses a text column, not the native inet type) so a not-strictly-valid value round-trips unchanged. Default (absent/false) is strict: an absolute-scheme URI / an IPv4-or-IPv6 literal." } ] + }, + { + "type": "field", + "subType": "duration", + "dataType": "string", + "extendsBase": true, + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit." } ] } From 30254a8ef215ea9b336d4341e17af0c8a472ba9f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Tue, 3 Nov 2026 12:19:42 -0500 Subject: [PATCH 026/267] feat(field): field.duration gets each stack's full capability Per-stack limits only, no cross-port normalisation: - No shared upper bound: each port is limited by its own type (TimeSpan, timedelta; java.time.Duration is effectively unbounded) and refuses, never wraps. - SQLite, D1 and MySQL store a 64-bit integer count of microseconds (Django's DurationField precedent); Postgres keeps its native interval. Both order and compare as the span, so duration takes every ordered filter op (gt, gte, lt, lte) and sort on every database; Cube exposes it as seconds. - C# on Npgsql maps each duration through NpgsqlInterval and refuses a month or year part and a day count past TimeSpan, which Npgsql's own TimeSpan read silently drops or wraps. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +- docs/features/field-types.md | 11 +- docs/ports/csharp.md | 15 +- .../runtime/drizzle-fastify/filter-parser.ts | 10 +- .../codegen/runtime/duration-wire.ts | 2 +- .../codegen/templates/duration-wire-helper.ts | 262 +++++++++--------- .../codegen/templates/zod-validators.ts | 4 +- .../runtime/drizzle-fastify/filter-parser.ts | 10 +- .../showcase/codegen/runtime/duration-wire.ts | 2 +- .../codegen/templates/duration-wire-helper.ts | 262 +++++++++--------- .../codegen/templates/zod-validators.ts | 4 +- .../filter-ops-matrix/input/meta.matrix.json | 1 + .../conformance/filter-ops-matrix/script.json | 3 + .../expected/openapi.json | 36 +++ .../expected/openapi.json | 36 +++ .../all-fields/expected/openapi.json | 36 +++ fixtures/duration-wire/README.md | 14 +- fixtures/duration-wire/vectors.json | 26 +- fixtures/metamodel-docs/expected/INDEX.md | 2 +- .../metamodel-docs/expected/types/field.md | 2 +- .../canonical/schema.mysql.sql | 2 +- .../canonical/schema.sqlite.sql | 2 +- .../registry-conformance/coverage-report.json | 1 - .../expected-registry.json | 2 +- fixtures/validation-conformance/README.md | 3 +- fixtures/validation-conformance/cases.json | 3 +- .../runtime-errors.json | 9 - .../DurationWireTests.cs | 113 +++++--- .../ValidationConformanceTests.cs | 2 +- .../Generators/DbContextGenerator.cs | 212 +++++++++++--- .../Generators/EntityGenerator.cs | 41 +-- .../Runtime/DurationWire.cs | 39 +-- .../Api/DurationWireGeneratedApiTests.cs | 137 ++++++--- .../Generated/AppDbContext.g.cs | 120 +++++++- .../Generated/DurationWire.g.cs | 39 +-- .../MetaObjects/Core/Query/QueryConstants.cs | 6 +- .../MetaObjects/SpecMetamodel/field.json | 2 +- .../kotlin/KotlinDurationWireEmitter.kt | 52 ++-- .../kotlin/KotlinExposedTableGenerator.kt | 45 +-- .../kotlin/KotlinDurationWireTest.kt | 20 +- .../spring/runtime/CanonicalDuration.java | 37 +-- .../runtime/CanonicalDurationSerializer.java | 7 +- .../SpringDurationWireCompileRunTest.java | 7 +- .../spring/runtime/DurationWireTest.java | 16 +- .../kotlin/DurationOrderingScenarioTest.kt | 38 +++ .../kotlin/tables/MetaDurationColumnType.kt | 22 +- .../GeneratedDurationRoundTripTest.kt | 135 +++++++++ .../duration-ordering/duration-ordering.yaml | 71 +++++ .../DurationOrderingScenarioTests.java | 59 ++++ .../duration-ordering/duration-ordering.yaml | 70 +++++ .../com/metaobjects/field/DurationWire.java | 59 ++-- .../java/com/metaobjects/query/FilterOps.java | 5 +- .../field/DurationWireVectorsTest.java | 33 ++- .../manager/db/codec/JdbcCodecs.java | 56 ++-- .../db/codec/JdbcCodecRoundTripTest.java | 45 +-- .../generators/filter_allowlist_generator.py | 7 +- .../codegen/runtime/duration_wire.py | 73 +++-- .../metaobjects/loader/validation_passes.py | 9 +- .../python/src/metaobjects/runtime/dialect.py | 18 +- .../src/metaobjects/runtime/object_manager.py | 5 +- .../src/metaobjects/spec_metamodel/field.json | 2 +- .../tests/codegen/test_duration_codegen.py | 13 +- .../integration/test_duration_postgres.py | 69 +++++ .../tests/runtime/test_duration_wire.py | 48 +++- .../runtime/test_object_manager_duration.py | 69 +++-- .../packages/codegen-ts/src/column-mapper.ts | 18 +- .../codegen-ts/src/contract/field-schema.ts | 1 - .../codegen-ts/src/cube/cube-members.ts | 17 +- .../src/prisma/build-prisma-schema.ts | 4 +- .../src/templates/duration-wire-helper.ts | 262 +++++++++--------- .../src/templates/zod-validators.ts | 4 +- .../duration-json-schema-pattern.test.ts | 11 +- .../test/cube/build-cube-model.test.ts | 10 +- .../test/drizzle-duration-column.test.ts | 25 +- .../test/duration-wire-helper.test.ts | 99 ++++--- .../test/prisma/prisma-schema.test.ts | 7 +- .../test/templates/filter-allowlist.test.ts | 17 ++ .../test/zod-validators-execution.test.ts | 6 +- .../src/canonical-schema-mysql.ts | 2 +- .../metadata/src/core/field/duration-wire.ts | 51 ++-- .../src/core/field/field-constants.ts | 2 +- .../core/field/field-definition.embedded.ts | 2 +- .../src/core/query/query-constants.ts | 7 +- .../packages/migrate-ts/src/emit/sqlite.ts | 2 +- .../migrate-ts/src/expected-schema.ts | 11 +- .../test/unit/duration-column.test.ts | 39 +++ .../src/drizzle-fastify/filter-parser.ts | 10 +- .../packages/runtime-ts/src/duration-wire.ts | 2 +- .../packages/runtime-ts/src/query-builder.ts | 12 +- .../packages/runtime-ts/src/type-coercer.ts | 17 +- .../test/duration-wire-vectors.test.ts | 25 +- .../test/object-manager-duration.test.ts | 24 +- .../src/templates/duration-wire-helper.ts | 262 +++++++++--------- .../src/templates/zod-validators.ts | 4 +- site-reference/index.html | 2 +- site-reference/types/field.html | 2 +- spec/metamodel/field.json | 2 +- 97 files changed, 2347 insertions(+), 1182 deletions(-) create mode 100644 server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt create mode 100644 server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/duration/GeneratedDurationRoundTripTest.kt create mode 100644 server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml create mode 100644 server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java create mode 100644 server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml create mode 100644 server/python/tests/integration/test_duration_postgres.py create mode 100644 server/typescript/packages/migrate-ts/test/unit/duration-column.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f59acb350b..39dccc25ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,13 +14,14 @@ here.** - **`field.duration`: a fixed-length span of time, in every port.** `TimeSpan` in C#, `java.time.Duration` in Java and Kotlin, `timedelta` in Python, and a string in TypeScript; - a Postgres `interval` column, text on SQLite and MySQL. The wire form is an ISO-8601 duration + a Postgres `interval` column, and a 64-bit integer of microseconds on SQLite, D1 and MySQL, so + sorting and range filters follow the span on every database. The wire form is an ISO-8601 duration of days, hours, minutes and seconds, and every port writes the same canonical form (`PT1H30M`, `PT26H`, `-PT1M30S`, `PT0S`); years, months and weeks are refused. Postgres does not accept a signed ISO-8601 duration as input, so a value bound as text, and a declared `@default`, use - its own `HH:MM:SS` spelling, which it returns unchanged. Filters: `eq`, `ne`, `in`, `isNull`. - Shared vectors in `fixtures/duration-wire/`; see `docs/features/field-types.md`. A span is at - most 256204778 hours (the largest a .NET `TimeSpan` holds) in every port. + its own `HH:MM:SS` spelling, which it returns unchanged. Filters: every numeric operator. + Shared vectors in `fixtures/duration-wire/`; see `docs/features/field-types.md`. Each port is + limited only by its own duration type and each database by its own column. - An owned (ejected) generator copy from before this release does not know `field.duration`: re-eject it (`meta eject --force`, or merge) before a model uses one. Models without a duration are unaffected. diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 72dc593707..428aee977b 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -55,11 +55,12 @@ Five rows need a footnote: `[-]PT[nH][nM][n[.f]S]`: hours are never folded into days (`PT26H`), there are at most six fractional digits, and zero is `PT0S`. Every port reads that form and also a leading day count (`P1DT2H`). Years, months and weeks are refused, and so are lowercase designators and - fractional hours. The column is a Postgres `interval` and text elsewhere, where it holds the - canonical form, so equal spans are equal strings. Filters take `eq`, `ne`, `in` and - `isNull`; range filters are not offered yet, because a text column cannot order the - strings. For the same reason a `sort` on a duration orders by span on Postgres but by - text on SQLite and MySQL (`PT10S` before `PT9S`). The + fractional hours. The column is a Postgres `interval`; SQLite, D1 and MySQL store a 64-bit + integer count of microseconds, the way Django stores a `DurationField` outside Postgres. Both + order and compare as the span does, so every filter operator a number has (`eq`, `ne`, `gt`, + `gte`, `lt`, `lte`, `in`, `isNull`) and `sort` work on every database. There is no shared upper + bound: each port is limited only by its own type (a .NET `TimeSpan`, a Python `timedelta`) and + each database by its own column, and refuses what it cannot hold rather than wrapping it. The rule and its cross-port vectors are in [`fixtures/duration-wire/`](../../fixtures/duration-wire/). - **`field.map`** is the typed dict: string keys, and a value type set by exactly one of diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index c775647d13..eca44ae267 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -369,17 +369,16 @@ attributes or delete `DecimalWire.g.cs` to change the output: they also check in and regenerate. A `field.duration` is a `TimeSpan` carrying `[DurationWire.Iso]`, which reads and writes the -ISO-8601 form every port shares (`PT1H30M`) instead of System.Text.Json's `01:30:00`. Npgsql maps -it to an `interval` column; on any other provider a value converter stores the canonical string. +ISO-8601 form every port shares (`PT1H30M`) instead of System.Text.Json's `01:30:00`. On Npgsql it +is an `interval` column. EF reads an interval through Npgsql's own `TimeSpan` conversion, which (as +of Npgsql 8.0.5) silently drops a negative month or year part (`'-1 mons'` reads as `PT0S`) and +wraps a day count past `TimeSpan`'s range, so the generated context maps each duration column +through `NpgsqlInterval` instead and refuses either one on read. On any other provider a value +converter stores the 64-bit microsecond count, so sorting and range filters follow the span. +`TimeSpan`'s own range is the only limit: a longer span is refused, never wrapped. `DurationWire.g.cs` is emitted once per namespace that has a duration, and an owned `routes` generator also copies `DurationWire.cs`. -One limit is Npgsql's, not the generated code's: EF reads an `interval` through Npgsql's own -`TimeSpan` conversion, which (as of Npgsql 8.0.5) refuses a positive month part but silently drops -a negative month or year part (`'-1 mons'` reads as `PT0S`) and wraps a day count past `TimeSpan`'s -range. No MetaObjects writer stores either, so only a row written by hand can hold one; the other -ports refuse it on read. - ### `Names` — the physical names, as constants `names` is opt-in — list `new MetaObjects.Codegen.Generators.NamesGenerator()` in diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts index 4a438c3e9c..00d2177ab1 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-parser.ts @@ -17,7 +17,7 @@ import { } from "./filter-value-format.js"; import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; import { canonicalDecimal } from "../decimal-wire.js"; -import { formatDuration, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; +import { durationToStoredMicros, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -345,12 +345,12 @@ function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: stri if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; return dialect === "sqlite" ? Number(canonical) : canonical; } - // A duration bound is spelled the way the column stores it: the canonical string on a text - // column (SQLite, MySQL), so `PT90M` equals a stored `PT1H30M`; the interval spelling on - // Postgres, which compares spans and refuses a signed ISO-8601 duration. + // A duration bound is spelled the way the column stores it: the microsecond integer on SQLite / + // D1 / MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). Both + // compare and order as the span does. if (rule.format === FIELD_SUBTYPE_DURATION) { const micros = parseDurationLiteral(s) as bigint; - return dialect === "sqlite" || dialect === "mysql" ? formatDuration(micros) : formatPostgresInterval(micros); + return dialect === "sqlite" || dialect === "mysql" ? durationToStoredMicros(micros) : formatPostgresInterval(micros); } // A timestamp bound is compared in the same UTC spelling the generated schemas store: // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. diff --git a/examples/advanced-modeling/codegen/runtime/duration-wire.ts b/examples/advanced-modeling/codegen/runtime/duration-wire.ts index dc820cd628..7f5ea68bde 100644 --- a/examples/advanced-modeling/codegen/runtime/duration-wire.ts +++ b/examples/advanced-modeling/codegen/runtime/duration-wire.ts @@ -2,5 +2,5 @@ // re-exported here so the runtime's callers import it beside the decimal wire helpers. export { DURATION_PATTERN, DURATION_RE, parseDurationLiteral, formatDuration, formatPostgresInterval, - canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, + canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, durationToStoredMicros, } from "@metaobjectsdev/metadata"; diff --git a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts index 77267db3f7..a000f6de0e 100644 --- a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts +++ b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts @@ -6,8 +6,12 @@ // // Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left // out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. -// The emitted code holds a span as whole seconds plus microseconds (two JS numbers of one sign), -// so it needs no bigint and is exact for any span below 2^53 seconds. +// +// The emitted code counts a span in microseconds as a `bigint`, so it has no limit of its own: a +// span is as long as the stack it is stored in allows. The only limit here is a column's — the +// 64-bit integer a SQLite, D1 or MySQL column holds (refused past it, never wrapped). Postgres's +// interval has its own range, which Postgres enforces. The emitted code calls `BigInt(...)` and +// writes no bigint literal, so it needs the ES2020 `BigInt` global and nothing newer. import { code, imp, type Code } from "@metaobjectsdev/codegen-ts/engine"; import { DURATION_PATTERN } from "@metaobjectsdev/metadata"; @@ -23,67 +27,82 @@ export const ZOD_DURATION_EXPR = `z.string().regex(${DURATION_REGEX_LITERAL})`; export const DURATION_WRITE_HELPER = "durationWrite"; /** The Zod expression of a duration WRITE field: the accepted form, rewritten to the canonical one, - * so equal spans are stored as equal strings on every dialect. */ + * so equal spans are equal strings on the wire and in a jsonb value object. */ export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; -/** The largest span a field.duration holds, in whole seconds: 256204778 hours, the largest whole - * hour a .NET TimeSpan holds (fixtures/duration-wire). Every port refuses one microsecond more, so - * a value one port accepts every port can read. It also bounds the emitted arithmetic: 9.2e11 - * seconds is far below 2^53, so seconds and microseconds stay exact JS integers and never format - * in exponent notation. */ -export const DURATION_MAX_SECONDS = 256204778 * 3600; - /** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ -const ISO_PARTS_SOURCE = "/^([-+])?P(?!$)(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d{1,9}))?S)?)?$/"; +const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$/`; + +/** The default (`IntervalStyle = postgres`) text of a Postgres interval: signed year / mon / day + * parts, then an optionally signed `H:MM:SS[.ffffff]`. */ +const PG_INTERVAL_SOURCE = String.raw`/^(?:([-+]?\d+) years? ?)?(?:([-+]?\d+) mons? ?)?(?:([-+]?\d+) days? ?)?(?:([-+])?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/`; + +/** Indent every line of `block` by `n` spaces (blank lines stay blank). */ +function indent(block: string, n: number): string { + const pad = " ".repeat(n); + return block.split("\n").map((l) => (l === "" ? l : pad + l)).join("\n"); +} + +/** Microsecond unit constants, as `BigInt(...)` calls (no bigint literal). */ +const UNIT_LINES = [ + "const ZERO = BigInt(0);", + "const SECOND = BigInt(1000000);", + "const MINUTE = BigInt(60000000);", + "const HOUR = BigInt(3600000000);", + "const DAY = BigInt(86400000000);", +].join("\n"); -/** Lines formatting a span of `s` whole seconds plus `us` microseconds (one sign) canonically. */ -const ISO_FORMAT_LINES = [ - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - " const h = Math.floor(a / 3600);", - " const m = Math.floor((a % 3600) / 60);", - " const sec = a % 60;", +/** `parseIso(text)`: the microseconds of an accepted ISO-8601 duration, or undefined. */ +const PARSE_ISO_FN = [ + "const parseIso = (text: string): bigint | undefined => {", + ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, + " if (p === null) return undefined;", + " const mag = BigInt(p[2] ?? 0) * DAY + BigInt(p[3] ?? 0) * HOUR + BigInt(p[4] ?? 0) * MINUTE", + ' + BigInt(p[5] ?? 0) * SECOND + BigInt((p[6] ?? "").padEnd(6, "0").slice(0, 6));', + ' return p[1] === "-" ? -mag : mag;', + "};", +].join("\n"); + +/** `isoText(micros)`: the canonical wire form. */ +const ISO_TEXT_FN = [ + "const isoText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + " const s = rest / SECOND;", + " const f = rest % SECOND;", ' let out = "PT";', - ' if (h > 0) out += h + "H";', - ' if (m > 0) out += m + "M";', - ' if (sec > 0 || f > 0) out += sec + (f > 0 ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', + ' if (h > ZERO) out += String(h) + "H";', + ' if (m > ZERO) out += String(m) + "M";', + ' if (s > ZERO || f > ZERO) out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', ' if (out === "PT") return "PT0S";', ' return neg ? "-" + out : out;', -]; - -/** Lines matching `text` against the accepted form: `p` (null when it is not one), then `mag` whole - * seconds and `frac` microseconds of the span's magnitude. Read only after a null check on `p`. */ -const ISO_MATCH_LINES = [ - ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, - " const mag = p === null ? 0 : Number(p[2] ?? 0) * 86400 + Number(p[3] ?? 0) * 3600 + Number(p[4] ?? 0) * 60 + Number(p[5] ?? 0);", - ' const frac = p === null ? 0 : Number((p[6] ?? "").padEnd(6, "0").slice(0, 6));', -]; + "};", +].join("\n"); export const DURATION_WRITE_HELPER_DECL = [ "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", - " * fractional digits (truncated), one leading \"-\" for a negative span. A span past 256204778 hours", - " * (the bound every port holds) is a validation issue. Generated. */", - `function ${DURATION_WRITE_HELPER}(text: string, ctx: z.RefinementCtx): string {`, - ...ISO_MATCH_LINES, - " if (p === null) return text;", - ` if (mag > ${DURATION_MAX_SECONDS} || (mag === ${DURATION_MAX_SECONDS} && frac > 0)) {`, - ' ctx.addIssue({ code: "custom", message: "Duration out of range: at most 256204778 hours" });', - " return z.NEVER;", - " }", - ' const s = p[1] === "-" ? -mag : mag;', - ' const us = p[1] === "-" ? -frac : frac;', - ...ISO_FORMAT_LINES, + " * fractional digits (truncated), one leading \"-\" for a negative span. Counted in bigint", + " * microseconds, so any length is exact. Generated. */", + `function ${DURATION_WRITE_HELPER}(text: string): string {`, + indent(UNIT_LINES, 2), + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + " const micros = parseIso(text);", + " return micros === undefined ? text : isoText(micros);", "}", ].join("\n"); /** The physical column type a duration column's `customType` declares, per dialect: the - * Postgres-native interval; TEXT on SQLite; VARCHAR(64) on MySQL (the persistence corpus's - * canonical schemas, and what `meta migrate` writes). */ + * Postgres-native interval; a 64-bit integer count of microseconds on SQLite / D1 (INTEGER) and + * MySQL (BIGINT) — the persistence corpus's canonical schemas, and what `meta migrate` writes. */ export function durationColumnDataType(dialect: Dialect): string { - return dialect === "postgres" ? "interval" : dialect === "mysql" ? "varchar(64)" : "text"; + return dialect === "postgres" ? "interval" : dialect === "mysql" ? "bigint" : "integer"; } /** @@ -92,92 +111,87 @@ export function durationColumnDataType(dialect: Dialect): string { * declaration. Exported so a test can evaluate the exact text a generated module carries. * * - `toDriver` binds what the column holds: on Postgres the interval spelling `[-]HH:MM:SS[.f]` - * (Postgres refuses a signed ISO-8601 duration as interval input, and returns a value written - * this way in exactly this spelling); on SQLite and MySQL the canonical ISO-8601 string, so equal - * spans are equal strings. It takes the value in either spelling — an ISO-8601 duration (what the - * generated write schema hands it), or the Postgres interval text runtime-ts already binds a - * filter operand or a write in — and throws for anything else. - * - `fromDriver` reads what the driver returns — ISO-8601 text, Postgres interval text in the - * default `IntervalStyle`, or a node-postgres interval object — as the canonical ISO-8601 form. - * An interval with a year or month part is not a fixed-length span: reading one throws. + * (Postgres refuses a signed ISO-8601 duration, and returns a value written this way in exactly + * this spelling); on SQLite, D1 and MySQL the microsecond count — a number when it is a safe + * integer, else a bigint — refused past the 64-bit range, which is that column's limit. It takes + * the value as an ISO-8601 duration (what the generated write schema hands it), or as what + * runtime-ts already binds a filter operand in (the Postgres text; the microsecond integer), and + * throws for anything else. + * - `fromDriver` reads what the driver returns — the microsecond integer (a number, a bigint or a + * digit string), ISO-8601 text, Postgres interval text in the default `IntervalStyle`, or a + * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or + * month part is not a fixed-length span: reading one throws. */ export function durationColumnDeclParts(dialect: Dialect): [string, string] { - const bindPostgres = dialect === "postgres"; + const postgres = dialect === "postgres"; const before = [ - "/** A field.duration column. Binds " + (bindPostgres - ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration)," - : "the canonical ISO-8601 duration,"), - " * reads any interval back as the canonical ISO-8601 duration, and refuses an interval with a", - " * year or month part. Generated. */", + "/** A field.duration column. Binds " + (postgres + ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" + : "the span as a 64-bit integer count of microseconds (refused past that range);"), + " * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month", + " * part. Counted in bigint microseconds, so the column is the only limit. Generated. */", `const ${DURATION_COLUMN_FN} = (() => {`, - " const MICROS = 1000000;", - ` const MAX_SECONDS = ${DURATION_MAX_SECONDS};`, - " // A span normalised to one sign, refused past 256204778 hours (the bound every port holds).", - " const span = (s: number, us: number): [number, number] => {", - " s += Math.trunc(us / MICROS);", - " us %= MICROS;", - " if (s > 0 && us < 0) {", - " s -= 1;", - " us += MICROS;", - " } else if (s < 0 && us > 0) {", - " s += 1;", - " us -= MICROS;", - " }", - " const a = Math.abs(s);", - " if (!(a < MAX_SECONDS || (a === MAX_SECONDS && us === 0))) {", - ' throw new Error("a field.duration holds at most 256204778 hours (one microsecond more is refused)");', - " }", - " return [s, us];", - " };", - " const iso = (text: string): [number, number] | undefined => {", - ...ISO_MATCH_LINES.map((l) => " " + l), - " if (p === null) return undefined;", - ' return p[1] === "-" ? [-mag, -frac] : [mag, frac];', - " };", - " const isoText = ([s, us]: [number, number]): string => {", - ...ISO_FORMAT_LINES.map((l) => " " + l), - " };", - " const pgText = ([s, us]: [number, number]): string => {", - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - ' const two = (n: number): string => String(n).padStart(2, "0");', - ' let out = two(Math.floor(a / 3600)) + ":" + two(Math.floor((a % 3600) / 60)) + ":" + two(a % 60);', - ' if (f > 0) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', - ' return neg ? "-" + out : out;', - " };", - " const notFixed = (v: unknown): Error =>", - ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', - " const read = (v: unknown): [number, number] => {", - ' if (typeof v === "string") {', - " const fromIso = iso(v);", - " if (fromIso !== undefined) return span(fromIso[0], fromIso[1]);", - " const p = v.length === 0 ? null", - " : /^(?:([-+]?\\d+) years? ?)?(?:([-+]?\\d+) mons? ?)?(?:([-+]?\\d+) days? ?)?(?:([-+])?(\\d+):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?)?$/.exec(v);", - ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', - " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", - ' const t = p[5] === undefined ? 0 : Number(p[5]) * 3600 + Number(p[6]) * 60 + Number(p[7]);', - ' const tu = Number((p[8] ?? "").padEnd(6, "0"));', - ' const sign = p[4] === "-" ? -1 : 1;', - " return span(Number(p[3] ?? 0) * 86400 + sign * t, sign * tu);", - " }", - ' if (v !== null && typeof v === "object") {', - " const o = v as Record;", - " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", - " const whole = (n: number | undefined): number => Math.trunc(n ?? 0);", - " return span(", - " whole(o.days) * 86400 + whole(o.hours) * 3600 + whole(o.minutes) * 60 + whole(o.seconds),", - " Math.round((o.milliseconds ?? 0) * 1000),", - " );", - " }", - ' throw new Error("not a field.duration value: " + JSON.stringify(v));', - " };", + indent(UNIT_LINES, 2), + ` const INT64_MAX = BigInt("9223372036854775807");`, + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + indent([ + "const pgText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + ' const two = (n: bigint): string => String(n).padStart(2, "0");', + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + ' let out = two(h) + ":" + two(m) + ":" + two(rest / SECOND);', + " const f = rest % SECOND;", + ' if (f > ZERO) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', + ' return neg ? "-" + out : out;', + "};", + "const stored = (micros: bigint): number | bigint => {", + " if (micros > INT64_MAX || micros < -INT64_MAX - BigInt(1)) {", + ' throw new Error("the span " + isoText(micros) + " does not fit the 64-bit microsecond column a field.duration is stored in");', + " }", + " const n = Number(micros);", + " return Number.isSafeInteger(n) ? n : micros;", + "};", + "const notFixed = (v: unknown): Error =>", + ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', + "const read = (v: unknown): bigint => {", + ' if (typeof v === "bigint") return v;', + ' if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);', + ' if (typeof v === "string") {', + " if (/^-?\\d+$/.test(v)) return BigInt(v);", + " const iso = parseIso(v);", + " if (iso !== undefined) return iso;", + ` const p = v.length === 0 ? null : ${PG_INTERVAL_SOURCE}.exec(v);`, + ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', + " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", + " let time = ZERO;", + " if (p[5] !== undefined) {", + ' time = BigInt(p[5]) * HOUR + BigInt(p[6] ?? 0) * MINUTE + BigInt(p[7] ?? 0) * SECOND + BigInt((p[8] ?? "").padEnd(6, "0"));', + ' if (p[4] === "-") time = -time;', + " }", + " return BigInt(p[3] ?? 0) * DAY + time;", + " }", + ' if (v !== null && typeof v === "object") {', + " const o = v as Record;", + " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", + " const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0));", + " // postgres-interval carries microseconds as a fractional millisecond count.", + " return whole(o.days) * DAY + whole(o.hours) * HOUR + whole(o.minutes) * MINUTE + whole(o.seconds) * SECOND", + " + BigInt(Math.round((o.milliseconds ?? 0) * 1000));", + " }", + ' throw new Error("not a field.duration value: " + JSON.stringify(v));', + "};", + ].join("\n"), 2), " return ", ].join("\n"); const after = [ - "<{ data: string; driverData: string }>({", + `<{ data: string; driverData: ${postgres ? "string" : "number | bigint | string"} }>({`, ` dataType: () => ${JSON.stringify(durationColumnDataType(dialect))},`, - ` toDriver: (value) => ${bindPostgres ? "pgText" : "isoText"}(read(value)),`, + ` toDriver: (value) => ${postgres ? "pgText" : "stored"}(read(value)),`, " fromDriver: (value) => isoText(read(value)),", " });", "})();", diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts index 1edf2ab40b..82c061b07c 100644 --- a/examples/advanced-modeling/codegen/templates/zod-validators.ts +++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts @@ -775,8 +775,8 @@ function zodFieldExpr( case FIELD_SUBTYPE_DURATION: // An ISO-8601 duration (days, hours, minutes, seconds; no years, months or weeks). A WRITE // shape rewrites it to the canonical form (duration-wire-helper.ts), so equal spans are - // equal strings in a text column and in a jsonb value object; the TPH read shape parses - // rows the column codec has already put in that form. + // equal strings on the wire and in a jsonb value object (the column codec binds the + // column's own form); the TPH read shape parses rows the codec has already put in it. if (readShape) { baseStr = ZOD_DURATION_EXPR; break; diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts b/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts index 4a438c3e9c..00d2177ab1 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/filter-parser.ts @@ -17,7 +17,7 @@ import { } from "./filter-value-format.js"; import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; import { canonicalDecimal } from "../decimal-wire.js"; -import { formatDuration, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; +import { durationToStoredMicros, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -345,12 +345,12 @@ function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: stri if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; return dialect === "sqlite" ? Number(canonical) : canonical; } - // A duration bound is spelled the way the column stores it: the canonical string on a text - // column (SQLite, MySQL), so `PT90M` equals a stored `PT1H30M`; the interval spelling on - // Postgres, which compares spans and refuses a signed ISO-8601 duration. + // A duration bound is spelled the way the column stores it: the microsecond integer on SQLite / + // D1 / MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). Both + // compare and order as the span does. if (rule.format === FIELD_SUBTYPE_DURATION) { const micros = parseDurationLiteral(s) as bigint; - return dialect === "sqlite" || dialect === "mysql" ? formatDuration(micros) : formatPostgresInterval(micros); + return dialect === "sqlite" || dialect === "mysql" ? durationToStoredMicros(micros) : formatPostgresInterval(micros); } // A timestamp bound is compared in the same UTC spelling the generated schemas store: // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. diff --git a/examples/showcase/codegen/runtime/duration-wire.ts b/examples/showcase/codegen/runtime/duration-wire.ts index dc820cd628..7f5ea68bde 100644 --- a/examples/showcase/codegen/runtime/duration-wire.ts +++ b/examples/showcase/codegen/runtime/duration-wire.ts @@ -2,5 +2,5 @@ // re-exported here so the runtime's callers import it beside the decimal wire helpers. export { DURATION_PATTERN, DURATION_RE, parseDurationLiteral, formatDuration, formatPostgresInterval, - canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, + canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, durationToStoredMicros, } from "@metaobjectsdev/metadata"; diff --git a/examples/showcase/codegen/templates/duration-wire-helper.ts b/examples/showcase/codegen/templates/duration-wire-helper.ts index 77267db3f7..a000f6de0e 100644 --- a/examples/showcase/codegen/templates/duration-wire-helper.ts +++ b/examples/showcase/codegen/templates/duration-wire-helper.ts @@ -6,8 +6,12 @@ // // Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left // out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. -// The emitted code holds a span as whole seconds plus microseconds (two JS numbers of one sign), -// so it needs no bigint and is exact for any span below 2^53 seconds. +// +// The emitted code counts a span in microseconds as a `bigint`, so it has no limit of its own: a +// span is as long as the stack it is stored in allows. The only limit here is a column's — the +// 64-bit integer a SQLite, D1 or MySQL column holds (refused past it, never wrapped). Postgres's +// interval has its own range, which Postgres enforces. The emitted code calls `BigInt(...)` and +// writes no bigint literal, so it needs the ES2020 `BigInt` global and nothing newer. import { code, imp, type Code } from "@metaobjectsdev/codegen-ts/engine"; import { DURATION_PATTERN } from "@metaobjectsdev/metadata"; @@ -23,67 +27,82 @@ export const ZOD_DURATION_EXPR = `z.string().regex(${DURATION_REGEX_LITERAL})`; export const DURATION_WRITE_HELPER = "durationWrite"; /** The Zod expression of a duration WRITE field: the accepted form, rewritten to the canonical one, - * so equal spans are stored as equal strings on every dialect. */ + * so equal spans are equal strings on the wire and in a jsonb value object. */ export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; -/** The largest span a field.duration holds, in whole seconds: 256204778 hours, the largest whole - * hour a .NET TimeSpan holds (fixtures/duration-wire). Every port refuses one microsecond more, so - * a value one port accepts every port can read. It also bounds the emitted arithmetic: 9.2e11 - * seconds is far below 2^53, so seconds and microseconds stay exact JS integers and never format - * in exponent notation. */ -export const DURATION_MAX_SECONDS = 256204778 * 3600; - /** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ -const ISO_PARTS_SOURCE = "/^([-+])?P(?!$)(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d{1,9}))?S)?)?$/"; +const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$/`; + +/** The default (`IntervalStyle = postgres`) text of a Postgres interval: signed year / mon / day + * parts, then an optionally signed `H:MM:SS[.ffffff]`. */ +const PG_INTERVAL_SOURCE = String.raw`/^(?:([-+]?\d+) years? ?)?(?:([-+]?\d+) mons? ?)?(?:([-+]?\d+) days? ?)?(?:([-+])?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/`; + +/** Indent every line of `block` by `n` spaces (blank lines stay blank). */ +function indent(block: string, n: number): string { + const pad = " ".repeat(n); + return block.split("\n").map((l) => (l === "" ? l : pad + l)).join("\n"); +} + +/** Microsecond unit constants, as `BigInt(...)` calls (no bigint literal). */ +const UNIT_LINES = [ + "const ZERO = BigInt(0);", + "const SECOND = BigInt(1000000);", + "const MINUTE = BigInt(60000000);", + "const HOUR = BigInt(3600000000);", + "const DAY = BigInt(86400000000);", +].join("\n"); -/** Lines formatting a span of `s` whole seconds plus `us` microseconds (one sign) canonically. */ -const ISO_FORMAT_LINES = [ - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - " const h = Math.floor(a / 3600);", - " const m = Math.floor((a % 3600) / 60);", - " const sec = a % 60;", +/** `parseIso(text)`: the microseconds of an accepted ISO-8601 duration, or undefined. */ +const PARSE_ISO_FN = [ + "const parseIso = (text: string): bigint | undefined => {", + ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, + " if (p === null) return undefined;", + " const mag = BigInt(p[2] ?? 0) * DAY + BigInt(p[3] ?? 0) * HOUR + BigInt(p[4] ?? 0) * MINUTE", + ' + BigInt(p[5] ?? 0) * SECOND + BigInt((p[6] ?? "").padEnd(6, "0").slice(0, 6));', + ' return p[1] === "-" ? -mag : mag;', + "};", +].join("\n"); + +/** `isoText(micros)`: the canonical wire form. */ +const ISO_TEXT_FN = [ + "const isoText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + " const s = rest / SECOND;", + " const f = rest % SECOND;", ' let out = "PT";', - ' if (h > 0) out += h + "H";', - ' if (m > 0) out += m + "M";', - ' if (sec > 0 || f > 0) out += sec + (f > 0 ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', + ' if (h > ZERO) out += String(h) + "H";', + ' if (m > ZERO) out += String(m) + "M";', + ' if (s > ZERO || f > ZERO) out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', ' if (out === "PT") return "PT0S";', ' return neg ? "-" + out : out;', -]; - -/** Lines matching `text` against the accepted form: `p` (null when it is not one), then `mag` whole - * seconds and `frac` microseconds of the span's magnitude. Read only after a null check on `p`. */ -const ISO_MATCH_LINES = [ - ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, - " const mag = p === null ? 0 : Number(p[2] ?? 0) * 86400 + Number(p[3] ?? 0) * 3600 + Number(p[4] ?? 0) * 60 + Number(p[5] ?? 0);", - ' const frac = p === null ? 0 : Number((p[6] ?? "").padEnd(6, "0").slice(0, 6));', -]; + "};", +].join("\n"); export const DURATION_WRITE_HELPER_DECL = [ "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", - " * fractional digits (truncated), one leading \"-\" for a negative span. A span past 256204778 hours", - " * (the bound every port holds) is a validation issue. Generated. */", - `function ${DURATION_WRITE_HELPER}(text: string, ctx: z.RefinementCtx): string {`, - ...ISO_MATCH_LINES, - " if (p === null) return text;", - ` if (mag > ${DURATION_MAX_SECONDS} || (mag === ${DURATION_MAX_SECONDS} && frac > 0)) {`, - ' ctx.addIssue({ code: "custom", message: "Duration out of range: at most 256204778 hours" });', - " return z.NEVER;", - " }", - ' const s = p[1] === "-" ? -mag : mag;', - ' const us = p[1] === "-" ? -frac : frac;', - ...ISO_FORMAT_LINES, + " * fractional digits (truncated), one leading \"-\" for a negative span. Counted in bigint", + " * microseconds, so any length is exact. Generated. */", + `function ${DURATION_WRITE_HELPER}(text: string): string {`, + indent(UNIT_LINES, 2), + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + " const micros = parseIso(text);", + " return micros === undefined ? text : isoText(micros);", "}", ].join("\n"); /** The physical column type a duration column's `customType` declares, per dialect: the - * Postgres-native interval; TEXT on SQLite; VARCHAR(64) on MySQL (the persistence corpus's - * canonical schemas, and what `meta migrate` writes). */ + * Postgres-native interval; a 64-bit integer count of microseconds on SQLite / D1 (INTEGER) and + * MySQL (BIGINT) — the persistence corpus's canonical schemas, and what `meta migrate` writes. */ export function durationColumnDataType(dialect: Dialect): string { - return dialect === "postgres" ? "interval" : dialect === "mysql" ? "varchar(64)" : "text"; + return dialect === "postgres" ? "interval" : dialect === "mysql" ? "bigint" : "integer"; } /** @@ -92,92 +111,87 @@ export function durationColumnDataType(dialect: Dialect): string { * declaration. Exported so a test can evaluate the exact text a generated module carries. * * - `toDriver` binds what the column holds: on Postgres the interval spelling `[-]HH:MM:SS[.f]` - * (Postgres refuses a signed ISO-8601 duration as interval input, and returns a value written - * this way in exactly this spelling); on SQLite and MySQL the canonical ISO-8601 string, so equal - * spans are equal strings. It takes the value in either spelling — an ISO-8601 duration (what the - * generated write schema hands it), or the Postgres interval text runtime-ts already binds a - * filter operand or a write in — and throws for anything else. - * - `fromDriver` reads what the driver returns — ISO-8601 text, Postgres interval text in the - * default `IntervalStyle`, or a node-postgres interval object — as the canonical ISO-8601 form. - * An interval with a year or month part is not a fixed-length span: reading one throws. + * (Postgres refuses a signed ISO-8601 duration, and returns a value written this way in exactly + * this spelling); on SQLite, D1 and MySQL the microsecond count — a number when it is a safe + * integer, else a bigint — refused past the 64-bit range, which is that column's limit. It takes + * the value as an ISO-8601 duration (what the generated write schema hands it), or as what + * runtime-ts already binds a filter operand in (the Postgres text; the microsecond integer), and + * throws for anything else. + * - `fromDriver` reads what the driver returns — the microsecond integer (a number, a bigint or a + * digit string), ISO-8601 text, Postgres interval text in the default `IntervalStyle`, or a + * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or + * month part is not a fixed-length span: reading one throws. */ export function durationColumnDeclParts(dialect: Dialect): [string, string] { - const bindPostgres = dialect === "postgres"; + const postgres = dialect === "postgres"; const before = [ - "/** A field.duration column. Binds " + (bindPostgres - ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration)," - : "the canonical ISO-8601 duration,"), - " * reads any interval back as the canonical ISO-8601 duration, and refuses an interval with a", - " * year or month part. Generated. */", + "/** A field.duration column. Binds " + (postgres + ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" + : "the span as a 64-bit integer count of microseconds (refused past that range);"), + " * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month", + " * part. Counted in bigint microseconds, so the column is the only limit. Generated. */", `const ${DURATION_COLUMN_FN} = (() => {`, - " const MICROS = 1000000;", - ` const MAX_SECONDS = ${DURATION_MAX_SECONDS};`, - " // A span normalised to one sign, refused past 256204778 hours (the bound every port holds).", - " const span = (s: number, us: number): [number, number] => {", - " s += Math.trunc(us / MICROS);", - " us %= MICROS;", - " if (s > 0 && us < 0) {", - " s -= 1;", - " us += MICROS;", - " } else if (s < 0 && us > 0) {", - " s += 1;", - " us -= MICROS;", - " }", - " const a = Math.abs(s);", - " if (!(a < MAX_SECONDS || (a === MAX_SECONDS && us === 0))) {", - ' throw new Error("a field.duration holds at most 256204778 hours (one microsecond more is refused)");', - " }", - " return [s, us];", - " };", - " const iso = (text: string): [number, number] | undefined => {", - ...ISO_MATCH_LINES.map((l) => " " + l), - " if (p === null) return undefined;", - ' return p[1] === "-" ? [-mag, -frac] : [mag, frac];', - " };", - " const isoText = ([s, us]: [number, number]): string => {", - ...ISO_FORMAT_LINES.map((l) => " " + l), - " };", - " const pgText = ([s, us]: [number, number]): string => {", - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - ' const two = (n: number): string => String(n).padStart(2, "0");', - ' let out = two(Math.floor(a / 3600)) + ":" + two(Math.floor((a % 3600) / 60)) + ":" + two(a % 60);', - ' if (f > 0) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', - ' return neg ? "-" + out : out;', - " };", - " const notFixed = (v: unknown): Error =>", - ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', - " const read = (v: unknown): [number, number] => {", - ' if (typeof v === "string") {', - " const fromIso = iso(v);", - " if (fromIso !== undefined) return span(fromIso[0], fromIso[1]);", - " const p = v.length === 0 ? null", - " : /^(?:([-+]?\\d+) years? ?)?(?:([-+]?\\d+) mons? ?)?(?:([-+]?\\d+) days? ?)?(?:([-+])?(\\d+):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?)?$/.exec(v);", - ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', - " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", - ' const t = p[5] === undefined ? 0 : Number(p[5]) * 3600 + Number(p[6]) * 60 + Number(p[7]);', - ' const tu = Number((p[8] ?? "").padEnd(6, "0"));', - ' const sign = p[4] === "-" ? -1 : 1;', - " return span(Number(p[3] ?? 0) * 86400 + sign * t, sign * tu);", - " }", - ' if (v !== null && typeof v === "object") {', - " const o = v as Record;", - " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", - " const whole = (n: number | undefined): number => Math.trunc(n ?? 0);", - " return span(", - " whole(o.days) * 86400 + whole(o.hours) * 3600 + whole(o.minutes) * 60 + whole(o.seconds),", - " Math.round((o.milliseconds ?? 0) * 1000),", - " );", - " }", - ' throw new Error("not a field.duration value: " + JSON.stringify(v));', - " };", + indent(UNIT_LINES, 2), + ` const INT64_MAX = BigInt("9223372036854775807");`, + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + indent([ + "const pgText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + ' const two = (n: bigint): string => String(n).padStart(2, "0");', + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + ' let out = two(h) + ":" + two(m) + ":" + two(rest / SECOND);', + " const f = rest % SECOND;", + ' if (f > ZERO) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', + ' return neg ? "-" + out : out;', + "};", + "const stored = (micros: bigint): number | bigint => {", + " if (micros > INT64_MAX || micros < -INT64_MAX - BigInt(1)) {", + ' throw new Error("the span " + isoText(micros) + " does not fit the 64-bit microsecond column a field.duration is stored in");', + " }", + " const n = Number(micros);", + " return Number.isSafeInteger(n) ? n : micros;", + "};", + "const notFixed = (v: unknown): Error =>", + ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', + "const read = (v: unknown): bigint => {", + ' if (typeof v === "bigint") return v;', + ' if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);', + ' if (typeof v === "string") {', + " if (/^-?\\d+$/.test(v)) return BigInt(v);", + " const iso = parseIso(v);", + " if (iso !== undefined) return iso;", + ` const p = v.length === 0 ? null : ${PG_INTERVAL_SOURCE}.exec(v);`, + ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', + " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", + " let time = ZERO;", + " if (p[5] !== undefined) {", + ' time = BigInt(p[5]) * HOUR + BigInt(p[6] ?? 0) * MINUTE + BigInt(p[7] ?? 0) * SECOND + BigInt((p[8] ?? "").padEnd(6, "0"));', + ' if (p[4] === "-") time = -time;', + " }", + " return BigInt(p[3] ?? 0) * DAY + time;", + " }", + ' if (v !== null && typeof v === "object") {', + " const o = v as Record;", + " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", + " const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0));", + " // postgres-interval carries microseconds as a fractional millisecond count.", + " return whole(o.days) * DAY + whole(o.hours) * HOUR + whole(o.minutes) * MINUTE + whole(o.seconds) * SECOND", + " + BigInt(Math.round((o.milliseconds ?? 0) * 1000));", + " }", + ' throw new Error("not a field.duration value: " + JSON.stringify(v));', + "};", + ].join("\n"), 2), " return ", ].join("\n"); const after = [ - "<{ data: string; driverData: string }>({", + `<{ data: string; driverData: ${postgres ? "string" : "number | bigint | string"} }>({`, ` dataType: () => ${JSON.stringify(durationColumnDataType(dialect))},`, - ` toDriver: (value) => ${bindPostgres ? "pgText" : "isoText"}(read(value)),`, + ` toDriver: (value) => ${postgres ? "pgText" : "stored"}(read(value)),`, " fromDriver: (value) => isoText(read(value)),", " });", "})();", diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts index 1edf2ab40b..82c061b07c 100644 --- a/examples/showcase/codegen/templates/zod-validators.ts +++ b/examples/showcase/codegen/templates/zod-validators.ts @@ -775,8 +775,8 @@ function zodFieldExpr( case FIELD_SUBTYPE_DURATION: // An ISO-8601 duration (days, hours, minutes, seconds; no years, months or weeks). A WRITE // shape rewrites it to the canonical form (duration-wire-helper.ts), so equal spans are - // equal strings in a text column and in a jsonb value object; the TPH read shape parses - // rows the column codec has already put in that form. + // equal strings on the wire and in a jsonb value object (the column codec binds the + // column's own form); the TPH read shape parses rows the codec has already put in it. if (readShape) { baseStr = ZOD_DURATION_EXPR; break; diff --git a/fixtures/conformance/filter-ops-matrix/input/meta.matrix.json b/fixtures/conformance/filter-ops-matrix/input/meta.matrix.json index e305a32cfd..ef17aea318 100644 --- a/fixtures/conformance/filter-ops-matrix/input/meta.matrix.json +++ b/fixtures/conformance/filter-ops-matrix/input/meta.matrix.json @@ -17,6 +17,7 @@ { "field.boolean": { "name": "fBoolean", "@filterable": true } }, { "field.date": { "name": "fDate", "@filterable": true } }, { "field.time": { "name": "fTime", "@filterable": true } }, + { "field.duration": { "name": "fDuration", "@filterable": true } }, { "field.timestamp": { "name": "fTimestamp", "@filterable": true } }, { "field.enum": { "name": "fEnum", "@values": ["a", "b", "c"], "@filterable": true } }, { "field.enum": { "name": "fEnumInt", "@values": ["a", "b", "c"], "@intValueMap": { "a": 0, "b": 1, "c": 2 }, "@filterable": true } }, diff --git a/fixtures/conformance/filter-ops-matrix/script.json b/fixtures/conformance/filter-ops-matrix/script.json index acd7fe8414..96f6299bf2 100644 --- a/fixtures/conformance/filter-ops-matrix/script.json +++ b/fixtures/conformance/filter-ops-matrix/script.json @@ -36,6 +36,9 @@ { "navigate": ["object:Matrix", "field:fTime"], "invoke": "field.filter-ops", "expect": { "names": ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"] } }, + { "navigate": ["object:Matrix", "field:fDuration"], + "invoke": "field.filter-ops", + "expect": { "names": ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"] } }, { "navigate": ["object:Matrix", "field:fTimestamp"], "invoke": "field.filter-ops", "expect": { "names": ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"] } }, diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json index 4b68fc234d..1b5946bbc8 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json @@ -885,6 +885,42 @@ "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." } }, + { + "name": "filter[holdFor][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, { "name": "filter[holdFor][in]", "in": "query", diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json index b6b3147ede..654aa92256 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json @@ -885,6 +885,42 @@ "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." } }, + { + "name": "filter[holdFor][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, { "name": "filter[holdFor][in]", "in": "query", diff --git a/fixtures/contract-conformance/all-fields/expected/openapi.json b/fixtures/contract-conformance/all-fields/expected/openapi.json index 39028f8de3..d1fe3174fb 100644 --- a/fixtures/contract-conformance/all-fields/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields/expected/openapi.json @@ -885,6 +885,42 @@ "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." } }, + { + "name": "filter[holdFor][gt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][gte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][lt]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, + { + "name": "filter[holdFor][lte]", + "in": "query", + "schema": { + "type": "string", + "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", + "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + } + }, { "name": "filter[holdFor][in]", "in": "query", diff --git a/fixtures/duration-wire/README.md b/fixtures/duration-wire/README.md index c965d5bc1a..a640f95d83 100644 --- a/fixtures/duration-wire/README.md +++ b/fixtures/duration-wire/README.md @@ -7,9 +7,9 @@ agree on every input, not only the ones a persistence scenario happens to write. for it. The canonical form is `[-]PT[H][M][[.]S]`: hours are never folded into days, zero components are left out, zero is `PT0S`, there are at most six fractional digits (the precision of a Postgres `interval`; more are truncated toward zero, never rounded), and a - negative duration has one leading `-`. A day (`D`) is exactly 24 hours. The magnitude is at - most 256204778 hours (about 29,000 years), the largest whole hour a .NET `TimeSpan` holds, - so a value one port accepts every port can read; one microsecond more is refused. + negative duration has one leading `-`. A day (`D`) is exactly 24 hours. There is no shared + upper bound: each port is limited only by its own type (a .NET `TimeSpan`, a `timedelta`) and + each database by its own column, and refuses what it cannot hold rather than wrapping it. - **`refused`**: input that is not a duration. Years, months and weeks are refused because a calendar span has no fixed length. So are lowercase designators, fractional hours or minutes, a comma decimal separator, per-component signs, out-of-order components and whitespace. @@ -18,8 +18,7 @@ agree on every input, not only the ones a persistence scenario happens to write. hands back a native value (Npgsql `TimeSpan`, a JDBC `PGInterval`) checks the same rule against that value. - **`postgresRefused`**: an interval with a year or month part is not a duration; reading one - is an error, never a guess at the length of a month. So is an interval past the 256204778-hour - bound. + is an error, never a guess at the length of a month. - **`postgresText`**: a canonical duration and its Postgres interval spelling, `[-]HH:MM:SS[.f]` with unbounded hours and no day part. Postgres refuses an ISO-8601 duration with a leading sign (`-PT1M30S` is "invalid input syntax for type interval"), so a port that binds a duration to @@ -27,3 +26,8 @@ agree on every input, not only the ones a persistence scenario happens to write. interval written this way is returned in exactly this spelling, so a default never drifts and a value reads back as it was written. A port whose driver binds a native type (Npgsql `TimeSpan`, a JDBC `PGInterval`, a Python `timedelta`) does not need it. +- **`storedMicros`**: a canonical duration and the integer count of microseconds a SQLite, D1 or + MySQL column stores for it (`BIGINT`; Postgres keeps its native `interval`). An integer orders and + compares as the span does, so sorting, range filters and equality are right on every database. + This is how Django stores a `DurationField` outside Postgres. The 64-bit column holds about + 2.56 billion hours; a port refuses to bind a longer span there. diff --git a/fixtures/duration-wire/vectors.json b/fixtures/duration-wire/vectors.json index ef20e238e4..2bf300c4ce 100644 --- a/fixtures/duration-wire/vectors.json +++ b/fixtures/duration-wire/vectors.json @@ -19,9 +19,7 @@ { "in": "-PT90S", "out": "-PT1M30S" }, { "in": "-P1DT1H", "out": "-PT25H" }, { "in": "PT0.0000001S", "out": "PT0S" }, - { "in": "PT876000H", "out": "PT876000H" }, - { "in": "PT256204778H", "out": "PT256204778H" }, - { "in": "-P10675199DT2H", "out": "-PT256204778H" } + { "in": "PT876000H", "out": "PT876000H" } ], "refused": [ "", @@ -43,11 +41,7 @@ " PT1H", "PT-1H", "--PT1H", - "PT1M1H", - "PT256204778H0.000001S", - "PT256204779H", - "P10675200D", - "-PT256204779H" + "PT1M1H" ], "postgres": [ { "in": "01:30:00", "out": "PT1H30M" }, @@ -62,17 +56,14 @@ { "in": "-1 days", "out": "-PT24H" }, { "in": "-1 days +02:00:00", "out": "-PT22H" }, { "in": "1 day -01:00:00", "out": "PT23H" }, - { "in": "876000:00:00", "out": "PT876000H" }, - { "in": "256204778:00:00", "out": "PT256204778H" } + { "in": "876000:00:00", "out": "PT876000H" } ], "postgresRefused": [ "1 year", "2 mons", "1 year 2 mons 3 days 04:05:06", "1 mon 00:00:01", - "abc", - "256204779:00:00", - "10675200 days" + "abc" ], "postgresText": [ { "in": "PT1H30M", "out": "01:30:00" }, @@ -83,5 +74,14 @@ { "in": "PT26H", "out": "26:00:00" }, { "in": "-PT26H0.5S", "out": "-26:00:00.5" }, { "in": "PT876000H", "out": "876000:00:00" } + ], + "storedMicros": [ + { "in": "PT0S", "out": "0" }, + { "in": "PT0.000001S", "out": "1" }, + { "in": "PT1.5S", "out": "1500000" }, + { "in": "PT1H30M", "out": "5400000000" }, + { "in": "-PT1M30S", "out": "-90000000" }, + { "in": "PT26H", "out": "93600000000" }, + { "in": "PT876000H", "out": "3153600000000000" } ] } diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 7292ec4dc0..2e118b6217 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -34,7 +34,7 @@ children and the cardinality of that subtype. Documentation attributes | `field.date` | Calendar date (no time-of-day). Binds to the native date/temporal type; DB column is DATE. | [types/field.md#fielddate](types/field.md#fielddate) | | `field.decimal` | Precision-exact decimal (use @precision/@scale). Native TS binding is string (lossless); DB column is NUMERIC(p,s); the wire form is a string. Classified DATA_TYPE_STRING so an exact decimal is never silently rounded through a double. | [types/field.md#fielddecimal](types/field.md#fielddecimal) | | `field.double` | Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/number type; DB column is DOUBLE PRECISION. Not for money — use field.currency or field.decimal. | [types/field.md#fielddouble](types/field.md#fielddouble) | -| `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. | [types/field.md#fieldduration](types/field.md#fieldduration) | +| `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. | [types/field.md#fieldduration](types/field.md#fieldduration) | | `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. | [types/field.md#fieldenum](types/field.md#fieldenum) | | `field.float` | Single-precision floating point. Binds to the native double/number type (TS has no distinct float); DB column is REAL. Not for money. | [types/field.md#fieldfloat](types/field.md#fieldfloat) | | `field.inet` | An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IPv4-or-IPv6 literal validator (a Zod regex union in TS — z.string().ip() was removed in Zod 4 — native IP-type parsing in the other ports); add @lenient to bind a plain string with no validator. v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4\|ipv6 value-constraint. | [types/field.md#fieldinet](types/field.md#fieldinet) | diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index 6145b3aae4..637f59fb34 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -216,7 +216,7 @@ Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/nu ### field.duration -A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. +A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. **Owning provider:** metaobjects-core-types diff --git a/fixtures/persistence-conformance/canonical/schema.mysql.sql b/fixtures/persistence-conformance/canonical/schema.mysql.sql index 0aeada6a40..3f2037f6fc 100644 --- a/fixtures/persistence-conformance/canonical/schema.mysql.sql +++ b/fixtures/persistence-conformance/canonical/schema.mysql.sql @@ -102,7 +102,7 @@ CREATE TABLE `all_types` ( `uriVal` VARCHAR(255) NOT NULL, `inetVal` VARCHAR(45) NOT NULL, `inet6Val` VARCHAR(45) NOT NULL, - `durationVal` VARCHAR(64), + `durationVal` BIGINT, `settings` JSON, `labels` JSON ); diff --git a/fixtures/persistence-conformance/canonical/schema.sqlite.sql b/fixtures/persistence-conformance/canonical/schema.sqlite.sql index 2a1615c334..c61ed55174 100644 --- a/fixtures/persistence-conformance/canonical/schema.sqlite.sql +++ b/fixtures/persistence-conformance/canonical/schema.sqlite.sql @@ -133,7 +133,7 @@ CREATE TABLE "all_types" ( "uriVal" TEXT NOT NULL, "inetVal" TEXT NOT NULL, "inet6Val" TEXT NOT NULL, - "durationVal" TEXT, + "durationVal" INTEGER, "settings" TEXT, "labels" TEXT, CONSTRAINT "all_types_enumVal_chk" CHECK ("enumVal" IN ('LOW', 'MEDIUM', 'HIGH')), diff --git a/fixtures/registry-conformance/coverage-report.json b/fixtures/registry-conformance/coverage-report.json index ac4931549c..898c776a48 100644 --- a/fixtures/registry-conformance/coverage-report.json +++ b/fixtures/registry-conformance/coverage-report.json @@ -98,7 +98,6 @@ "dbColumnType", "default", "example", - "filterable", "formExclude", "instruction", "mutability", diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index e81411218b..bbb82ec019 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1027,7 +1027,7 @@ { "type": "field", "subType": "duration", - "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit.", "attrs": [ { diff --git a/fixtures/validation-conformance/README.md b/fixtures/validation-conformance/README.md index 72f93ff2c2..778245d519 100644 --- a/fixtures/validation-conformance/README.md +++ b/fixtures/validation-conformance/README.md @@ -157,8 +157,7 @@ runners wrap the bind step so a native-parse failure maps to `valid=false`. `Account.holdFor` (`field.duration`, OPTIONAL) pins the duration accept/reject verdicts. ACCEPT an ISO-8601 duration of days, hours, minutes and seconds (`PT1H30M`, `P1DT2H`, `-PT30S`, `PT0.5S`, `PT0S`). REJECT a calendar span (`P1M`, `P1Y`, `P2W`), a clock form (`1:30:00`), a fractional hour -(`PT1.5H`), lowercase designators, a `T` with no component (`PT`), and a span past the -256204778-hour bound (`PT256204779H`). The full rule, with the +(`PT1.5H`), lowercase designators, and a `T` with no component (`PT`). The full rule, with the canonical form every port writes, is in [`fixtures/duration-wire/`](../duration-wire/); a port that binds a native duration type (`TimeSpan`, `java.time.Duration`, `timedelta`) still refuses what that type's own parser would accept beyond this form. diff --git a/fixtures/validation-conformance/cases.json b/fixtures/validation-conformance/cases.json index a09f1dacba..f2d46e7303 100644 --- a/fixtures/validation-conformance/cases.json +++ b/fixtures/validation-conformance/cases.json @@ -121,7 +121,6 @@ { "name": "duration-reject-clock", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "1:30:00" }, "expectValid": false }, { "name": "duration-reject-fractional-hours", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT1.5H" }, "expectValid": false }, { "name": "duration-reject-lowercase", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "pt1h" }, "expectValid": false }, - { "name": "duration-reject-empty-time", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT" }, "expectValid": false }, - { "name": "duration-reject-too-long", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT256204779H" }, "expectValid": false } + { "name": "duration-reject-empty-time", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT" }, "expectValid": false } ] } diff --git a/fixtures/validation-conformance/runtime-errors.json b/fixtures/validation-conformance/runtime-errors.json index 5aefbc0c5c..acc01d2df8 100644 --- a/fixtures/validation-conformance/runtime-errors.json +++ b/fixtures/validation-conformance/runtime-errors.json @@ -270,15 +270,6 @@ "expected": "duration", "received": "PT" } - ], - "duration-reject-too-long": [ - { - "field": "holdFor", - "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", - "expected": "duration", - "received": "PT256204779H" - } ] } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs index c9550abcc9..6bdbf7d40d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs @@ -97,24 +97,39 @@ public void Null_crosses_as_null_and_a_tick_below_a_microsecond_truncates_toward Assert.Equal("-PT1M30S", DurationWire.Format(TimeSpan.FromSeconds(-90))); } + public static TheoryData StoredMicrosVectors() + { + var data = new TheoryData(); + foreach (var v in Vectors().GetProperty("storedMicros").EnumerateArray()) + data.Add(v.GetProperty("in").GetString()!, v.GetProperty("out").GetString()!); + return data; + } + + [Theory, MemberData(nameof(StoredMicrosVectors))] + public void On_a_database_without_an_interval_a_duration_is_its_microsecond_count(string canonical, string micros) + { + var count = long.Parse(micros, System.Globalization.CultureInfo.InvariantCulture); + Assert.Equal(count, DurationWire.ToMicros(DurationWire.Parse(canonical))); + Assert.Equal(canonical, DurationWire.Format(DurationWire.FromMicros(count))); + } + + // C#'s own limit — a TimeSpan's range, about 10.7 million days — not a cross-port one: a span + // past it is refused, never wrapped, on parse and on a stored microsecond count. [Fact] - public void The_magnitude_is_bounded_at_256204778_hours_exactly_on_parse_and_on_write() + public void A_span_past_a_timespan_is_refused_never_wrapped() { - var max = TimeSpan.FromHours(DurationWire.MaxHours); - Assert.Equal("PT256204778H", DurationWire.Format(max)); - Assert.Equal("-PT256204778H", DurationWire.Format(-max)); - // A tick below a microsecond over the bound truncates back onto it; one microsecond over is refused. - Assert.Equal("PT256204778H", DurationWire.Format(max + TimeSpan.FromTicks(9))); - Assert.Throws(() => DurationWire.Format(max + TimeSpan.FromTicks(10))); - Assert.Throws(() => DurationWire.Format(-max - TimeSpan.FromTicks(10))); - Assert.Throws(() => DurationWire.Format(TimeSpan.MaxValue)); - Assert.Throws(() => DurationWire.Format(TimeSpan.MinValue)); - Assert.False(DurationWire.InRange(TimeSpan.MaxValue)); - Assert.True(DurationWire.InRange(-max)); - Assert.True(DurationWire.TryParse("PT256204777H59M59.999999S", out _)); - Assert.False(DurationWire.TryParse("PT256204778H0.000001S", out _)); - // A value past the bound is refused by the property converter on the way out, too. - Assert.ThrowsAny(() => JsonSerializer.Serialize(new Holder { Span = TimeSpan.MaxValue })); + Assert.Equal("PT256204778H48M5.47758S", DurationWire.Format(TimeSpan.MaxValue)); + Assert.Equal("-PT256204778H48M5.47758S", DurationWire.Format(TimeSpan.MinValue)); + Assert.Equal("PT256204778H", DurationWire.Format(DurationWire.Parse("PT256204778H"))); + Assert.Equal("-PT256204778H", DurationWire.Format(DurationWire.Parse("-P10675199DT2H"))); + Assert.True(DurationWire.TryParse("PT256204778H48M5.47758S", out var top)); + Assert.Equal(TimeSpan.MaxValue.Ticks / 10, top.Ticks / 10); + foreach (var past in new[] { "PT256204778H48M5.477581S", "PT256204779H", "P10675200D", "-PT256204779H", "PT99999999999999999999S" }) + Assert.False(DurationWire.TryParse(past, out _), past); + Assert.Equal(TimeSpan.MaxValue.Ticks / 10, DurationWire.ToMicros(TimeSpan.MaxValue)); + Assert.Throws(() => DurationWire.FromMicros(long.MaxValue)); + Assert.Throws(() => DurationWire.FromMicros(long.MinValue)); + Assert.Equal(-1, DurationWire.ToMicros(TimeSpan.FromTicks(-19))); // truncated toward zero } // ---- filter operands ---------------------------------------------------------------------- @@ -146,9 +161,9 @@ public void A_good_duration_operand_passes_and_an_in_list_is_checked_element_wis } [Fact] - public void A_duration_filters_on_the_identity_band() + public void A_duration_filters_on_the_ordered_band() { - Assert.Equal(["eq", "ne", "in", "isNull"], QueryConstants.OpsForSubType(FIELD_SUBTYPE_DURATION)); + Assert.Equal(["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"], QueryConstants.OpsForSubType(FIELD_SUBTYPE_DURATION)); } // ---- generated code ------------------------------------------------------------------------- @@ -224,35 +239,40 @@ public void A_duration_is_a_TimeSpan_with_the_wire_converter_an_interval_on_Post Assert.Contains("[DurationWire.Iso]", window); var ctx = files.Single(f => f.Path == "AppDbContext.g.cs").Content.Replace("\r\n", "\n"); + const string Npgsql = "if (Database.ProviderName == \"Npgsql.EntityFrameworkCore.PostgreSQL\")"; + const string Micros = "new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + "v => global::Acme.Ops.DurationWire.ToMicros(v), v => global::Acme.Ops.DurationWire.FromMicros(v))"; + // Npgsql: the native interval, read through the generated NpgsqlInterval mapping; anything + // else: an integer count of microseconds. Assert.Contains( - " if (Database.ProviderName == \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + - " modelBuilder.Entity().Property(x => x.Timeout).HasColumnType(\"interval\");\n" + + $" {Npgsql}\n" + + " modelBuilder.Entity().Property(x => x.Timeout).HasColumnType(\"interval\").Metadata.SetTypeMapping(DurationInterval.Mapping);\n" + " else\n" + - " modelBuilder.Entity().Property(x => x.Timeout).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + - "v => global::Acme.Ops.DurationWire.Format(v), v => global::Acme.Ops.DurationWire.Parse(v)));", + $" modelBuilder.Entity().Property(x => x.Timeout).HasConversion({Micros});", ctx); Assert.Contains( - " if (Database.ProviderName != \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + - " modelBuilder.Entity().PrimitiveCollection(x => x.Backoff).ElementType().HasConversion(", + $" {Npgsql}\n" + + " modelBuilder.Entity().PrimitiveCollection(x => x.Backoff).Metadata.SetTypeMapping(DurationInterval.ArrayMapping);\n" + + " else\n" + + $" modelBuilder.Entity().PrimitiveCollection(x => x.Backoff).ElementType().HasConversion({Micros});", ctx); + Assert.Contains("internal static class DurationInterval", ctx); + Assert.DoesNotContain("using Npgsql", ctx); // A duration member of a jsonb value object is stored as its canonical string on every provider. Assert.Contains("b.Property(p => p.Length).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(", ctx); - Assert.Contains("b.PrimitiveCollection(p => p.Steps).ElementType().HasConversion(", ctx); - // ...and a duration member of a FLATTENED value object takes the top-level column mapping: - // native on Postgres, the canonical-string converter elsewhere. + Assert.Contains("b.PrimitiveCollection(p => p.Steps).ElementType().HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(", ctx); + // ...and a duration member of a FLATTENED value object takes the top-level column mapping. Assert.Contains( " b.Property(p => p.Cap).HasColumnName(\"limits_cap\");\n" + - " if (Database.ProviderName != \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + - " b.Property(p => p.Cap).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + - "v => global::Acme.Ops.DurationWire.Format(v), v => global::Acme.Ops.DurationWire.Parse(v)));", - ctx); - Assert.Contains( - " if (Database.ProviderName != \"Npgsql.EntityFrameworkCore.PostgreSQL\")\n" + - " b.PrimitiveCollection(p => p.Marks).ElementType().HasConversion(", + $" {Npgsql}\n" + + " b.Property(p => p.Cap).HasColumnType(\"interval\").Metadata.SetTypeMapping(DurationInterval.Mapping);\n" + + " else\n" + + $" b.Property(p => p.Cap).HasConversion({Micros});", ctx); + Assert.Contains($" b.PrimitiveCollection(p => p.Marks).ElementType().HasConversion({Micros});", ctx); var allowlist = files.Single(f => f.Path == "TimerFilterAllowlist.g.cs").Content; - Assert.Contains("[\"grace\"] = new(System.StringComparer.Ordinal) { \"eq\", \"ne\", \"in\", \"isNull\" },", allowlist); + Assert.Contains("[\"grace\"] = new(System.StringComparer.Ordinal) { \"eq\", \"ne\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\", \"isNull\" },", allowlist); // The PATCH merge reads a duration through the wire helper, not System.Text.Json's own form. var routes = files.Single(f => f.Path == "TimerRoutes.g.cs").Content; @@ -260,6 +280,29 @@ public void A_duration_is_a_TimeSpan_with_the_wire_converter_an_interval_on_Post Assert.Contains("DurationWire.TryParseElement(prop.Value, out var __dur)", routes); } + // Stand-ins for NpgsqlTypes.NpgsqlInterval: the shape the generated Npgsql mapping reads, and two + // that have drifted from it. + public readonly struct IntervalLike { public int Months { get; } public int Days { get; } public long Time { get; } } + public readonly struct IntervalWithoutMonths { public int Days { get; } public long Time { get; } } + public readonly struct IntervalWithIntTime { public int Months { get; } public int Days { get; } public int Time { get; } } + + [Fact] + public void The_npgsql_mapping_names_what_is_missing_when_the_interval_shape_has_changed() + { + var asm = Compile(Emit()); + var shape = asm.GetType("Acme.Ops.AppDbContext+DurationInterval+IntervalShape")!; + var problem = shape.GetMethod("Problem", BindingFlags.NonPublic | BindingFlags.Static)!; + string? Check(Type? t) => (string?)problem.Invoke(null, [t]); + + Assert.Null(Check(typeof(IntervalLike))); + Assert.Contains("no type NpgsqlTypes.NpgsqlInterval was found", Check(null)); + var noMonths = Check(typeof(IntervalWithoutMonths))!; + Assert.Contains("has no Int32 Months property", noMonths); + Assert.Contains("tested with Npgsql 8.0.5", noMonths); + Assert.Contains("has no Int64 Time property", Check(typeof(IntervalWithIntTime))); + Assert.Equal("NpgsqlTypes.NpgsqlInterval, Npgsql", shape.GetField("TypeName", BindingFlags.NonPublic | BindingFlags.Static)!.GetValue(null)); + } + [Fact] public void The_generated_entity_compiles_and_crosses_json_in_the_canonical_form() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs index baed0b406b..62505fe455 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ValidationConformanceTests.cs @@ -48,7 +48,7 @@ public static IEnumerable Cases() [Fact] public void Discovers_all_validation_conformance_cases() { - Assert.Equal(55, Cases().Count()); + Assert.Equal(54, Cases().Count()); } [Theory] diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index addc0531fa..d358b95bce 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -276,6 +276,7 @@ public virtual IEnumerable Generate(GenContext ctx) // three emission sites, and had already been wrong twice: it undercounted them, and it // did not model jsonbObjectsOnly suppressing the flattened arm on a read model. if (modelLines.Any(l => l.Contains(MapJsonbHelperName))) EmitMapJsonbHelper(sb); + if (modelLines.Any(l => l.Contains(DurationIntervalHelperName + "."))) EmitDurationIntervalHelper(sb); sb.AppendLine("}"); return [new EmittedFile("AppDbContext.g.cs", sb.ToString())]; } @@ -1109,29 +1110,181 @@ private static void AddDurationConfig( string className, MetaObject entity, IEnumerable fields, GenContext ctx, List modelLines) { foreach (var f in fields.Where(f => f.SubType == FIELD_SUBTYPE_DURATION && f.DbColumnType is null)) - { - var prop = CSharpNaming.Pascal(f.Name); - var converter = DurationConverter(entity, ctx); - var npgsql = f.ResolvedIsArray() - ? null - : $" modelBuilder.Entity<{className}>().Property(x => x.{prop}).HasColumnType(\"interval\");"; - var text = f.ResolvedIsArray() - ? $" modelBuilder.Entity<{className}>().PrimitiveCollection(x => x.{prop}).ElementType().HasConversion({converter});" - : $" modelBuilder.Entity<{className}>().Property(x => x.{prop}).HasConversion({converter});"; - modelLines.Add(npgsql is null - ? $" if (Database.ProviderName != \"{NpgsqlProviderName}\")\n{text}" - : $" if (Database.ProviderName == \"{NpgsqlProviderName}\")\n{npgsql}\n else\n{text}"); - } + modelLines.Add(string.Join("\n", + DurationColumnLines($"modelBuilder.Entity<{className}>()", "x", CSharpNaming.Pascal(f.Name), f.ResolvedIsArray(), entity, ctx, " "))); + } + + // The provider-dependent mapping of one duration column (a top-level property, or a member of a + // flattened value object through its owned builder `target`): + // - Npgsql: the native `interval` (`interval[]` for an array), read through the generated + // DurationInterval type mapping, so a month or year part, or a day count past what a TimeSpan + // holds, is refused instead of read wrong (Npgsql's own TimeSpan read drops a negative month + // part and wraps such a day count). + // - any other provider (SQLite, MySQL): a 64-bit count of microseconds in an integer column + // (sub-microsecond ticks truncated toward zero; a count past a TimeSpan refused, not + // wrapped), which orders and compares as the span does. An array holds the counts. + private static IEnumerable DurationColumnLines( + string target, string v, string prop, bool isArray, MetaObject owner, GenContext ctx, string indent) + { + var micros = DurationMicrosConverter(owner, ctx); + yield return $"{indent}if (Database.ProviderName == \"{NpgsqlProviderName}\")"; + yield return isArray + ? $"{indent} {target}.PrimitiveCollection({v} => {v}.{prop}).Metadata.SetTypeMapping({DurationIntervalHelperName}.ArrayMapping);" + : $"{indent} {target}.Property({v} => {v}.{prop}).HasColumnType(\"interval\").Metadata.SetTypeMapping({DurationIntervalHelperName}.Mapping);"; + yield return $"{indent}else"; + yield return isArray + ? $"{indent} {target}.PrimitiveCollection({v} => {v}.{prop}).ElementType().HasConversion({micros});" + : $"{indent} {target}.Property({v} => {v}.{prop}).HasConversion({micros});"; } - // A TimeSpan <-> canonical ISO-8601 string converter, through the DurationWire the entity - // generator emits into OWNER's namespace (owner has a duration field, so it has one). + // The namespace OWNER's DurationWire is emitted into (owner has a duration field, so it has one). + private static string DurationWireRef(MetaObject owner, GenContext ctx) => + "global::" + PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(owner), owner.Name, fallbackContext: owner.Name) + + ".DurationWire"; + + // A TimeSpan <-> canonical ISO-8601 string converter: a duration inside a JSON document. private static string DurationConverter(MetaObject owner, GenContext ctx) { - var ns = PackageBindingResolver.Resolve(ctx.Config, PackageBindingResolver.EffectivePackage(owner), owner.Name, fallbackContext: owner.Name); + var dw = DurationWireRef(owner, ctx); return "new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + - $"v => global::{ns}.DurationWire.Format(v), v => global::{ns}.DurationWire.Parse(v))"; + $"v => {dw}.Format(v), v => {dw}.Parse(v))"; + } + + // A TimeSpan <-> microsecond-count converter: a duration column on a database without an interval type. + private static string DurationMicrosConverter(MetaObject owner, GenContext ctx) + { + var dw = DurationWireRef(owner, ctx); + return "new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + $"v => {dw}.ToMicros(v), v => {dw}.FromMicros(v))"; + } + + private const string DurationIntervalHelperName = "DurationInterval"; + + // field.duration on Npgsql — the interval type mapping the duration columns are read through. + // Npgsql's own TimeSpan read guards the month part with `months > 0` (so '-1 mons' reads as zero) + // and adds the day part unchecked (so a day count past a TimeSpan wraps); this mapping reads the + // value as NpgsqlInterval instead and refuses both. Npgsql is reached by reflection only, so the + // generated context compiles, and runs, in a project with no Npgsql reference; the class is first + // touched in the Npgsql branch of OnModelCreating. + private static void EmitDurationIntervalHelper(StringBuilder sb) => sb.Append(DurationIntervalHelperSource); + + private const string DurationIntervalHelperSource = """ + + /// + /// field.duration on Npgsql: an interval column read through NpgsqlInterval, so a month + /// or year part, or a day count past what a TimeSpan holds, is refused rather than read wrong. + /// Npgsql is reached by reflection: a project on another provider needs no Npgsql reference. + /// + internal static class DurationInterval + { + // The Npgsql shape this mapping reads, resolved and checked when the model is built (the + // first touch is SetTypeMapping in OnModelCreating), so a missing or changed type fails + // there, naming what is missing, rather than on the first row read. + private static readonly System.Type IntervalType = Resolve(); + private static readonly System.Reflection.PropertyInfo Months = IntervalType.GetProperty("Months")!; + private static readonly System.Reflection.PropertyInfo Days = IntervalType.GetProperty("Days")!; + private static readonly System.Reflection.PropertyInfo Time = IntervalType.GetProperty("Time")!; + private static readonly System.Reflection.MethodInfo GetFieldValue = + typeof(System.Data.Common.DbDataReader).GetMethod(nameof(System.Data.Common.DbDataReader.GetFieldValue))!; + + internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Mapping = new ScalarMapping(); + internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping ArrayMapping = new ListMapping(); + + private static System.Type Resolve() + { + var type = System.Type.GetType(IntervalShape.TypeName, throwOnError: false); + if (IntervalShape.Problem(type) is { } problem) throw new System.InvalidOperationException(problem); + return type!; + } + + /// The check of the NpgsqlInterval shape, kept apart from the state above so it can run against any type. + internal static class IntervalShape + { + internal const string TypeName = "NpgsqlTypes.NpgsqlInterval, Npgsql"; + + /// Null when has the shape the mapping reads, else a message naming what is missing. + internal static string? Problem(System.Type? type) + { + const string Lead = "field.duration on Npgsql: the generated DurationInterval mapping reads an interval column as " + + "NpgsqlTypes.NpgsqlInterval (an Int32 Months, an Int32 Days and an Int64 Time in microseconds; " + + "tested with Npgsql 8.0.5), but "; + if (type is null) return Lead + "no type NpgsqlTypes.NpgsqlInterval was found in the loaded Npgsql assembly."; + var missing = new System.Collections.Generic.List(); + foreach (var (name, want) in new[] { ("Months", typeof(int)), ("Days", typeof(int)), ("Time", typeof(long)) }) + { + var property = type.GetProperty(name); + if (property is null || property.PropertyType != want) + missing.Add(want.Name + " " + name); + } + return missing.Count == 0 + ? null + : Lead + type.FullName + " has no " + string.Join(", no ", missing) + " property. Check the Npgsql version the project references."; + } + } + + /// An NpgsqlInterval as a TimeSpan: refused when it has a month or year part, or a span a TimeSpan cannot hold. + public static System.TimeSpan FromInterval(object interval) + { + if ((int)Months.GetValue(interval)! != 0) + throw new System.InvalidCastException("field.duration: the interval has a month or year part, so it is not a fixed-length span"); + var days = (int)Days.GetValue(interval)!; + var micros = (long)Time.GetValue(interval)!; + return System.TimeSpan.FromTicks(checked(days * System.TimeSpan.TicksPerDay + micros * 10)); + } + + /// An interval[] (an NpgsqlInterval array) as the list a duration array property holds. + public static System.Collections.Generic.IList FromIntervals(object intervals) + { + var list = new System.Collections.Generic.List(); + foreach (var interval in (System.Array)intervals) list.Add(FromInterval(interval!)); + return list; + } + + // A span as Postgres interval input: [-]HH:MM:SS[.f], hours unbounded, no day part. + private static string Literal(System.TimeSpan value) + { + long micros = value.Ticks / 10; + bool negative = micros < 0; + long rest = negative ? -micros : micros; + long frac = rest % 1_000_000L, s = rest / 1_000_000L % 60, m = rest / 60_000_000L % 60, h = rest / 3_600_000_000L; + var text = h.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + ":" + m.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + + ":" + s.ToString("00", System.Globalization.CultureInfo.InvariantCulture); + if (frac > 0) text += "." + frac.ToString("D6", System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0'); + return "INTERVAL '" + (negative ? "-" : "") + text + "'"; + } + + private sealed class ScalarMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping + { + public ScalarMapping() : base("interval", typeof(System.TimeSpan)) { } + private ScalarMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new ScalarMapping(parameters); + public override System.Reflection.MethodInfo GetDataReaderMethod() => GetFieldValue.MakeGenericMethod(IntervalType); + public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => + System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(FromInterval))!, + System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => Literal((System.TimeSpan)value); + } + + private sealed class ListMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping + { + private static readonly Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer> ListComparer = new( + (a, b) => a == null ? b == null : b != null && System.Linq.Enumerable.SequenceEqual(a, b), + v => System.Linq.Enumerable.Aggregate(v, 0, (h, e) => System.HashCode.Combine(h, e)), + v => System.Linq.Enumerable.ToList(v)); + + public ListMapping() : base(new RelationalTypeMappingParameters( + new CoreTypeMappingParameters(typeof(System.Collections.Generic.IList), comparer: ListComparer, keyComparer: ListComparer), "interval[]")) { } + private ListMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new ListMapping(parameters); + public override System.Reflection.MethodInfo GetDataReaderMethod() => GetFieldValue.MakeGenericMethod(IntervalType.MakeArrayType()); + public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => + System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(FromIntervals))!, + System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => + "ARRAY[" + string.Join(",", System.Linq.Enumerable.Select((System.Collections.Generic.IEnumerable)value, Literal)) + "]::interval[]"; + } } +"""; // The EF Core provider name Npgsql registers (DbContext.Database.ProviderName). private const string NpgsqlProviderName = "Npgsql.EntityFrameworkCore.PostgreSQL"; @@ -1304,26 +1457,17 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s } // A `field.duration` member: the migration flattens it to an `interval` column on - // Postgres (Npgsql maps the TimeSpan natively) and a text column elsewhere, which holds - // the canonical ISO-8601 string — the same provider-dependent mapping a top-level - // duration takes (AddDurationConfig). Without the converter EF would write its own - // "01:30:00" there and fail to read another port's "PT1H30M". + // Postgres and an integer microsecond count elsewhere — the same provider-dependent + // mapping a top-level duration takes (DurationColumnLines). Without it EF would write + // its own "01:30:00" text there and fail to read another port's count. if (nf.SubType == FIELD_SUBTYPE_DURATION && CSharpNaming.DbColumnTypeClrOverride(nf) is null) { var dprop = CSharpNaming.Pascal(nf.Name); - var converter = DurationConverter(vo, ctx); - if (nf.ResolvedIsArray()) - { - sb.AppendLine($" b.PrimitiveCollection(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); - sb.AppendLine($" if (Database.ProviderName != \"{NpgsqlProviderName}\")"); - sb.AppendLine($" b.PrimitiveCollection(p => p.{dprop}).ElementType().HasConversion({converter});"); - } - else - { - sb.AppendLine($" b.Property(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); - sb.AppendLine($" if (Database.ProviderName != \"{NpgsqlProviderName}\")"); - sb.AppendLine($" b.Property(p => p.{dprop}).HasConversion({converter});"); - } + sb.AppendLine(nf.ResolvedIsArray() + ? $" b.PrimitiveCollection(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");" + : $" b.Property(p => p.{dprop}).HasColumnName(\"{nestedColAny}\");"); + foreach (var line in DurationColumnLines("b", "p", dprop, nf.ResolvedIsArray(), vo, ctx, " ")) + sb.AppendLine(line); continue; } diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index cae663d7ad..359e0f18f5 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -1405,10 +1405,11 @@ private static EmittedFile EmitDecimalWireFile(string ns, string fileName) => // ticks below that are truncated toward zero), one leading `-` for a negative span. Every port // reads that form plus a leading day count (`nD`, exactly 24 hours), an optional `+`, and up to // nine fractional digits. Years, months and weeks are refused: a calendar span has no fixed -// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. The magnitude is -// bounded at 256204778 hours, the largest whole hour a TimeSpan holds, in every port: a longer span -// is refused on parse and on write, never wrapped or rounded. The rule and its cross-port vectors -// are in fixtures/duration-wire/. +// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. A span longer than a +// TimeSpan holds (about 10.7 million days) is refused, never wrapped: that is this port's own limit, +// not a cross-port one. On a database without an interval type (SQLite, MySQL) a duration is stored +// as a 64-bit count of microseconds (ToMicros / FromMicros). The rule and its cross-port vectors are +// in fixtures/duration-wire/. // // ONE source, two homes. This file is the package's production helper (the filter dispatcher // parses its operands through it). The entity generator emits the SAME text, with only the @@ -1439,27 +1440,9 @@ public static class DurationWire private const long MicrosPerDay = 24L * MicrosPerHour; private const long TicksPerMicro = TimeSpan.TicksPerMillisecond / 1000L; - /// The largest magnitude a duration may have, in hours (the largest whole hour a TimeSpan holds); every port shares the bound. - public const long MaxHours = 256_204_778L; - - private const long MaxMicros = MaxHours * MicrosPerHour; - - /// True when is within the shared bound (at most hours either way, counted in whole microseconds). - public static bool InRange(TimeSpan value) - { - long micros = value.Ticks / TicksPerMicro; - return micros <= MaxMicros && micros >= -MaxMicros; - } - - /// - /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks - /// truncated toward zero. Throws for a span past the shared bound - /// (), which no port can read. - /// + /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks truncated toward zero. public static string Format(TimeSpan value) { - if (!InRange(value)) - throw new OverflowException("field.duration: a span longer than " + MaxHours.ToString(CultureInfo.InvariantCulture) + " hours is not a duration"); long micros = value.Ticks / TicksPerMicro; // integer division truncates toward zero bool negative = micros < 0; long rest = negative ? -micros : micros; @@ -1484,8 +1467,7 @@ public static string Format(TimeSpan value) /// /// Parse an ISO-8601 duration in the accepted form (). False for anything /// else: years, months or weeks, lowercase designators, fractional hours or minutes, a comma, - /// per-component signs, whitespace, out-of-order components, or a span longer than - /// hours (one microsecond over is refused). + /// per-component signs, whitespace, out-of-order components, or a span a TimeSpan cannot hold. /// Fractional seconds past the sixth digit are truncated toward zero. /// public static bool TryParse(string? text, out TimeSpan value) @@ -1542,7 +1524,6 @@ public static bool TryParse(string? text, out TimeSpan value) i++; } } - if (micros > MaxMicros) return false; value = TimeSpan.FromTicks((negative ? -micros : micros) * TicksPerMicro); } } @@ -1553,6 +1534,12 @@ public static bool TryParse(string? text, out TimeSpan value) return true; } + /// The stored form on a database without an interval type: whole microseconds, sub-microsecond ticks truncated toward zero. + public static long ToMicros(TimeSpan value) => value.Ticks / TicksPerMicro; + + /// A stored microsecond count as a TimeSpan. Throws for a count a TimeSpan cannot hold: refused, never wrapped. + public static TimeSpan FromMicros(long micros) => TimeSpan.FromTicks(checked(micros * TicksPerMicro)); + /// Parse the accepted form, or throw . public static TimeSpan Parse(string text) => TryParse(text, out var value) @@ -2132,7 +2119,7 @@ protected static string DefaultInitializer(MetaField field, string baseType) // The accepted field.duration form (fixtures/duration-wire/), the gate on a duration @default. // `\z`, not `$`: .NET's `$` also matches before a trailing newline, which would land in the - // emitted string literal. The magnitude bound is DurationWire.Parse's, checked when it runs. + // emitted string literal. A span a TimeSpan cannot hold is refused by DurationWire.Parse when it runs. private static readonly System.Text.RegularExpressions.Regex DurationDefaultPattern = new( @"^[-+]?P(?!\z)([0-9]+D)?(T(?=[0-9])([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]{1,9})?S)?)?\z", System.Text.RegularExpressions.RegexOptions.CultureInvariant); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs b/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs index 1de7a8d9e3..af74e04edf 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/DurationWire.cs @@ -7,10 +7,11 @@ // ticks below that are truncated toward zero), one leading `-` for a negative span. Every port // reads that form plus a leading day count (`nD`, exactly 24 hours), an optional `+`, and up to // nine fractional digits. Years, months and weeks are refused: a calendar span has no fixed -// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. The magnitude is -// bounded at 256204778 hours, the largest whole hour a TimeSpan holds, in every port: a longer span -// is refused on parse and on write, never wrapped or rounded. The rule and its cross-port vectors -// are in fixtures/duration-wire/. +// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. A span longer than a +// TimeSpan holds (about 10.7 million days) is refused, never wrapped: that is this port's own limit, +// not a cross-port one. On a database without an interval type (SQLite, MySQL) a duration is stored +// as a 64-bit count of microseconds (ToMicros / FromMicros). The rule and its cross-port vectors are +// in fixtures/duration-wire/. // // ONE source, two homes. This file is the package's production helper (the filter dispatcher // parses its operands through it). The entity generator emits the SAME text, with only the @@ -41,27 +42,9 @@ public static class DurationWire private const long MicrosPerDay = 24L * MicrosPerHour; private const long TicksPerMicro = TimeSpan.TicksPerMillisecond / 1000L; - /// The largest magnitude a duration may have, in hours (the largest whole hour a TimeSpan holds); every port shares the bound. - public const long MaxHours = 256_204_778L; - - private const long MaxMicros = MaxHours * MicrosPerHour; - - /// True when is within the shared bound (at most hours either way, counted in whole microseconds). - public static bool InRange(TimeSpan value) - { - long micros = value.Ticks / TicksPerMicro; - return micros <= MaxMicros && micros >= -MaxMicros; - } - - /// - /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks - /// truncated toward zero. Throws for a span past the shared bound - /// (), which no port can read. - /// + /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks truncated toward zero. public static string Format(TimeSpan value) { - if (!InRange(value)) - throw new OverflowException("field.duration: a span longer than " + MaxHours.ToString(CultureInfo.InvariantCulture) + " hours is not a duration"); long micros = value.Ticks / TicksPerMicro; // integer division truncates toward zero bool negative = micros < 0; long rest = negative ? -micros : micros; @@ -86,8 +69,7 @@ public static string Format(TimeSpan value) /// /// Parse an ISO-8601 duration in the accepted form (). False for anything /// else: years, months or weeks, lowercase designators, fractional hours or minutes, a comma, - /// per-component signs, whitespace, out-of-order components, or a span longer than - /// hours (one microsecond over is refused). + /// per-component signs, whitespace, out-of-order components, or a span a TimeSpan cannot hold. /// Fractional seconds past the sixth digit are truncated toward zero. /// public static bool TryParse(string? text, out TimeSpan value) @@ -144,7 +126,6 @@ public static bool TryParse(string? text, out TimeSpan value) i++; } } - if (micros > MaxMicros) return false; value = TimeSpan.FromTicks((negative ? -micros : micros) * TicksPerMicro); } } @@ -155,6 +136,12 @@ public static bool TryParse(string? text, out TimeSpan value) return true; } + /// The stored form on a database without an interval type: whole microseconds, sub-microsecond ticks truncated toward zero. + public static long ToMicros(TimeSpan value) => value.Ticks / TicksPerMicro; + + /// A stored microsecond count as a TimeSpan. Throws for a count a TimeSpan cannot hold: refused, never wrapped. + public static TimeSpan FromMicros(long micros) => TimeSpan.FromTicks(checked(micros * TicksPerMicro)); + /// Parse the accepted form, or throw . public static TimeSpan Parse(string text) => TryParse(text, out var value) diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs b/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs index a8d9ed7f9e..33bc99600d 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests.cs @@ -2,9 +2,9 @@ // bytes, on a model of its own, and the Postgres half of the shared wire vectors // (fixtures/duration-wire/vectors.json) against a live interval column through Npgsql. // -// SQLite needs no Docker: a duration there is the canonical ISO-8601 string in a TEXT column, -// through the generated DbContext's value converter. Postgres is the native interval, bound and -// read as a TimeSpan by Npgsql. +// SQLite needs no Docker: a duration there is a 64-bit count of microseconds in an INTEGER column, +// through the generated DbContext's value converter, so it orders as the span does. Postgres is the +// native interval, bound as a TimeSpan and read through the generated NpgsqlInterval mapping. using System.Text; using System.Text.Json; @@ -40,7 +40,7 @@ public sealed class DurationWireGeneratedApiTests ] } } """; - private const string SqliteSchema = """CREATE TABLE "timers" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "label" TEXT, "timeout" TEXT NOT NULL, "grace" TEXT, "backoff" TEXT NOT NULL, "window" TEXT, "limits_cap" TEXT)"""; + private const string SqliteSchema = """CREATE TABLE "timers" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "label" TEXT, "timeout" INTEGER NOT NULL, "grace" INTEGER, "backoff" TEXT NOT NULL, "window" TEXT, "limits_cap" INTEGER)"""; private const string PgSchema = """CREATE TABLE "timers" ("id" BIGSERIAL PRIMARY KEY, "label" TEXT, "timeout" INTERVAL NOT NULL, "grace" INTERVAL, "backoff" INTERVAL[] NOT NULL, "window" JSONB, "limits_cap" INTERVAL)"""; private static async Task Start(ScenarioEngine engine, string conn, bool createSchema = true) @@ -126,10 +126,32 @@ private static async Task Exercise(HttpClient c) Assert.Contains("invalid_filter_value", bx); Assert.Contains("\"field\":\"timeout\"", bx); } + + // A duration orders as the span: a gt / lt / gte filter and a sort compare lengths, not text. + var (s3, b3) = await Send(c, "POST", "/api/timers", """{"label":"c","timeout":"PT30M","grace":"PT1S","backoff":[]}"""); + Assert.True(s3 == 201, $"POST: {s3} {b3}"); + var (_, longer) = await Send(c, "GET", "/api/timers?filter%5Btimeout%5D%5Bgt%5D=PT1H"); + Assert.Contains("\"label\":\"a\"", longer); + Assert.Contains("\"label\":\"b\"", longer); + Assert.DoesNotContain("\"label\":\"c\"", longer); + var (_, shorter) = await Send(c, "GET", "/api/timers?filter%5Btimeout%5D%5Blt%5D=P1D"); + Assert.Contains("\"label\":\"c\"", shorter); + Assert.DoesNotContain("\"label\":\"a\"", shorter); + var (_, atLeast) = await Send(c, "GET", "/api/timers?filter%5Bgrace%5D%5Bgte%5D=-PT90S"); + Assert.Contains("\"label\":\"a\"", atLeast); // -PT1M30S: as long as the bound, not shorter + Assert.Contains("\"label\":\"c\"", atLeast); + var (_, below) = await Send(c, "GET", "/api/timers?filter%5Bgrace%5D%5Blt%5D=PT0S"); + Assert.Contains("\"label\":\"a\"", below); // a negative span is shorter than zero + Assert.DoesNotContain("\"label\":\"c\"", below); + var (ss, asc) = await Send(c, "GET", "/api/timers?sort=timeout:asc"); + Assert.True(ss == 200, $"sort: {ss} {asc}"); + Assert.True(asc.IndexOf("\"label\":\"c\"", StringComparison.Ordinal) < asc.IndexOf("\"label\":\"a\"", StringComparison.Ordinal), asc); + var (_, desc) = await Send(c, "GET", "/api/timers?sort=grace:desc&filter%5Bgrace%5D%5BisNull%5D=false"); + Assert.True(desc.IndexOf("\"label\":\"c\"", StringComparison.Ordinal) < desc.IndexOf("\"label\":\"a\"", StringComparison.Ordinal), desc); } [Fact] - public async Task On_sqlite_a_duration_is_the_canonical_string_in_a_text_column() + public async Task On_sqlite_a_duration_is_a_microsecond_count_in_an_integer_column() { using var db = new SqliteTempDatabase("mo-duration-wire-"); var conn = $"Data Source={db.FilePath}"; @@ -139,26 +161,26 @@ public async Task On_sqlite_a_duration_is_the_canonical_string_in_a_text_column( await Exercise(c); } - // The column holds one spelling per span: the canonical one. + // The column holds the span's microsecond count (a JSON document keeps the canonical string). await using var sql = await ScenarioEngine.Sqlite.OpenConnectionAsync(conn); await using var cmd = sql.CreateCommand(); cmd.CommandText = """SELECT "timeout", "grace", "backoff", "window", "limits_cap" FROM "timers" WHERE "id" = 1"""; await using (var r = await cmd.ExecuteReaderAsync()) { Assert.True(await r.ReadAsync()); - Assert.Equal("PT26H", r.GetString(0)); - Assert.Equal("-PT1M30S", r.GetString(1)); - Assert.Equal("[\"PT1H30M\",\"PT0.5S\"]", r.GetString(2)); + Assert.Equal(93_600_000_000L, r.GetInt64(0)); + Assert.Equal(-90_000_000L, r.GetInt64(1)); + Assert.Equal("[5400000000,500000]", r.GetString(2)); Assert.Contains("\"PT1H30M\"", r.GetString(3)); - Assert.Equal("PT2H", r.GetString(4)); // a flattened value object's member too + Assert.Equal(7_200_000_000L, r.GetInt64(4)); // a flattened value object's member too } - // A row another port wrote, in the accepted (not canonical) form, reads back canonical. + // A row another port wrote reads back canonical. await ScenarioEngine.Sqlite.ExecuteScriptAsync(conn, - """INSERT INTO "timers" ("label","timeout","backoff","window","limits_cap") VALUES ('other','P1D','["PT90M"]','{"Length":"PT90M","Slack":null}','PT5400S')"""); + """INSERT INTO "timers" ("label","timeout","backoff","window","limits_cap") VALUES ('other',86400000000,'[5400000000]','{"Length":"PT90M","Slack":null}',5400000000)"""); await using var again = await Start(ScenarioEngine.Sqlite, conn, createSchema: false); using var c2 = new HttpClient { BaseAddress = new Uri(again.BaseUrl) }; - var (so, bo) = await Send(c2, "GET", "/api/timers/3"); + var (so, bo) = await Send(c2, "GET", "/api/timers/4"); Assert.True(so == 200, $"GET other: {so} {bo}"); Assert.Equal("\"PT24H\"", Field(bo, "timeout")); Assert.Equal("[\"PT1H30M\"]", Field(bo, "backoff")); @@ -166,7 +188,7 @@ await ScenarioEngine.Sqlite.ExecuteScriptAsync(conn, } [Fact] - public async Task On_postgres_a_duration_is_a_native_interval_and_a_month_part_is_refused() + public async Task On_postgres_a_duration_is_a_native_interval() { await using var pg = await PostgresContainer.StartAsync(); await using var server = await Start(ScenarioEngine.Postgres, pg.ConnectionString); @@ -184,25 +206,61 @@ public async Task On_postgres_a_duration_is_a_native_interval_and_a_month_part_i Assert.True(r.GetBoolean(1)); } - // An interval with a month part is not a duration: reading one is an error, never a guess. - // ("-1 mons" / "-1 year" are not here: Npgsql misreads them; see NpgsqlMisreads below.) - foreach (var calendar in new[] { "1 mon", "2 years" }) + } + + // Npgsql's own TimeSpan read guards the month part with `months > 0` (a stored '-1 mons' reads + // as PT0S) and adds the day part unchecked (a day count past a TimeSpan wraps). The generated + // context reads the column through NpgsqlInterval instead: every Postgres vector reads back + // canonical, and a month or year part of either sign, or a day count a TimeSpan cannot hold, is + // refused — never read wrong. A C#/Npgsql limit, not a cross-port one. + [Fact] + public async Task On_postgres_the_generated_read_refuses_a_month_part_and_a_day_count_past_a_timespan() + { + var vectors = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine( + CorpusPaths.Repo, "fixtures", "duration-wire", "vectors.json"))).RootElement; + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await Start(ScenarioEngine.Postgres, pg.ConnectionString); + using var c = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + + async Task<(int Status, string Body)> ReadStored(string timeout, string backoff = "{}") { - await ScenarioEngine.Postgres.ExecuteScriptAsync(pg.ConnectionString, - "INSERT INTO \"timers\" (\"id\",\"label\",\"timeout\",\"backoff\") VALUES (900,'calendar', interval '" + calendar + "', '{}')"); - var (sm, bm) = await Send(c, "GET", "/api/timers/900"); - Assert.True(sm != 200, $"interval '{calendar}' read as {bm}"); - await ScenarioEngine.Postgres.ExecuteScriptAsync(pg.ConnectionString, """DELETE FROM "timers" WHERE "id" = 900"""); + await using var sql = new NpgsqlConnection(pg.ConnectionString); + await sql.OpenAsync(); + await using (var del = new NpgsqlCommand("""DELETE FROM "timers" WHERE "id" = 900""", sql)) await del.ExecuteNonQueryAsync(); + await using (var ins = new NpgsqlCommand("""INSERT INTO "timers" ("id","label","timeout","backoff") VALUES (900, 'stored', @t::interval, @b::interval[])""", sql)) + { + ins.Parameters.AddWithValue("t", timeout); + ins.Parameters.AddWithValue("b", backoff); + await ins.ExecuteNonQueryAsync(); + } + return await Send(c, "GET", "/api/timers/900"); + } + + foreach (var v in vectors.GetProperty("postgres").EnumerateArray()) + { + var (st, body) = await ReadStored(v.GetProperty("in").GetString()!); + Assert.True(st == 200, $"interval '{v.GetProperty("in").GetString()}': {st} {body}"); + Assert.Equal($"\"{v.GetProperty("out").GetString()}\"", Field(body, "timeout")); + } + var refused = vectors.GetProperty("postgresRefused").EnumerateArray().Select(v => v.GetString()!) + .Where(t => t != "abc") // not an interval: Postgres itself refuses the INSERT + .Concat(["-1 mons", "-1 year", "-1 year 2 mons", "10675200 days", "-10675200 days"]); + foreach (var text in refused) + { + var (st, body) = await ReadStored(text); + Assert.True(st != 200, $"interval '{text}' read as {body}"); } - } - // Intervals Npgsql 8.0.5's native TimeSpan read gets WRONG instead of refusing: it guards the month - // part with `months > 0`, so a negative month or year part is silently dropped ('-1 mons' reads as - // PT0S), and it adds the day part without an overflow check, so '10675200 days' wraps to a negative - // span inside the bound. EF materializes the column through that read, so the generated code - // never sees the interval's parts. Closing it needs host-side Npgsql configuration (or a driver - // fix), not generated code. - private static readonly HashSet NpgsqlMisreads = ["10675200 days", "-1 mons", "-1 year"]; + // An interval[] reads element by element through the same rule. + var (sa, ba) = await ReadStored("00:00:00", "{26:00:00,1 day,-00:01:30}"); + Assert.True(sa == 200, $"interval[]: {sa} {ba}"); + Assert.Equal("[\"PT26H\",\"PT24H\",\"-PT1M30S\"]", Field(ba, "backoff")); + foreach (var array in new[] { "{1 hour,-1 mons}", "{10675200 days}" }) + { + var (st, body) = await ReadStored("00:00:00", array); + Assert.True(st != 200, $"interval[] '{array}' read as {body}"); + } + } private static async Task> Misread(NpgsqlConnection sql, IEnumerable texts) { @@ -219,16 +277,6 @@ private static async Task> Misread(NpgsqlConnection sql, IEnumerabl return misread; } - [Fact(Skip = "Npgsql 8.0.5 misreads these intervals (see NpgsqlMisreads); unskip once the read is guarded.")] - public async Task A_negative_month_part_and_a_day_overflow_are_refused_on_read() - { - await using var pg = await PostgresContainer.StartAsync(); - await using var sql = new NpgsqlConnection(pg.ConnectionString); - await sql.OpenAsync(); - var misread = await Misread(sql, NpgsqlMisreads); - Assert.True(misread.Count == 0, string.Join("; ", misread)); - } - // The `postgres`, `postgresRefused` and `postgresText` vectors, against Npgsql's native TimeSpan. [Fact] public async Task The_postgres_vectors_hold_through_npgsqls_native_timespan() @@ -249,12 +297,9 @@ public async Task The_postgres_vectors_hold_through_npgsqls_native_timespan() Assert.Equal(v.GetProperty("out").GetString(), DurationWire.Format(span)); } - // An interval with a year or month part, one past the shared magnitude bound, or text that is - // no interval is refused: by Npgsql's read, or by DurationWire on the way out. The inputs - // Npgsql itself misreads are pinned separately (NpgsqlMisreads). - var refused = vectors.GetProperty("postgresRefused").EnumerateArray().Select(v => v.GetString()!) - .Where(t => !NpgsqlMisreads.Contains(t)); - Assert.Empty(await Misread(sql, refused)); + // An interval with a (positive) year or month part, or text that is no interval, is refused by + // Npgsql's own read too. (A negative month part is not: the generated mapping covers it.) + Assert.Empty(await Misread(sql, vectors.GetProperty("postgresRefused").EnumerateArray().Select(v => v.GetString()!))); // A TimeSpan bound natively is the same span as the Postgres spelling of its canonical form. foreach (var v in vectors.GetProperty("postgresText").EnumerateArray()) diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs index 271e47c87f..7913c64cc5 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs @@ -101,9 +101,9 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().Property(x => x.InetVal).HasColumnType("inet"); modelBuilder.Entity().Property(x => x.Inet6Val).HasColumnType("inet"); if (Database.ProviderName == "Npgsql.EntityFrameworkCore.PostgreSQL") - modelBuilder.Entity().Property(x => x.DurationVal).HasColumnType("interval"); + modelBuilder.Entity().Property(x => x.DurationVal).HasColumnType("interval").Metadata.SetTypeMapping(DurationInterval.Mapping); else - modelBuilder.Entity().Property(x => x.DurationVal).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => global::MetaObjects.IntegrationTests.Generated.DurationWire.Format(v), v => global::MetaObjects.IntegrationTests.Generated.DurationWire.Parse(v))); + modelBuilder.Entity().Property(x => x.DurationVal).HasConversion(new Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => global::MetaObjects.IntegrationTests.Generated.DurationWire.ToMicros(v), v => global::MetaObjects.IntegrationTests.Generated.DurationWire.FromMicros(v))); modelBuilder.Entity().Property(x => x.RecordedAt).HasColumnType("timestamp with time zone"); modelBuilder.Entity().Property(x => x.ObservedAt).HasColumnType("timestamp without time zone"); modelBuilder.Entity().Property(x => x.ExternalId).HasColumnType("uuid").HasConversion(v => System.Guid.Parse(v!), g => g.ToString("D")); @@ -136,4 +136,118 @@ private static T UnmappedEnumValue(int stored, string field) => throw new System.InvalidOperationException( $"field.enum '{field}' read stored value {stored} with no member in " + "@intValueMap — the database holds a value the model does not describe."); -} + + /// + /// field.duration on Npgsql: an interval column read through NpgsqlInterval, so a month + /// or year part, or a day count past what a TimeSpan holds, is refused rather than read wrong. + /// Npgsql is reached by reflection: a project on another provider needs no Npgsql reference. + /// + internal static class DurationInterval + { + // The Npgsql shape this mapping reads, resolved and checked when the model is built (the + // first touch is SetTypeMapping in OnModelCreating), so a missing or changed type fails + // there, naming what is missing, rather than on the first row read. + private static readonly System.Type IntervalType = Resolve(); + private static readonly System.Reflection.PropertyInfo Months = IntervalType.GetProperty("Months")!; + private static readonly System.Reflection.PropertyInfo Days = IntervalType.GetProperty("Days")!; + private static readonly System.Reflection.PropertyInfo Time = IntervalType.GetProperty("Time")!; + private static readonly System.Reflection.MethodInfo GetFieldValue = + typeof(System.Data.Common.DbDataReader).GetMethod(nameof(System.Data.Common.DbDataReader.GetFieldValue))!; + + internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Mapping = new ScalarMapping(); + internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping ArrayMapping = new ListMapping(); + + private static System.Type Resolve() + { + var type = System.Type.GetType(IntervalShape.TypeName, throwOnError: false); + if (IntervalShape.Problem(type) is { } problem) throw new System.InvalidOperationException(problem); + return type!; + } + + /// The check of the NpgsqlInterval shape, kept apart from the state above so it can run against any type. + internal static class IntervalShape + { + internal const string TypeName = "NpgsqlTypes.NpgsqlInterval, Npgsql"; + + /// Null when has the shape the mapping reads, else a message naming what is missing. + internal static string? Problem(System.Type? type) + { + const string Lead = "field.duration on Npgsql: the generated DurationInterval mapping reads an interval column as " + + "NpgsqlTypes.NpgsqlInterval (an Int32 Months, an Int32 Days and an Int64 Time in microseconds; " + + "tested with Npgsql 8.0.5), but "; + if (type is null) return Lead + "no type NpgsqlTypes.NpgsqlInterval was found in the loaded Npgsql assembly."; + var missing = new System.Collections.Generic.List(); + foreach (var (name, want) in new[] { ("Months", typeof(int)), ("Days", typeof(int)), ("Time", typeof(long)) }) + { + var property = type.GetProperty(name); + if (property is null || property.PropertyType != want) + missing.Add(want.Name + " " + name); + } + return missing.Count == 0 + ? null + : Lead + type.FullName + " has no " + string.Join(", no ", missing) + " property. Check the Npgsql version the project references."; + } + } + + /// An NpgsqlInterval as a TimeSpan: refused when it has a month or year part, or a span a TimeSpan cannot hold. + public static System.TimeSpan FromInterval(object interval) + { + if ((int)Months.GetValue(interval)! != 0) + throw new System.InvalidCastException("field.duration: the interval has a month or year part, so it is not a fixed-length span"); + var days = (int)Days.GetValue(interval)!; + var micros = (long)Time.GetValue(interval)!; + return System.TimeSpan.FromTicks(checked(days * System.TimeSpan.TicksPerDay + micros * 10)); + } + + /// An interval[] (an NpgsqlInterval array) as the list a duration array property holds. + public static System.Collections.Generic.IList FromIntervals(object intervals) + { + var list = new System.Collections.Generic.List(); + foreach (var interval in (System.Array)intervals) list.Add(FromInterval(interval!)); + return list; + } + + // A span as Postgres interval input: [-]HH:MM:SS[.f], hours unbounded, no day part. + private static string Literal(System.TimeSpan value) + { + long micros = value.Ticks / 10; + bool negative = micros < 0; + long rest = negative ? -micros : micros; + long frac = rest % 1_000_000L, s = rest / 1_000_000L % 60, m = rest / 60_000_000L % 60, h = rest / 3_600_000_000L; + var text = h.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + ":" + m.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + + ":" + s.ToString("00", System.Globalization.CultureInfo.InvariantCulture); + if (frac > 0) text += "." + frac.ToString("D6", System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0'); + return "INTERVAL '" + (negative ? "-" : "") + text + "'"; + } + + private sealed class ScalarMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping + { + public ScalarMapping() : base("interval", typeof(System.TimeSpan)) { } + private ScalarMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new ScalarMapping(parameters); + public override System.Reflection.MethodInfo GetDataReaderMethod() => GetFieldValue.MakeGenericMethod(IntervalType); + public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => + System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(FromInterval))!, + System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => Literal((System.TimeSpan)value); + } + + private sealed class ListMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping + { + private static readonly Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer> ListComparer = new( + (a, b) => a == null ? b == null : b != null && System.Linq.Enumerable.SequenceEqual(a, b), + v => System.Linq.Enumerable.Aggregate(v, 0, (h, e) => System.HashCode.Combine(h, e)), + v => System.Linq.Enumerable.ToList(v)); + + public ListMapping() : base(new RelationalTypeMappingParameters( + new CoreTypeMappingParameters(typeof(System.Collections.Generic.IList), comparer: ListComparer, keyComparer: ListComparer), "interval[]")) { } + private ListMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new ListMapping(parameters); + public override System.Reflection.MethodInfo GetDataReaderMethod() => GetFieldValue.MakeGenericMethod(IntervalType.MakeArrayType()); + public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => + System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(FromIntervals))!, + System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => + "ARRAY[" + string.Join(",", System.Linq.Enumerable.Select((System.Collections.Generic.IEnumerable)value, Literal)) + "]::interval[]"; + } + }} diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/DurationWire.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/DurationWire.g.cs index d9e09d4fa9..57b683d524 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/DurationWire.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/DurationWire.g.cs @@ -7,10 +7,11 @@ // ticks below that are truncated toward zero), one leading `-` for a negative span. Every port // reads that form plus a leading day count (`nD`, exactly 24 hours), an optional `+`, and up to // nine fractional digits. Years, months and weeks are refused: a calendar span has no fixed -// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. The magnitude is -// bounded at 256204778 hours, the largest whole hour a TimeSpan holds, in every port: a longer span -// is refused on parse and on write, never wrapped or rounded. The rule and its cross-port vectors -// are in fixtures/duration-wire/. +// length. System.Text.Json's own TimeSpan form (`01:30:00`) is refused too. A span longer than a +// TimeSpan holds (about 10.7 million days) is refused, never wrapped: that is this port's own limit, +// not a cross-port one. On a database without an interval type (SQLite, MySQL) a duration is stored +// as a 64-bit count of microseconds (ToMicros / FromMicros). The rule and its cross-port vectors are +// in fixtures/duration-wire/. // // ONE source, two homes. This file is the package's production helper (the filter dispatcher // parses its operands through it). The entity generator emits the SAME text, with only the @@ -41,27 +42,9 @@ public static class DurationWire private const long MicrosPerDay = 24L * MicrosPerHour; private const long TicksPerMicro = TimeSpan.TicksPerMillisecond / 1000L; - /// The largest magnitude a duration may have, in hours (the largest whole hour a TimeSpan holds); every port shares the bound. - public const long MaxHours = 256_204_778L; - - private const long MaxMicros = MaxHours * MicrosPerHour; - - /// True when is within the shared bound (at most hours either way, counted in whole microseconds). - public static bool InRange(TimeSpan value) - { - long micros = value.Ticks / TicksPerMicro; - return micros <= MaxMicros && micros >= -MaxMicros; - } - - /// - /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks - /// truncated toward zero. Throws for a span past the shared bound - /// (), which no port can read. - /// + /// The canonical string of : [-]PT[nH][nM][n[.f]S], sub-microsecond ticks truncated toward zero. public static string Format(TimeSpan value) { - if (!InRange(value)) - throw new OverflowException("field.duration: a span longer than " + MaxHours.ToString(CultureInfo.InvariantCulture) + " hours is not a duration"); long micros = value.Ticks / TicksPerMicro; // integer division truncates toward zero bool negative = micros < 0; long rest = negative ? -micros : micros; @@ -86,8 +69,7 @@ public static string Format(TimeSpan value) /// /// Parse an ISO-8601 duration in the accepted form (). False for anything /// else: years, months or weeks, lowercase designators, fractional hours or minutes, a comma, - /// per-component signs, whitespace, out-of-order components, or a span longer than - /// hours (one microsecond over is refused). + /// per-component signs, whitespace, out-of-order components, or a span a TimeSpan cannot hold. /// Fractional seconds past the sixth digit are truncated toward zero. /// public static bool TryParse(string? text, out TimeSpan value) @@ -144,7 +126,6 @@ public static bool TryParse(string? text, out TimeSpan value) i++; } } - if (micros > MaxMicros) return false; value = TimeSpan.FromTicks((negative ? -micros : micros) * TicksPerMicro); } } @@ -155,6 +136,12 @@ public static bool TryParse(string? text, out TimeSpan value) return true; } + /// The stored form on a database without an interval type: whole microseconds, sub-microsecond ticks truncated toward zero. + public static long ToMicros(TimeSpan value) => value.Ticks / TicksPerMicro; + + /// A stored microsecond count as a TimeSpan. Throws for a count a TimeSpan cannot hold: refused, never wrapped. + public static TimeSpan FromMicros(long micros) => TimeSpan.FromTicks(checked(micros * TicksPerMicro)); + /// Parse the accepted form, or throw . public static TimeSpan Parse(string text) => TryParse(text, out var value) diff --git a/server/csharp/MetaObjects/Core/Query/QueryConstants.cs b/server/csharp/MetaObjects/Core/Query/QueryConstants.cs index a7208b3cc6..55efc1b6cc 100644 --- a/server/csharp/MetaObjects/Core/Query/QueryConstants.cs +++ b/server/csharp/MetaObjects/Core/Query/QueryConstants.cs @@ -61,9 +61,9 @@ public static class QueryConstants ["date"] = [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, FILTER_OP_IN, FILTER_OP_IS_NULL], ["time"] = [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, FILTER_OP_IN, FILTER_OP_IS_NULL], ["timestamp"] = [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, FILTER_OP_IN, FILTER_OP_IS_NULL], - // duration: identity-comparison ops only for now. Ordering is not exposed: a text - // column (SQLite, MySQL) cannot order ISO-8601 strings. Adding it later is additive. - ["duration"] = [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_IN, FILTER_OP_IS_NULL], + // duration: an orderable span — a native interval on Postgres, an integer count of + // microseconds on SQLite / MySQL, so ordering holds on every database. + ["duration"] = [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, FILTER_OP_IN, FILTER_OP_IS_NULL], }; /// diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index 57bb390cbe..29176405ef 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -190,7 +190,7 @@ "subType": "duration", "dataType": "string", "extendsBase": true, - "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit." } ] diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt index df0ea2069e..8104eddde0 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireEmitter.kt @@ -38,7 +38,6 @@ object KotlinDurationWireEmitter { |import com.fasterxml.jackson.core.JsonParser |import com.fasterxml.jackson.core.JsonToken |import com.fasterxml.jackson.databind.DeserializationContext - |import com.fasterxml.jackson.databind.JsonMappingException |import com.fasterxml.jackson.databind.JsonNode |import com.fasterxml.jackson.databind.SerializerProvider |import com.fasterxml.jackson.databind.deser.std.StdDeserializer @@ -60,23 +59,10 @@ object KotlinDurationWireEmitter { | private val PG_INTERVAL = Regex("^(-?\\d+) years (-?\\d+) mons (-?\\d+) days (-?\\d+) hours (-?\\d+) mins (-?)(\\d+)(?:\\.(\\d+))? secs$") | private val CALENDAR = Regex("\\b(years?|mons?)\\b") | - | /** - | * The largest magnitude: 256204778 hours (about 29,000 years), the largest whole hour a .NET - | * TimeSpan holds, so every port can read what any port wrote. One microsecond more is refused. - | */ - | const val MAX_HOURS = 256_204_778L - | private val MAX: Duration = Duration.ofHours(MAX_HOURS) - | - | /** [value] when its magnitude is within [MAX_HOURS] hours; otherwise an IllegalArgumentException. */ - | fun checkBound(value: Duration, shown: String?): Duration { - | require(value.abs() <= MAX) { "field.duration: out of range (at most " + MAX_HOURS + " hours either way): " + shown } - | return value - | } - | | /** What a refused value should have been. */ | const val EXPECTED = "an ISO-8601 duration such as PT1H30M (no years, months or weeks)" | - | /** True when [text] is in the accepted ISO-8601 form and within [MAX_HOURS] hours. */ + | /** True when [text] is in the accepted ISO-8601 form and fits a Duration (refused past it, never wrapped). */ | fun isDuration(text: String?): Boolean = | text != null && ACCEPTED.matches(text) && runCatching { parse(text) }.isSuccess | @@ -90,7 +76,7 @@ object KotlinDurationWireEmitter { | Math.addExact(Math.multiplyExact(num(g[2]), 86_400L), Math.multiplyExact(num(g[3]), 3_600L)), | Math.addExact(Math.multiplyExact(num(g[4]), 60L), num(g[5]))) | val d = Duration.ofSeconds(seconds, micros(g[6]) * 1_000L) - | return checkBound(if (g[1] == "-") d.negated() else d, text) + | return if (g[1] == "-") d.negated() else d | } catch (e: ArithmeticException) { | throw IllegalArgumentException("field.duration: out of range: " + text) | } catch (e: NumberFormatException) { @@ -100,7 +86,6 @@ object KotlinDurationWireEmitter { | | /** The canonical wire form of [value] (sub-microsecond precision truncated toward zero). */ | fun format(value: Duration): String { - | checkBound(value, value.toString()) | val negative = value.isNegative | val mag = if (negative) value.negated() else value | val total = mag.seconds @@ -119,7 +104,6 @@ object KotlinDurationWireEmitter { | | /** The Postgres interval input spelling `[-]HH:MM:SS[.f]`: Postgres refuses a signed ISO-8601 duration. */ | fun formatPostgres(value: Duration): String { - | checkBound(value, value.toString()) | val mag = if (value.isNegative) value.negated() else value | val total = mag.seconds | val micros = mag.nano / 1_000L @@ -149,8 +133,8 @@ object KotlinDurationWireEmitter { | "field.duration: the interval " + text + " has a year or month part; a calendar span is not a duration" | } | val secs = Duration.ofSeconds(g[7].toLong(), micros(g[8]) * 1_000L) - | return checkBound(Duration.ofDays(g[3].toLong()).plusHours(g[4].toLong()).plusMinutes(g[5].toLong()) - | .plus(if (g[6] == "-") secs.negated() else secs), text) + | return Duration.ofDays(g[3].toLong()).plusHours(g[4].toLong()).plusMinutes(g[5].toLong()) + | .plus(if (g[6] == "-") secs.negated() else secs) | } | require(!CALENDAR.containsMatchIn(text)) { | "field.duration: the interval " + text + " has a year or month part; a calendar span is not a duration" @@ -161,11 +145,29 @@ object KotlinDurationWireEmitter { | } | val g = m!!.groupValues | val days = Duration.ofDays(if (g[1].isEmpty()) 0L else g[1].toLong()) - | if (g[3].isEmpty()) return checkBound(days, text) + | if (g[3].isEmpty()) return days | val time = Duration.ofSeconds(g[3].toLong() * 3_600L + g[4].toLong() * 60L + g[5].toLong(), micros(g[6]) * 1_000L) - | return checkBound(days.plus(if (g[2] == "-") time.negated() else time), text) + | return days.plus(if (g[2] == "-") time.negated() else time) + | } + | + | /** + | * The 64-bit count of microseconds a SQLite / MySQL column stores (sub-microsecond precision + | * truncated toward zero); past the 64-bit range (that column's limit) it is refused. + | */ + | fun toMicros(value: Duration): Long { + | try { + | val mag = if (value.isNegative) value.negated() else value + | val micros = Math.addExact(Math.multiplyExact(mag.seconds, 1_000_000L), mag.nano / 1_000L) + | return if (value.isNegative) -micros else micros + | } catch (e: ArithmeticException) { + | throw IllegalArgumentException("field.duration: " + value + " is past a 64-bit count of microseconds") + | } | } | + | /** A stored count of microseconds as a duration. */ + | fun fromMicros(micros: Long): Duration = + | Duration.ofSeconds(Math.floorDiv(micros, 1_000_000L), Math.floorMod(micros, 1_000_000L) * 1_000L) + | | /** A duration from a JSON node: an accepted string, anything else is rejected. */ | fun fromNode(node: JsonNode): Duration { | if (node.isTextual) return parse(node.asText()) @@ -185,11 +187,7 @@ object KotlinDurationWireEmitter { | /** Writes a duration as its canonical ISO-8601 string, whatever the host ObjectMapper would do. */ | class Serializer : StdSerializer(Duration::class.java) { | override fun serialize(value: Duration, gen: JsonGenerator, provider: SerializerProvider) { - | // Past the shared bound no port could read it back, so it is not written. - | val text = try { format(value) } catch (e: IllegalArgumentException) { - | throw JsonMappingException.from(gen, e.message, e) - | } - | gen.writeString(text) + | gen.writeString(format(value)) | } | } | diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index 417d02eec3..9eeb922b81 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -1750,15 +1750,14 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase` over the Postgres-native - * `INTERVAL`, and elsewhere a text column holding the canonical ISO-8601 string (so an - * equality filter on the text matches one spelling per span). Postgres refuses a signed + * `INTERVAL`, and elsewhere a BIGINT count of microseconds (so filters and sorts order it). Postgres refuses a signed * ISO-8601 duration as interval input, so the value binds in the interval spelling * `[-]HH:MM:SS[.f]`, as text under a `CAST(? AS INTERVAL)` parameter marker (a bare * varchar parameter is refused where an interval goes). A read takes the * driver's value — pgjdbc's `PGInterval`, or the stored text — through * `MetaDurationWire.fromStored`, which refuses an interval with a year or month part. * - `MetaDurationArrayColumnType` — an `isArray` duration: `INTERVAL[]` on Postgres, a JSON - * text array of canonical strings on MySQL and SQLite. + * text array of microsecond counts on MySQL and SQLite. * * The text differs by [ExposedApi] only in the array bind (and the imports). */ @@ -1778,18 +1777,27 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase value + | is Number -> MetaDurationWire.fromMicros(value.toLong()) + | else -> MetaDurationWire.fromStored(value.toString()) + |} + | + |/** + | * GENERATED — do not hand-edit. A `java.time.Duration` column: native `INTERVAL` on Postgres, and + | * elsewhere a BIGINT count of microseconds, so a range filter and a sort order it as a number. + | */ |internal class MetaDurationColumnType : ColumnType() { - | override fun sqlType(): String = - | if (isPostgres()) "INTERVAL" else if (isMySql()) "VARCHAR(64)" else currentDialect.dataTypeProvider.textType() - | override fun valueFromDB(value: Any): Duration = - | if (value is Duration) value else MetaDurationWire.fromStored(value.toString()) + | override fun sqlType(): String = if (isPostgres()) "INTERVAL" else "BIGINT" + | override fun valueFromDB(value: Any): Duration = durationOf(value) | override fun notNullValueToDB(value: Duration): Any = stored(value) - | override fun nonNullValueToString(value: Duration): String = "'" + stored(value) + "'" + | override fun nonNullValueToString(value: Duration): String = + | if (isPostgres()) "'" + stored(value) + "'" else stored(value).toString() | // The value binds as text; Postgres will not take a varchar where an interval goes, so the | // marker casts it (an explicit cast from text to interval is always allowed). | override fun parameterMarker(value: Duration?): String = if (isPostgres()) "CAST(? AS INTERVAL)" else "?" @@ -1799,16 +1807,21 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase = | registerColumn(name, MetaDurationColumnType()) | - |/** GENERATED — do not hand-edit. An `isArray` duration column: `INTERVAL[]` on Postgres, a JSON text array elsewhere. */ + |/** + | * GENERATED — do not hand-edit. An `isArray` duration column: `INTERVAL[]` on Postgres, and elsewhere + | * a JSON text array of microsecond counts. + | */ |internal class MetaDurationArrayColumnType : ColumnType>() { - | private fun element(value: Any): Duration = if (value is Duration) value else MetaDurationWire.fromStored(value.toString()) - | private fun json(value: List): String = value.joinToString(",", "[", "]") { "\"" + MetaDurationWire.format(it) + "\"" } + | private fun element(value: Any): Duration = durationOf(value) + | private fun json(value: List): String = value.joinToString(",", "[", "]") { MetaDurationWire.toMicros(it).toString() } | override fun sqlType(): String = if (isPostgres()) "INTERVAL[]" else if (isMySql()) "JSON" else "TEXT" | override fun valueFromDB(value: Any): List = when (value) { | is java.sql.Array -> (value.array as Array<*>).map { element(it!!) } | is Array<*> -> value.map { element(it!!) } | is List<*> -> value.map { element(it!!) } - | else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { MetaDurationWire.fromNode(it) } + | else -> com.fasterxml.jackson.databind.ObjectMapper().readTree(value.toString()).map { + | if (it.isIntegralNumber) MetaDurationWire.fromMicros(it.longValue()) else MetaDurationWire.fromNode(it) + | } | } | override fun notNullValueToDB(value: List): Any = | if (isPostgres()) value.map { MetaDurationWire.formatPostgres(it) }.toTypedArray() else json(value) diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireTest.kt index c38a89123b..e22d64a40f 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinDurationWireTest.kt @@ -96,7 +96,10 @@ class KotlinDurationWireTest { assertTrue("MetaDurationWire.parse" in controller, controller) assertTrue("MetaDurationWire.fromNode(body.get(\"holdFor\"))" in controller, controller) val allowlist = files.getValue("acme/ops/JobFilterAllowlist.kt") - assertFalse("\"gt\"" in allowlist.substringAfter("\"holdFor\"").substringBefore("\n"), allowlist) + // A duration orders on every DB (interval on Postgres, microsecond count elsewhere). + val holdForOps = allowlist.substringAfter("\"holdFor\" to setOf(").substringBefore(")") + for (op in listOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull")) assertTrue("\"$op\"" in holdForOps, allowlist) + assertTrue("JobTable.holdFor greater (p.value as Duration)" in controller, controller) // Generated code names no MetaObjects package. for ((path, src) in files) { val code = src.lineSequence().filterNot { it.trimStart().let { l -> l.startsWith("*") || l.startsWith("/*") || l.startsWith("//") } } @@ -147,8 +150,19 @@ class KotlinDurationWireTest { } assertFailsWith { call("fromStored", "1 years 2 mons 3 days 4 hours 5 mins 6.0 secs") } assertEquals("-PT1.123456S", call("format", Duration.ofSeconds(-1, -123_456_789))) - // The shared bound holds on write too, and no default locale changes the digits. - assertFailsWith { call("format", Duration.ofHours(256_204_778).plusNanos(1_000)) } + // The stored microsecond count (SQLite / MySQL). + for (c in v.get("storedMicros")) { + val d = call("parse", c.get("in").asText()) + assertEquals(c.get("out").asText().toLong(), call("toMicros", d), "storedMicros ${c.get("in")}") + assertEquals(c.get("in").asText(), call("format", call("fromMicros", c.get("out").asText().toLong()))) + } + assertEquals(-1_000_000L, call("toMicros", Duration.ofSeconds(-1, -500))) + assertFailsWith { call("toMicros", Duration.ofSeconds(Long.MAX_VALUE / 1_000_000L + 1)) } + // Java's Duration range is the only limit, refused past it, never wrapped. + assertEquals("PT2562047788015215H", call("format", call("parse", "PT2562047788015215H"))) + assertFailsWith { call("parse", "PT9223372036854775808S") } + assertEquals(false, call("isDuration", "PT99999999999999999999H")) + // No default locale changes the digits. val saved = java.util.Locale.getDefault() try { java.util.Locale.setDefault(java.util.Locale.forLanguageTag("ar-EG-u-nu-arab")) diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDuration.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDuration.java index 3ee24c2ad2..e94fe3aa37 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDuration.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDuration.java @@ -34,29 +34,7 @@ public static final class InvalidDurationException extends IllegalArgumentExcept public InvalidDurationException(String message) { super(message); } } - /** - * The largest magnitude a duration may have: 256204778 hours (about 29,000 years), the largest - * whole hour a .NET {@code TimeSpan} holds, so every port can read what any port wrote. One - * microsecond more is refused, on read and on write. - */ - public static final long MAX_HOURS = 256_204_778L; - - private static final Duration MAX = Duration.ofHours(MAX_HOURS); - - /** - * {@code d} when its magnitude is within {@link #MAX_HOURS} hours. - * - * @throws InvalidDurationException when it is not - */ - public static Duration checkBound(Duration d, String shown) { - if (d.abs().compareTo(MAX) > 0) { - throw new InvalidDurationException("field.duration: out of range (at most " + MAX_HOURS - + " hours either way): \"" + shown + "\""); - } - return d; - } - - /** True iff {@code s} is in the accepted form and within {@link #MAX_HOURS} hours. */ + /** True iff {@code s} is in the accepted form and fits a {@link Duration} (refused past it, never wrapped). */ public static boolean isDuration(String s) { if (s == null || !ACCEPTED.matcher(s).matches()) return false; try { @@ -68,8 +46,8 @@ public static boolean isDuration(String s) { } /** - * Parse an accepted ISO-8601 duration (sub-microsecond digits truncated toward zero), at most - * {@link #MAX_HOURS} hours either way. + * Parse an accepted ISO-8601 duration (sub-microsecond digits truncated toward zero). A + * {@link Duration}'s own range is the only limit. * * @throws InvalidDurationException when {@code s} is not in the accepted form or overflows */ @@ -86,19 +64,14 @@ public static Duration parse(String s) { long micros = frac == null ? 0L : Long.parseLong(frac.length() >= 6 ? frac.substring(0, 6) : (frac + "000000").substring(0, 6)); Duration d = Duration.ofSeconds(seconds, micros * 1_000L); - return checkBound("-".equals(m.group(1)) ? d.negated() : d, s); + return "-".equals(m.group(1)) ? d.negated() : d; } catch (ArithmeticException | NumberFormatException e) { throw new InvalidDurationException("field.duration: out of range: \"" + s + "\""); } } - /** - * The canonical wire form of {@code d} (sub-microsecond precision truncated toward zero). - * - * @throws InvalidDurationException past {@link #MAX_HOURS} hours, which no port could read back - */ + /** The canonical wire form of {@code d} (sub-microsecond precision truncated toward zero). */ public static String format(Duration d) { - checkBound(d, d.toString()); boolean negative = d.isNegative(); Duration mag = negative ? d.negated() : d; long total = mag.getSeconds(); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDurationSerializer.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDurationSerializer.java index 5ea6683633..520502341d 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDurationSerializer.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/runtime/CanonicalDurationSerializer.java @@ -24,11 +24,6 @@ public CanonicalDurationSerializer() { @Override public void serialize(Duration value, JsonGenerator gen, SerializerProvider provider) throws IOException { - try { - gen.writeString(CanonicalDuration.format(value)); - } catch (CanonicalDuration.InvalidDurationException e) { - // Past the shared bound: no port could read it back, so it is not written. - throw com.fasterxml.jackson.databind.JsonMappingException.from(gen, e.getMessage(), e); - } + gen.writeString(CanonicalDuration.format(value)); } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringDurationWireCompileRunTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringDurationWireCompileRunTest.java index a7bc5e8409..091cb1b47b 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringDurationWireCompileRunTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringDurationWireCompileRunTest.java @@ -38,7 +38,7 @@ * {@code field.duration}, end to end over GENERATED code: the DTO, the value-object record and the * Patch type a duration as {@code java.time.Duration}, write the canonical ISO-8601 string and read * the accepted form only — whatever the host ObjectMapper's JavaTimeModule would do — and the - * allowlist gives a duration the identity-comparison band (eq/ne/in/isNull). + * allowlist gives a duration the ordering band (eq/ne/gt/gte/lt/lte/in/isNull). */ public class SpringDurationWireCompileRunTest { @@ -135,12 +135,11 @@ private void run(WireFormat.Decimals decimals, ObjectMapper mapper) throws Excep } } - // The filter band: identity comparison only (a text column cannot order ISO strings). + // The filter band orders: a native interval on Postgres, a microsecond count elsewhere. Class allow = cl.loadClass(PKG + ".JobFilterAllowlist"); @SuppressWarnings("unchecked") Map> ops = (Map>) allow.getField("OPS_BY_FIELD").get(null); - assertEquals(Set.of("eq", "ne", "in", "isNull"), ops.get("holdFor")); - assertFalse(ops.get("holdFor").contains("gt")); + assertEquals(Set.of("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), ops.get("holdFor")); } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/runtime/DurationWireTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/runtime/DurationWireTest.java index 26efe4bd77..87d4c94e36 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/runtime/DurationWireTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/runtime/DurationWireTest.java @@ -96,12 +96,16 @@ public void formattingIgnoresTheDefaultLocalesDigits() throws Exception { } @Test - public void aValuePastTheSharedBoundIsNotWritten() { - try { - MAPPER.writeValueAsString(new Holder(Duration.ofHours(CanonicalDuration.MAX_HOURS).plusNanos(1_000))); - fail("one microsecond past the bound must not be written"); - } catch (com.fasterxml.jackson.core.JsonProcessingException expected) { - // refused + public void javaDurationsOwnRangeIsTheOnlyLimit() { + assertEquals("PT2562047788015215H", CanonicalDuration.format(CanonicalDuration.parse("PT2562047788015215H"))); + for (String tooLong : new String[]{"PT9223372036854775808S", "PT99999999999999999999H"}) { + assertFalse(tooLong, CanonicalDuration.isDuration(tooLong)); + try { + CanonicalDuration.parse(tooLong); + fail("must refuse, never wrap: " + tooLong); + } catch (CanonicalDuration.InvalidDurationException expected) { + // refused + } } } } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt new file mode 100644 index 0000000000..1dff73a42e --- /dev/null +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/DurationOrderingScenarioTest.kt @@ -0,0 +1,38 @@ +package com.metaobjects.integration.kotlin + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertDoesNotThrow +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Path +import kotlin.test.assertEquals + +/** + * field.duration orders on every engine (port-local scenario `duration-ordering/`): a range + * filter, an equality across spellings and a sort, through Exposed, on Postgres (native interval) + * and SQLite (a 64-bit microsecond count). + */ +internal class DurationOrderingScenarioTest { + + private fun scenario(): Scenarios.QueryScenario { + val dir = Path.of(DurationOrderingScenarioTest::class.java.getResource("/duration-ordering")!!.toURI()) + val all = ScenarioLoader.loadQueries(dir) + assertEquals(1, all.size) + return all[0] + } + + @Test + fun `orders on SQLite`(@TempDir dir: Path) { + val s = scenario() + assertDoesNotThrow { + QueryScenarioRunner.run(s, "jdbc:sqlite:${dir.resolve("duration.db")}", "", "", ScenarioEngine.SQLITE) + } + } + + @Test + fun `orders on Postgres`() { + val s = scenario() + assertDoesNotThrow { + PostgresContainer().use { pg -> QueryScenarioRunner.run(s, pg) } + } + } +} diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/MetaDurationColumnType.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/MetaDurationColumnType.kt index 9694061d28..02c0155ca2 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/MetaDurationColumnType.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/MetaDurationColumnType.kt @@ -14,23 +14,27 @@ import java.time.Duration * [com.metaobjects.generator.kotlin.KotlinExposedTableGenerator] emits, over the metadata * module's [DurationWire] (the generated copy carries its own `MetaDurationWire`). * - * A `Column` over the Postgres-native `INTERVAL` (the canonical ISO-8601 - * string on a text column elsewhere). Postgres refuses a signed ISO-8601 duration as interval + * A `Column` over the Postgres-native `INTERVAL`, and elsewhere (SQLite, MySQL) + * a BIGINT count of microseconds. Postgres refuses a signed ISO-8601 duration as interval * input, so the value binds in the interval spelling `[-]HH:MM:SS[.f]` under a * `CAST(? AS INTERVAL)` marker; the read takes the interval's text (`ResultSet.getString`, the * `postgres` IntervalStyle) and refuses one with a year or month part. */ internal class MetaDurationColumnType : ColumnType() { private fun isPostgres(): Boolean = currentDialect.name.equals("postgresql", ignoreCase = true) - override fun sqlType(): String = if (isPostgres()) "INTERVAL" else currentDialect.dataTypeProvider.textType() - override fun valueFromDB(value: Any): Duration = - if (value is Duration) value else DurationWire.fromStored(value.toString()) + override fun sqlType(): String = if (isPostgres()) "INTERVAL" else "BIGINT" + override fun valueFromDB(value: Any): Duration = when (value) { + is Duration -> value + is Number -> DurationWire.fromMicros(value.toLong()) + else -> DurationWire.fromStored(value.toString()) + } override fun notNullValueToDB(value: Duration): Any = - if (isPostgres()) DurationWire.formatPostgres(value) else DurationWire.format(value) - override fun nonNullValueToString(value: Duration): String = "'" + notNullValueToDB(value) + "'" + if (isPostgres()) DurationWire.formatPostgres(value) else DurationWire.toMicros(value) + override fun nonNullValueToString(value: Duration): String = + if (isPostgres()) "'" + notNullValueToDB(value) + "'" else notNullValueToDB(value).toString() override fun parameterMarker(value: Duration?): String = if (isPostgres()) "CAST(? AS INTERVAL)" else "?" - /** Read the interval's text, never pgjdbc's PGInterval object. */ - override fun readObject(rs: ResultSet, index: Int): Any? = rs.getString(index) + /** Read the interval's text on Postgres (never pgjdbc's PGInterval object), the integer elsewhere. */ + override fun readObject(rs: ResultSet, index: Int): Any? = if (isPostgres()) rs.getString(index) else rs.getObject(index) } /** Column builder for `field.duration`: a `Column`. */ diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/duration/GeneratedDurationRoundTripTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/duration/GeneratedDurationRoundTripTest.kt new file mode 100644 index 0000000000..903c39232f --- /dev/null +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/duration/GeneratedDurationRoundTripTest.kt @@ -0,0 +1,135 @@ +package com.metaobjects.integration.kotlin.tables.duration + +import com.metaobjects.generator.kotlin.KotlinEntityGenerator +import com.metaobjects.generator.kotlin.KotlinExposedTableGenerator +import com.metaobjects.integration.kotlin.PostgresContainer +import com.metaobjects.metadata.ktx.loadString +import com.tschuchort.compiletesting.KotlinCompilation +import com.tschuchort.compiletesting.SourceFile +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.isRegularFile +import kotlin.io.path.readText +import kotlin.test.assertEquals + +/** + * The GENERATED (exposedApi=0) `field.duration` columns, compiled and run: a scalar and an + * `isArray` duration round-trip, a range filter and a sort order spans (never text), on SQLite (a + * BIGINT microsecond count, a JSON array of counts) and Postgres (INTERVAL, INTERVAL[]). + */ +@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class) +class GeneratedDurationRoundTripTest { + + private val fixture = """{ + "metadata.root": { "package": "durdemo", "children": [ + { "object.entity": { "name": "Timer", "children": [ + { "source.rdb": { "@table": "timers" } }, + { "field.long": { "name": "id", "@required": true } }, + { "field.duration": { "name": "timeout", "@required": true } }, + { "field.duration": { "name": "backoff", "isArray": true } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } } + ] } + }""".trimIndent() + + private val driverSource = """ + package durdemo + + import org.jetbrains.exposed.sql.Database + import org.jetbrains.exposed.sql.SchemaUtils + import org.jetbrains.exposed.sql.SortOrder + import org.jetbrains.exposed.sql.insert + import org.jetbrains.exposed.sql.selectAll + import org.jetbrains.exposed.sql.transactions.TransactionManager + import org.jetbrains.exposed.sql.transactions.transaction + import java.time.Duration + + object DurationRoundTripDriver { + fun run(jdbcUrl: String, driver: String, user: String, pass: String): String { + val db = Database.connect(jdbcUrl, driver = driver, user = user, password = pass) + return transaction(db) { + SchemaUtils.create(TimerTable) + val spans = mapOf( + 1L to Duration.ofMinutes(30), + 2L to Duration.ofMinutes(90), + 3L to Duration.ofSeconds(-90, -500_000_000), + 4L to Duration.ofHours(26), + ) + for ((id, d) in spans) { + TimerTable.insert { + it[TimerTable.id] = id + it[TimerTable.timeout] = d + it[TimerTable.backoff] = listOf(d, Duration.ofNanos(1_000)) + } + } + val longer = TimerTable.selectAll() + .where { TimerTable.timeout greater Duration.ofHours(1) } + .orderBy(TimerTable.timeout, SortOrder.DESC) + .map { it[TimerTable.id] } + val all = TimerTable.selectAll().orderBy(TimerTable.timeout, SortOrder.ASC).map { it[TimerTable.id] } + val r3 = TimerTable.selectAll().where { TimerTable.id eq 3L }.single() + val problems = mutableListOf() + if (longer != listOf(4L, 2L)) problems += "gt + desc: " + longer + if (all != listOf(3L, 1L, 2L, 4L)) problems += "asc: " + all + if (r3[TimerTable.timeout] != spans.getValue(3L)) problems += "timeout: " + r3[TimerTable.timeout] + if (r3[TimerTable.backoff] != listOf(spans.getValue(3L), Duration.ofNanos(1_000))) problems += "backoff: " + r3[TimerTable.backoff] + if (!jdbcUrl.startsWith("jdbc:postgresql")) { + var kind: String? = null + TransactionManager.current().exec("SELECT typeof(timeout), timeout FROM timers WHERE id = 3") { rs -> + rs.next(); kind = rs.getString(1) + " " + rs.getString(2) + } + if (kind != "integer -90500000") problems += "stored: " + kind + } + if (problems.isEmpty()) "OK" else problems.joinToString("; ") + } + } + } + """.trimIndent() + + private fun compileDriver(): ClassLoader { + val outDir = Files.createTempDirectory("duration-rt-") + try { + val loader = loadString("duration-rt", fixture) + for (g in listOf(KotlinEntityGenerator(), KotlinExposedTableGenerator())) { + g.setArgs(mapOf("outputDir" to outDir.toString())) + g.execute(loader) + } + val sources = Files.walk(outDir).use { s -> + s.filter { it.isRegularFile() && it.toString().endsWith(".kt") } + .map { SourceFile.kotlin(outDir.relativize(it).toString().replace('/', '_'), it.readText()) } + .toList() + }.toMutableList() + sources.add(SourceFile.kotlin("DurationRoundTripDriver.kt", driverSource)) + val result = KotlinCompilation().apply { + this.sources = sources + inheritClassPath = true + messageOutputStream = System.out + }.compile() + assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode, result.messages) + return result.classLoader + } finally { + outDir.toFile().deleteRecursively() + } + } + + private fun drive(cl: ClassLoader, url: String, driver: String, user: String, pass: String): String { + val cls = cl.loadClass("durdemo.DurationRoundTripDriver") + return cls.getMethod("run", String::class.java, String::class.java, String::class.java, String::class.java) + .invoke(cls.getField("INSTANCE").get(null), url, driver, user, pass) as String + } + + @Test + fun `generated duration columns order and round-trip on SQLite`(@TempDir dir: Path) { + assertEquals("OK", drive(compileDriver(), "jdbc:sqlite:${dir.resolve("d.db")}", "org.sqlite.JDBC", "", "")) + } + + @Test + fun `generated duration columns order and round-trip on Postgres`() { + val cl = compileDriver() + PostgresContainer().use { pg -> + assertEquals("OK", drive(cl, pg.jdbcUrl, "org.postgresql.Driver", pg.username, pg.password)) + } + } +} diff --git a/server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml b/server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml new file mode 100644 index 0000000000..05518659bd --- /dev/null +++ b/server/java/integration-tests-kotlin/src/test/resources/duration-ordering/duration-ordering.yaml @@ -0,0 +1,71 @@ +name: duration-ordering +description: | + Port-local (Kotlin / Exposed runner; the SQLite seed spells timestamps the way Exposed's SQLite + dialect reads them): field.duration orders on every engine. Postgres keeps a + native interval; SQLite stores a 64-bit count of microseconds. A range filter (gt / lte), an + equality on a differently-spelled span, and a sort all compare spans, never text. +engines: [postgres, sqlite] +seed-data: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', '00:30:00'), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', '01:30:00'), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', '-00:01:30'), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', '26:00:00'), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +seed-data-engine: + sqlite: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', 1800000000), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', 5400000000), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', -90000000), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', 93600000000), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01 10:00:00.000', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +queries: + - name: longer-than-an-hour + op: count + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + expect: 2 + + - name: at-most-thirty-minutes-includes-a-negative-span + op: count + entity: AllTypes + filter: { durationVal: { lte: "PT30M" } } + expect: 2 + + - name: equality-across-spellings + op: count + entity: AllTypes + filter: { durationVal: { eq: "PT5400S" } } + expect: 1 + + - name: longer-than-an-hour-longest-first + op: list + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + sort: [{ field: durationVal, dir: desc }] + expect: + - { id: "00000004-0000-4000-8000-000000000004", sVal: "long", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000004-0000-4000-8000-000000000004", uriVal: "urn:example:long", + inetVal: "10.0.0.4", inet6Val: "fe80::4", durationVal: "PT26H", settings: null, labels: null } + - { id: "00000002-0000-4000-8000-000000000002", sVal: "ninety", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000002-0000-4000-8000-000000000002", uriVal: "urn:example:ninety", + inetVal: "10.0.0.2", inet6Val: "fe80::2", durationVal: "PT1H30M", settings: null, labels: null } + + - name: shortest-two + op: list + entity: AllTypes + filter: { durationVal: { isNull: false } } + sort: [{ field: durationVal, dir: asc }] + limit: 2 + expect: + - { id: "00000003-0000-4000-8000-000000000003", sVal: "minus", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000003-0000-4000-8000-000000000003", uriVal: "urn:example:minus", + inetVal: "10.0.0.3", inet6Val: "fe80::3", durationVal: "-PT1M30S", settings: null, labels: null } + - { id: "00000001-0000-4000-8000-000000000001", sVal: "thirty", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000001-0000-4000-8000-000000000001", uriVal: "urn:example:thirty", + inetVal: "10.0.0.1", inet6Val: "fe80::1", durationVal: "PT30M", settings: null, labels: null } diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java new file mode 100644 index 0000000000..5b9f60c11f --- /dev/null +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/DurationOrderingScenarioTests.java @@ -0,0 +1,59 @@ +package com.metaobjects.integration; + +import com.metaobjects.integration.Scenarios.QueryScenario; +import com.metaobjects.object.value.ValueObject; +import com.metaobjects.registry.ObjectClassRegistry; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * field.duration orders on every engine (port-local scenario {@code duration-ordering/}): a range + * filter, an equality across spellings and a sort, through OMDB, on Postgres (native interval) + * and SQLite (a 64-bit microsecond count). + */ +final class DurationOrderingScenarioTests { + + private static final Path CORPUS = ScenarioLoader.findCorpusRoot(); + + private static QueryScenario scenario() throws URISyntaxException { + Path dir = Path.of(DurationOrderingScenarioTests.class.getResource("/duration-ordering").toURI()); + List all = ScenarioLoader.loadQueries(dir); + assertEquals(1, all.size()); + return all.get(0); + } + + @BeforeAll + static void beforeAll() { + ObjectClassRegistry reg = new ObjectClassRegistry(); + reg.register(() -> Map.of("fitness::AllTypes", ValueObject.class)); + ObjectClassRegistry.setGlobal(reg); + } + + @Test + void ordersOnSqlite() throws Exception { + QueryScenario s = scenario(); + assertDoesNotThrow(() -> { + try (SqliteDatabase db = new SqliteDatabase()) { + QueryScenarioRunner.run(s, db, CORPUS.resolve("canonical"), ScenarioEngine.SQLITE); + } + }); + } + + @Test + void ordersOnPostgres() throws Exception { + QueryScenario s = scenario(); + assertDoesNotThrow(() -> { + try (PostgresContainer pg = new PostgresContainer()) { + QueryScenarioRunner.run(s, pg, CORPUS.resolve("canonical")); + } + }); + } +} diff --git a/server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml b/server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml new file mode 100644 index 0000000000..a9f12641ac --- /dev/null +++ b/server/java/integration-tests/src/test/resources/duration-ordering/duration-ordering.yaml @@ -0,0 +1,70 @@ +name: duration-ordering +description: | + Port-local (Java / Kotlin JVM runners): field.duration orders on every engine. Postgres keeps a + native interval; SQLite stores a 64-bit count of microseconds. A range filter (gt / lte), an + equality on a differently-spelled span, and a sort all compare spans, never text. +engines: [postgres, sqlite] +seed-data: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', '00:30:00'), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', '01:30:00'), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', '-00:01:30'), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', '26:00:00'), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, true, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +seed-data-engine: + sqlite: | + INSERT INTO "all_types" ("id", "sVal", "iVal", "lVal", "dVal", "fVal", "decVal", "bVal", "dateVal", "timeVal", "tsVal", "tsTzVal", "moneyVal", "enumVal", "uuidVal", "uriVal", "inetVal", "inet6Val", "durationVal") VALUES + ('00000001-0000-4000-8000-000000000001', 'thirty', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000001-0000-4000-8000-000000000001', 'urn:example:thirty', '10.0.0.1', 'fe80::1', 1800000000), + ('00000002-0000-4000-8000-000000000002', 'ninety', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000002-0000-4000-8000-000000000002', 'urn:example:ninety', '10.0.0.2', 'fe80::2', 5400000000), + ('00000003-0000-4000-8000-000000000003', 'minus', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000003-0000-4000-8000-000000000003', 'urn:example:minus', '10.0.0.3', 'fe80::3', -90000000), + ('00000004-0000-4000-8000-000000000004', 'long', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000004-0000-4000-8000-000000000004', 'urn:example:long', '10.0.0.4', 'fe80::4', 93600000000), + ('00000005-0000-4000-8000-000000000005', 'none', 1, 1, 0.5, 0.5, 1.5, 1, '2026-01-01', '10:00:00', '2026-01-01T10:00:00', '2026-01-01T10:00:00.000Z', 100, 'LOW', '00000005-0000-4000-8000-000000000005', 'urn:example:none', '10.0.0.5', 'fe80::5', NULL); +queries: + - name: longer-than-an-hour + op: count + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + expect: 2 + + - name: at-most-thirty-minutes-includes-a-negative-span + op: count + entity: AllTypes + filter: { durationVal: { lte: "PT30M" } } + expect: 2 + + - name: equality-across-spellings + op: count + entity: AllTypes + filter: { durationVal: { eq: "PT5400S" } } + expect: 1 + + - name: longer-than-an-hour-longest-first + op: list + entity: AllTypes + filter: { durationVal: { gt: "PT1H" } } + sort: [{ field: durationVal, dir: desc }] + expect: + - { id: "00000004-0000-4000-8000-000000000004", sVal: "long", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000004-0000-4000-8000-000000000004", uriVal: "urn:example:long", + inetVal: "10.0.0.4", inet6Val: "fe80::4", durationVal: "PT26H", settings: null, labels: null } + - { id: "00000002-0000-4000-8000-000000000002", sVal: "ninety", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000002-0000-4000-8000-000000000002", uriVal: "urn:example:ninety", + inetVal: "10.0.0.2", inet6Val: "fe80::2", durationVal: "PT1H30M", settings: null, labels: null } + + - name: shortest-two + op: list + entity: AllTypes + filter: { durationVal: { isNull: false } } + sort: [{ field: durationVal, dir: asc }] + limit: 2 + expect: + - { id: "00000003-0000-4000-8000-000000000003", sVal: "minus", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000003-0000-4000-8000-000000000003", uriVal: "urn:example:minus", + inetVal: "10.0.0.3", inet6Val: "fe80::3", durationVal: "-PT1M30S", settings: null, labels: null } + - { id: "00000001-0000-4000-8000-000000000001", sVal: "thirty", iVal: 1, lVal: "1", dVal: "0.5", fVal: "0.5", decVal: "1.5", bVal: true, + dateVal: "2026-01-01", timeVal: "10:00:00", tsVal: "2026-01-01T10:00:00", tsTzVal: "2026-01-01T10:00:00Z", + moneyVal: "100", enumVal: "LOW", intEnumVal: null, uuidVal: "00000001-0000-4000-8000-000000000001", uriVal: "urn:example:thirty", + inetVal: "10.0.0.1", inet6Val: "fe80::1", durationVal: "PT30M", settings: null, labels: null } diff --git a/server/java/metadata/src/main/java/com/metaobjects/field/DurationWire.java b/server/java/metadata/src/main/java/com/metaobjects/field/DurationWire.java index d23f6b5336..a4cf5c8cda 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/field/DurationWire.java +++ b/server/java/metadata/src/main/java/com/metaobjects/field/DurationWire.java @@ -62,34 +62,14 @@ private DurationWire() {} private static final Pattern POSTGRES_CALENDAR = Pattern.compile("\\b(years?|mons?)\\b"); - /** - * The largest magnitude a duration may have: 256204778 hours (about 29,000 years), the largest - * whole hour a .NET {@code TimeSpan} holds, so every port can read what any port wrote. One - * microsecond more is refused, on parse and on read. - */ - public static final long MAX_HOURS = 256_204_778L; - - /** {@link #MAX_HOURS} as a {@link Duration}. */ - public static final Duration MAX = Duration.ofHours(MAX_HOURS); - - /** - * {@code d} when its magnitude is within {@link #MAX}. - * - * @throws IllegalArgumentException when it is not ({@code shown} names the input) - */ - public static Duration checkBound(Duration d, String shown) { - if (d.abs().compareTo(MAX) > 0) { - throw new IllegalArgumentException("field.duration: out of range (at most " + MAX_HOURS - + " hours either way): " + quote(shown)); - } - return d; - } - /** What a refused value is told it should be. */ public static final String EXPECTED = "an ISO-8601 duration such as PT1H30M (no years, months or weeks)"; - /** True iff {@code s} is in the accepted ISO-8601 form and within {@link #MAX_HOURS} hours. */ + /** + * True iff {@code s} is in the accepted ISO-8601 form and fits a {@link Duration} (its own range + * is the only limit; a value past it is refused, never wrapped). + */ public static boolean isDuration(String s) { if (s == null || !ACCEPTED.matcher(s).matches()) return false; try { @@ -117,7 +97,7 @@ public static Duration parse(String s) { Math.multiplyExact(num(m.group(3)), 3_600L)), Math.addExact(Math.multiplyExact(num(m.group(4)), 60L), num(m.group(5)))); Duration d = Duration.ofSeconds(seconds, micros(m.group(6)) * 1_000L); - return checkBound("-".equals(m.group(1)) ? d.negated() : d, s); + return "-".equals(m.group(1)) ? d.negated() : d; } catch (ArithmeticException e) { throw new IllegalArgumentException("field.duration: out of range: " + quote(s), e); } @@ -131,7 +111,6 @@ public static String canonicalize(String s) { /** The canonical wire form of {@code d} (sub-microsecond precision truncated toward zero). */ public static String format(Duration d) { if (d == null) throw new IllegalArgumentException("field.duration: null is not a duration"); - checkBound(d, d.toString()); boolean negative = d.isNegative(); Duration mag = negative ? d.negated() : d; long total = mag.getSeconds(); @@ -154,7 +133,6 @@ public static String format(Duration d) { /** The Postgres interval input spelling of {@code d}: {@code [-]HH:MM:SS[.f]}, no day part. */ public static String formatPostgres(Duration d) { if (d == null) throw new IllegalArgumentException("field.duration: null is not a duration"); - checkBound(d, d.toString()); boolean negative = d.isNegative(); Duration mag = negative ? d.negated() : d; long total = mag.getSeconds(); @@ -189,11 +167,11 @@ public static Duration parsePostgres(String s) { } try { Duration days = Duration.ofSeconds(Math.multiplyExact(m.group(1) == null ? 0L : Long.parseLong(m.group(1)), 86_400L)); - if (m.group(3) == null) return checkBound(days, s); + if (m.group(3) == null) return days; long secs = Math.addExact(Math.multiplyExact(Long.parseLong(m.group(3)), 3_600L), Long.parseLong(m.group(4)) * 60L + Long.parseLong(m.group(5))); Duration time = Duration.ofSeconds(secs, micros(m.group(6)) * 1_000L); - return checkBound(days.plus("-".equals(m.group(2)) ? time.negated() : time), s); + return days.plus("-".equals(m.group(2)) ? time.negated() : time); } catch (ArithmeticException | NumberFormatException e) { throw new IllegalArgumentException("field.duration: interval out of range: " + quote(s), e); } @@ -212,6 +190,29 @@ public static String canonicalizeStored(String s) { return format(fromStored(s)); } + /** + * The 64-bit count of microseconds a SQLite / MySQL column stores (sub-microsecond precision + * truncated toward zero). + * + * @throws IllegalArgumentException past the 64-bit range, which is that column's limit + */ + public static long toMicros(Duration d) { + try { + boolean negative = d.isNegative(); + Duration mag = negative ? d.negated() : d; + long micros = Math.addExact(Math.multiplyExact(mag.getSeconds(), 1_000_000L), mag.getNano() / 1_000L); + return negative ? -micros : micros; + } catch (ArithmeticException tooLong) { + throw new IllegalArgumentException( + "field.duration: " + d + " is past a 64-bit count of microseconds", tooLong); + } + } + + /** A stored count of microseconds as a duration. */ + public static Duration fromMicros(long micros) { + return Duration.ofSeconds(Math.floorDiv(micros, 1_000_000L), Math.floorMod(micros, 1_000_000L) * 1_000L); + } + // ── helpers ── private static long num(String digits) { diff --git a/server/java/metadata/src/main/java/com/metaobjects/query/FilterOps.java b/server/java/metadata/src/main/java/com/metaobjects/query/FilterOps.java index bdf1f53ce0..09f77297e8 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/query/FilterOps.java +++ b/server/java/metadata/src/main/java/com/metaobjects/query/FilterOps.java @@ -119,9 +119,6 @@ private static Set ordered(String... ops) { // inet is identity-comparison-only (uuid band — no like, no ordering). m.put(UriField.SUBTYPE_URI, OPS_STRING); m.put(InetField.SUBTYPE_INET, OPS_UUID); - // field.duration — identity-comparison ops only for now: a text column (SQLite, MySQL) - // cannot order ISO-8601 strings. Adding the ordering ops later is additive. - m.put(DurationField.SUBTYPE_DURATION, OPS_UUID); m.put(IntegerField.SUBTYPE_INT, OPS_NUMERIC); m.put(LongField.SUBTYPE_LONG, OPS_NUMERIC); m.put(DoubleField.SUBTYPE_DOUBLE, OPS_NUMERIC); @@ -130,6 +127,8 @@ private static Set ordered(String... ops) { m.put(CurrencyField.SUBTYPE_CURRENCY, OPS_NUMERIC); m.put(DateField.SUBTYPE_DATE, OPS_NUMERIC); m.put(TimeField.SUBTYPE_TIME, OPS_NUMERIC); + // field.duration orders on every DB: a native interval on Postgres, a microsecond count elsewhere. + m.put(DurationField.SUBTYPE_DURATION, OPS_NUMERIC); m.put(TimestampField.SUBTYPE_TIMESTAMP, OPS_NUMERIC); m.put(BooleanField.SUBTYPE_BOOLEAN, OPS_BOOLEAN); OPS_BY_SUBTYPE = Collections.unmodifiableMap(m); diff --git a/server/java/metadata/src/test/java/com/metaobjects/field/DurationWireVectorsTest.java b/server/java/metadata/src/test/java/com/metaobjects/field/DurationWireVectorsTest.java index 6fdc0672aa..c5f66cf5eb 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/field/DurationWireVectorsTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/field/DurationWireVectorsTest.java @@ -108,11 +108,36 @@ public void formattingIgnoresTheDefaultLocalesDigits() { } @Test - public void aDurationValuePastTheSharedBoundIsNotWritten() { - assertEquals("PT256204778H", DurationWire.format(DurationWire.MAX)); + public void storedMicrosVectors() throws Exception { + for (JsonElement e : vectors().getAsJsonArray("storedMicros")) { + String in = e.getAsJsonObject().get("in").getAsString(); + long out = Long.parseLong(e.getAsJsonObject().get("out").getAsString()); + assertEquals("micros " + in, out, DurationWire.toMicros(DurationWire.parse(in))); + assertEquals("from micros " + out, in, DurationWire.format(DurationWire.fromMicros(out))); + } + // Sub-microsecond precision truncates toward zero on both sides of zero. + assertEquals(-1_000_000L, DurationWire.toMicros(Duration.ofSeconds(-1, -500))); + assertEquals(1_000_000L, DurationWire.toMicros(Duration.ofSeconds(1, 500))); + } + + @Test + public void javaDurationsOwnRangeIsTheOnlyLimitAndIsRefusedNeverWrapped() { + // Far past any other port's range: Java takes it. + assertEquals("PT2562047788015215H", DurationWire.canonicalize("PT2562047788015215H")); + // Past a long count of seconds: refused, never wrapped. + for (String tooLong : new String[]{"PT9223372036854775808S", "P106751991167301D", "PT99999999999999999999H"}) { + assertFalse(tooLong, DurationWire.isDuration(tooLong)); + try { + DurationWire.parse(tooLong); + fail("must refuse " + tooLong); + } catch (IllegalArgumentException expected) { + // refused + } + } + // A BIGINT column holds about 292,000 years of microseconds: past it, the write is refused. try { - DurationWire.format(DurationWire.MAX.plusNanos(1_000)); - fail("one microsecond past the bound must be refused"); + DurationWire.toMicros(Duration.ofSeconds(Long.MAX_VALUE / 1_000_000L + 1)); + fail("past a 64-bit microsecond count must be refused"); } catch (IllegalArgumentException expected) { // refused } diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java index 3855b5bb89..d42ee883a2 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java @@ -106,8 +106,8 @@ public static JdbcFieldCodec forField(MetaField f) { // type (a plain setString fails "operator does not exist: inet = varchar"), mirroring // the UuidCodec native-column pattern. register(InetField.class, new InetCodec()); - // field.duration ⇄ the canonical ISO-8601 string on a text column; the Postgres driver - // binds the interval spelling to its native interval column (see DurationCodec). + // field.duration ⇄ a microsecond count on an integer column; the Postgres driver binds the + // interval spelling to its native interval column (see DurationCodec). register(DurationField.class, new DurationCodec()); register(ObjectField.class, DEFAULT); // identity with the fallback codec } @@ -547,25 +547,41 @@ static final class InetCodec implements JdbcFieldCodec { } /** - * {@code field.duration} ⇄ a text column holding the canonical ISO-8601 duration - * ({@link DurationWire#format}), or — on Postgres — the native {@code interval} column. - * DurationField is backed by {@code DataTypes.STRING} (the canonical wire string); a - * {@link java.time.Duration} value is accepted too. + * {@code field.duration} ⇄ a 64-bit integer column holding the count of microseconds (SQLite, + * MySQL and any other engine without a native interval — Django's DurationField precedent), or + * — on Postgres — the native {@code interval} column. DurationField is backed by + * {@code DataTypes.STRING} (the canonical wire string); a {@link java.time.Duration} value is + * accepted too. * - *

    Read: the column's text is either the stored ISO string or the text a Postgres - * interval returns ({@code 1 day 02:00:00}); both become the canonical string, and an - * interval with a year or month part is refused ({@link DurationWire#fromStored}). Write: - * the canonical string, so a text column holds one spelling per span. Postgres refuses a - * signed ISO-8601 duration, so {@code PostgresDriver} binds {@link #postgresText} instead.

    + *

    Read: an integer is a microsecond count; text is what a Postgres interval returns + * ({@code 1 day 02:00:00}) or a stored ISO string; all become the canonical string, and an + * interval with a year or month part is refused ({@link DurationWire#fromStored}). Write: the + * microsecond count (sub-microsecond truncated toward zero; past a 64-bit count is refused), so + * the column orders and compares as a number. Postgres refuses a signed ISO-8601 duration, so + * {@code PostgresDriver} binds {@link #postgresText} instead.

    */ public static final class DurationCodec implements JdbcFieldCodec { + @Override public int sqlType() { return Types.BIGINT; } + @Override public int sqlLength() { return 0; } + @Override public void readInto(Object o, MetaField f, ResultSet rs, int j) throws SQLException { - String v = rs.getString(j); - f.setString(o, (v == null || rs.wasNull()) ? null : stored(f, v)); + Object raw = rs.getObject(j); + if (raw == null || rs.wasNull()) { f.setString(o, null); return; } + try { + f.setString(o, raw instanceof Number n + ? DurationWire.format(DurationWire.fromMicros(n.longValue())) + : DurationWire.canonicalizeStored(rs.getString(j))); + } catch (IllegalArgumentException e) { + throw new SQLException("field.duration '" + f.getName() + "' cannot be read: " + e.getMessage(), e); + } } @Override public void write(PreparedStatement s, MetaField f, int j, Object v) throws SQLException { - if (v == null) s.setNull(j, Types.VARCHAR); - else s.setString(j, DurationWire.format(toDuration(f, v))); + if (v == null) { s.setNull(j, Types.BIGINT); return; } + try { + s.setLong(j, DurationWire.toMicros(toDuration(f, v))); + } catch (IllegalArgumentException e) { + throw new SQLException("field.duration '" + f.getName() + "' cannot be written: " + e.getMessage(), e); + } } /** The Postgres interval input spelling of a duration value ({@code [-]HH:MM:SS[.f]}). */ @@ -574,21 +590,13 @@ public static String postgresText(MetaField f, Object v) throws SQLException { } static java.time.Duration toDuration(MetaField f, Object v) throws SQLException { + if (v instanceof java.time.Duration d) return d; try { - if (v instanceof java.time.Duration d) return DurationWire.checkBound(d, d.toString()); return DurationWire.parse(v.toString()); } catch (IllegalArgumentException e) { throw new SQLException("field.duration '" + f.getName() + "' cannot be written: " + e.getMessage(), e); } } - - private static String stored(MetaField f, String v) throws SQLException { - try { - return DurationWire.canonicalizeStored(v); - } catch (IllegalArgumentException e) { - throw new SQLException("field.duration '" + f.getName() + "' cannot be read: " + e.getMessage(), e); - } - } } /** diff --git a/server/java/omdb/src/test/java/com/metaobjects/manager/db/codec/JdbcCodecRoundTripTest.java b/server/java/omdb/src/test/java/com/metaobjects/manager/db/codec/JdbcCodecRoundTripTest.java index 32b3006799..1446b261a8 100644 --- a/server/java/omdb/src/test/java/com/metaobjects/manager/db/codec/JdbcCodecRoundTripTest.java +++ b/server/java/omdb/src/test/java/com/metaobjects/manager/db/codec/JdbcCodecRoundTripTest.java @@ -391,12 +391,12 @@ public void uuidCodecReadsBackLowercaseCanonical() throws Exception { } /** - * {@code DurationCodec} on a text column: a written duration is stored canonically (one - * spelling per span, so an equality filter matches), and the text a Postgres interval - * returns reads back as the canonical wire string. + * {@code DurationCodec} on an engine without a native interval: a duration is stored as a + * 64-bit count of microseconds (so a range filter and a sort order it as a number), and reads + * back as the canonical wire string. The text a Postgres interval returns reads canonically too. */ @Test - public void durationCodecStoresAndReadsTheCanonicalForm() throws Exception { + public void durationCodecStoresAMicrosecondCountAndReadsTheCanonicalForm() throws Exception { final java.util.Map store = new java.util.HashMap<>(); com.metaobjects.field.DurationField durationField = new com.metaobjects.field.DurationField("holdFor") { @Override public void setString(Object obj, String value) { store.put("v", value); } @@ -405,29 +405,42 @@ public void durationCodecStoresAndReadsTheCanonicalForm() throws Exception { try (Connection conn = getConnection()) { try (Statement st = conn.createStatement()) { - st.execute("CREATE TABLE codec_duration_probe (d VARCHAR(64))"); + st.execute("CREATE TABLE codec_duration_probe (d BIGINT, t VARCHAR(64))"); } try (PreparedStatement ps = conn.prepareStatement("INSERT INTO codec_duration_probe (d) VALUES (?)")) { codec.write(ps, durationField, 1, "P1DT0.5S"); ps.executeUpdate(); codec.write(ps, durationField, 1, java.time.Duration.ofSeconds(-90)); ps.executeUpdate(); + codec.write(ps, durationField, 1, "PT1H30M"); + ps.executeUpdate(); } - try (Statement st = conn.createStatement()) { - st.execute("INSERT INTO codec_duration_probe (d) VALUES ('-1 days +02:00:00')"); - } + // A range filter binds through the same codec and compares numbers: > PT1H. java.util.List stored = new java.util.ArrayList<>(); java.util.List read = new java.util.ArrayList<>(); - try (Statement st = conn.createStatement(); - ResultSet rs = st.executeQuery("SELECT d FROM codec_duration_probe")) { - while (rs.next()) { - stored.add(rs.getString(1)); - codec.readInto(new Object(), durationField, rs, 1); - read.add((String) store.get("v")); + try (PreparedStatement ps = conn.prepareStatement( + "SELECT d FROM codec_duration_probe WHERE d > ? ORDER BY d")) { + codec.write(ps, durationField, 1, "PT1H"); + try (ResultSet rs = ps.executeQuery()) { + while (rs.next()) { + stored.add(rs.getString(1)); + codec.readInto(new Object(), durationField, rs, 1); + read.add((String) store.get("v")); + } } } - assertEquals(java.util.List.of("PT24H0.5S", "-PT1M30S", "-1 days +02:00:00"), stored); - assertEquals(java.util.List.of("PT24H0.5S", "-PT1M30S", "-PT22H"), read); + assertEquals(java.util.List.of("5400000000", "86400500000"), stored); + assertEquals(java.util.List.of("PT1H30M", "PT24H0.5S"), read); + // Postgres interval text in a text column reads canonically. + try (Statement st = conn.createStatement()) { + st.execute("INSERT INTO codec_duration_probe (t) VALUES ('-1 days +02:00:00')"); + } + try (Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery("SELECT t FROM codec_duration_probe WHERE t IS NOT NULL")) { + assertTrue(rs.next()); + codec.readInto(new Object(), durationField, rs, 1); + assertEquals("-PT22H", store.get("v")); + } try (PreparedStatement ps = conn.prepareStatement("INSERT INTO codec_duration_probe (d) VALUES (?)")) { codec.write(ps, durationField, 1, "P1M"); fail("a calendar span is not a duration"); diff --git a/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py b/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py index dbc6a8e04e..8230ff0790 100644 --- a/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py +++ b/server/python/src/metaobjects/codegen/generators/filter_allowlist_generator.py @@ -90,13 +90,14 @@ def ops_for_subtype_ordered(sub_type: str | None) -> tuple[str, ...]: return _OPS_STRING # ADR-0036/0037 Wave 3 — field.uri is string-like (substring searchable); # field.inet is uuid-like (identity value, no substring search, no ordering). - # field.duration takes the inet band (ordering deferred: text dialects cannot - # order ISO-8601 strings). if sub_type == fc.FIELD_SUBTYPE_URI: return _OPS_STRING - if sub_type in (fc.FIELD_SUBTYPE_UUID, fc.FIELD_SUBTYPE_INET, fc.FIELD_SUBTYPE_DURATION): + if sub_type in (fc.FIELD_SUBTYPE_UUID, fc.FIELD_SUBTYPE_INET): return _OPS_UUID + # field.duration is an orderable span (a Postgres interval; a microsecond integer on + # SQLite, D1 and MySQL): the numeric band. if sub_type in ( + fc.FIELD_SUBTYPE_DURATION, fc.FIELD_SUBTYPE_INT, fc.FIELD_SUBTYPE_LONG, fc.FIELD_SUBTYPE_FLOAT, diff --git a/server/python/src/metaobjects/codegen/runtime/duration_wire.py b/server/python/src/metaobjects/codegen/runtime/duration_wire.py index 4ef59393c1..f39c0aa867 100644 --- a/server/python/src/metaobjects/codegen/runtime/duration_wire.py +++ b/server/python/src/metaobjects/codegen/runtime/duration_wire.py @@ -14,9 +14,11 @@ optional days (``D`` is exactly 24 hours), then an optional ``T`` with hours, minutes and seconds in that order; at least one component, up to nine fractional-second digits. Years, months and weeks are refused: a calendar span has no fixed length. -* **Bounded** -- the magnitude is at most :data:`MAX_DURATION_HOURS` hours (the largest whole hour a - .NET ``TimeSpan`` holds, so every port reads what any port wrote). One microsecond past it is - refused, on parse and on read. +* **Range** -- this port's own limit only: a ``timedelta`` spans at most 999999999 days either + way. A duration past it is refused, never wrapped. +* **Stored micros** -- :func:`to_stored_micros` / :func:`from_stored_micros`: on SQLite, D1 and + MySQL a duration is a 64-bit integer count of microseconds (the column's limit: past it is + refused). * **Postgres** -- :func:`parse_postgres_interval` reads the default-style (``IntervalStyle = postgres``) text of an ``interval``; :func:`format_postgres_interval` writes the ``[-]HH:MM:SS[.f]`` spelling Postgres reads as interval input (it refuses a signed ISO-8601 @@ -52,18 +54,18 @@ _MICROS_PER_HOUR = 60 * _MICROS_PER_MINUTE _MICROS_PER_DAY = 24 * _MICROS_PER_HOUR -#: The largest magnitude a duration may have, in whole hours (fixtures/duration-wire). -MAX_DURATION_HOURS = 256_204_778 -_MAX_MICROS = MAX_DURATION_HOURS * _MICROS_PER_HOUR +#: The range of a 64-bit integer column (SQLite INTEGER, MySQL BIGINT) holding microseconds. +_INT64_MIN = -(2**63) +_INT64_MAX = 2**63 - 1 #: The message a value that is not a duration is refused with (the run-time validator's text). NOT_A_DURATION = "must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)" def is_duration_literal(text: str) -> bool: - """True when *text* is an accepted ISO-8601 duration within the bound.""" + """True when *text* is an accepted ISO-8601 duration a ``timedelta`` can hold.""" micros = _micros_of_literal(text) - return micros is not None and abs(micros) <= _MAX_MICROS + return micros is not None and _in_range(micros) def _fraction_micros(digits: str | None) -> int: @@ -95,23 +97,41 @@ def micros_of(value: _dt.timedelta) -> int: return (value.days * 86_400 + value.seconds) * _MICROS_PER_SECOND + value.microseconds -def _out_of_range(shown: str) -> ValueError: - return ValueError(f"the duration {shown} is out of range: at most {MAX_DURATION_HOURS} hours either way") +_MIN_MICROS = micros_of(_dt.timedelta.min) +_MAX_MICROS = micros_of(_dt.timedelta.max) -def _checked(value: _dt.timedelta) -> _dt.timedelta: - """*value*, or a ``ValueError`` when its magnitude is past the bound.""" - if abs(micros_of(value)) > _MAX_MICROS: - raise _out_of_range(format_duration(value)) - return value +def _in_range(micros: int) -> bool: + return _MIN_MICROS <= micros <= _MAX_MICROS def _from_micros(micros: int) -> _dt.timedelta: - if abs(micros) > _MAX_MICROS: - raise _out_of_range(_format_micros(micros)) + """A ``timedelta`` of *micros* microseconds; past a ``timedelta``'s range is a ``ValueError`` + (refused, never wrapped).""" + if not _in_range(micros): + raise ValueError( + f"the duration {_format_micros(micros)} is out of range: a Python timedelta spans at most " + "999999999 days either way" + ) return _dt.timedelta(microseconds=micros) +def to_stored_micros(value: _dt.timedelta) -> int: + """*value* as the 64-bit microsecond count a SQLite / D1 / MySQL column stores. Past the + 64-bit range (the column's limit) is a ``ValueError``.""" + micros = micros_of(value) + if not _INT64_MIN <= micros <= _INT64_MAX: + raise ValueError( + f"the duration {_format_micros(micros)} is out of range for a 64-bit microsecond column" + ) + return micros + + +def from_stored_micros(micros: int) -> _dt.timedelta: + """The ``timedelta`` a stored microsecond count is.""" + return _from_micros(micros) + + def parse_duration(text: str) -> _dt.timedelta: """An accepted ISO-8601 duration as a ``timedelta``. Anything else is a ``ValueError``.""" micros = _micros_of_literal(text) @@ -154,9 +174,9 @@ def _format_micros(micros: int) -> str: def canonical_duration(text: str) -> str | None: """The canonical form of an accepted ISO-8601 duration, or ``None`` when *text* is not one - (a duration past the bound included).""" + (a duration past a ``timedelta``'s range included).""" micros = _micros_of_literal(text) - return None if micros is None or abs(micros) > _MAX_MICROS else _format_micros(micros) + return None if micros is None or not _in_range(micros) else _format_micros(micros) def format_postgres_interval(value: _dt.timedelta) -> str: @@ -193,11 +213,14 @@ def parse_postgres_interval(text: str) -> _dt.timedelta: def duration_from_driver(value: Any) -> _dt.timedelta: """What a driver hands back for a duration column, as a ``timedelta``: a ``timedelta`` - (pg8000 for an interval), the stored canonical string (a SQLite / MySQL text column), the - default-style text of an interval, or a pg8000 ``PGInterval`` (an interval pg8000 could not - make a ``timedelta`` of because it has a month part, which is refused).""" + (pg8000 for an interval), the microsecond count a SQLite / MySQL integer column holds, a + canonical ISO string (a duration inside a JSON value object), the default-style text of an + interval, or a pg8000 ``PGInterval`` (an interval pg8000 could not make a ``timedelta`` of + because it has a month part, which is refused).""" if isinstance(value, _dt.timedelta): - return _checked(value) + return value + if isinstance(value, int) and not isinstance(value, bool): + return from_stored_micros(value) if isinstance(value, str): micros = _micros_of_literal(value) return _from_micros(micros) if micros is not None else parse_postgres_interval(value) @@ -209,7 +232,7 @@ def duration_from_driver(value: Any) -> _dt.timedelta: raise _not_fixed_length(str(value)) result = to_timedelta() if isinstance(result, _dt.timedelta): - return _checked(result) + return result raise ValueError(f"not a field.duration value: {value!r}") @@ -219,7 +242,7 @@ def parse_duration_input(value: Any) -> _dt.timedelta: is every string outside the accepted form, including the ones Pydantic's own ``timedelta`` parser would take (``1:30:00``, ``P1Y``).""" if isinstance(value, _dt.timedelta): - return _checked(value) + return value if isinstance(value, str): return parse_duration(value) raise ValueError(f"{value!r} is not an ISO-8601 duration (such as PT1H30M; no years, months or weeks)") diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 6fc58a7048..b375e2fa94 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -1103,12 +1103,15 @@ def ops_for_subtype(field_subtype: str) -> frozenset[str]: return _OPS_STRING # ADR-0036/0037 Wave 3 — field.uri is string-like (substring searchable): # eq/ne/in/like/isNull. field.inet is uuid-like (an identity value, no - # substring search, no ordering): eq/ne/in/isNull. field.duration takes the - # same band: ordering is deferred, since a text dialect cannot order ISO strings. + # substring search, no ordering): eq/ne/in/isNull. if field_subtype == FIELD_SUBTYPE_URI: return _OPS_STRING - if field_subtype in ("uuid", FIELD_SUBTYPE_INET, FIELD_SUBTYPE_DURATION): + if field_subtype in ("uuid", FIELD_SUBTYPE_INET): return _OPS_UUID + # field.duration is an orderable span: the numeric/temporal band. Every engine orders it + # (a Postgres interval; a microsecond integer on SQLite, D1 and MySQL). + if field_subtype == FIELD_SUBTYPE_DURATION: + return _OPS_NUMERIC_TEMPORAL if field_subtype == "boolean": return _OPS_BOOLEAN if field_subtype in _NUMERIC_TEMPORAL_SUBTYPES: diff --git a/server/python/src/metaobjects/runtime/dialect.py b/server/python/src/metaobjects/runtime/dialect.py index 5ee1740514..a7ad385479 100644 --- a/server/python/src/metaobjects/runtime/dialect.py +++ b/server/python/src/metaobjects/runtime/dialect.py @@ -28,7 +28,7 @@ from typing import Any from ..codegen.runtime.decimal_wire import decimal_from_double15 -from ..codegen.runtime.duration_wire import format_duration +from ..codegen.runtime.duration_wire import to_stored_micros from ..meta.core.field import field_constants as fc from ..meta.core.field.meta_field import MetaField from ..meta.persistence.db import db_constants as dbc @@ -43,8 +43,9 @@ class DurationParam(_dt.timedelta): """A ``field.duration``'s bound value: the ``timedelta`` the write codec makes of it. - The SQLite and MySQL dialects bind it as its canonical ISO-8601 string (a TEXT column), - and they key that on THIS type, not on ``timedelta``: only the duration write codec makes + The SQLite and MySQL dialects bind it as its 64-bit microsecond count (an INTEGER / BIGINT + column, so it orders and compares as a number), and they key that on THIS type, not on + ``timedelta``: only the duration write codec makes one, so a ``timedelta`` handed in for any other column binds exactly as it did before. pg8000 binds it as the ``timedelta`` it is (an interval).""" @@ -278,9 +279,8 @@ def encode_param(self, value: Any) -> Any: if isinstance(value, _dt.time): return value.isoformat() if isinstance(value, DurationParam): - # field.duration: a TEXT column holding the canonical ISO-8601 string, so equal - # spans are equal strings. - return format_duration(value) + # field.duration: an INTEGER column holding the microsecond count. + return to_stored_micros(value) return value def decode_value(self, field: MetaField, value: Any) -> Any: @@ -319,9 +319,9 @@ def encode_param(self, value: Any) -> Any: if isinstance(value, _dt.time): return value.isoformat() if isinstance(value, DurationParam): - # field.duration: a VARCHAR column holding the canonical ISO-8601 string. PyMySQL - # would otherwise bind a timedelta as a TIME literal. - return format_duration(value) + # field.duration: a BIGINT column holding the microsecond count. PyMySQL would + # otherwise bind a timedelta as a TIME literal. + return to_stored_micros(value) return value def decode_value(self, field: MetaField, value: Any) -> Any: diff --git a/server/python/src/metaobjects/runtime/object_manager.py b/server/python/src/metaobjects/runtime/object_manager.py index 7050e8cbca..4c2de5d1a8 100644 --- a/server/python/src/metaobjects/runtime/object_manager.py +++ b/server/python/src/metaobjects/runtime/object_manager.py @@ -1048,7 +1048,8 @@ def _coerce_write_value(field: MetaField, value: Any) -> Any: # field.duration: an accepted ISO-8601 duration (or a timedelta already in process) → # datetime.timedelta, which pg8000 binds as an interval; the SQLite and MySQL dialects - # bind its canonical string (Dialect.encode_param). Anything else — a calendar span, a + # bind its microsecond count (Dialect.encode_param), so a filter operand compares and + # orders as a number there. Anything else — a calendar span, a # clock string, a number — is refused here, not by the database. if sub == fc.FIELD_SUBTYPE_DURATION: if _field_is_array(field) and isinstance(value, list): @@ -1222,7 +1223,7 @@ def _decode_read_value(field: MetaField, value: Any) -> Any: return None if field.sub_type == fc.FIELD_SUBTYPE_DURATION: # A duration reads back as a datetime.timedelta on every engine: pg8000 hands one back - # for an interval, a text column holds the canonical string. An interval with a month + # for an interval, a SQLite / MySQL integer column holds the microsecond count. An interval with a month # part (pg8000 returns a PGInterval for it) is not a fixed length: refused. if isinstance(value, list): return [None if v is None else duration_from_driver(v) for v in value] diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index 57bb390cbe..29176405ef 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -190,7 +190,7 @@ "subType": "duration", "dataType": "string", "extendsBase": true, - "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit." } ] diff --git a/server/python/tests/codegen/test_duration_codegen.py b/server/python/tests/codegen/test_duration_codegen.py index d94bffa5aa..772f9c904a 100644 --- a/server/python/tests/codegen/test_duration_codegen.py +++ b/server/python/tests/codegen/test_duration_codegen.py @@ -4,7 +4,7 @@ parser would also take a number, clock text and a calendar span) and writes the canonical form in JSON (Pydantic's own is ``PT5400S`` for 90 minutes). Its codec is the generated package's ``_duration_wire.py``, a copy of the production helper. A router writes a duration in a response -through the same formatter, and filters it in the inet band (eq / ne / in / isNull). +through the same formatter, filters it in the ordered band and sorts by it. """ from __future__ import annotations @@ -147,9 +147,14 @@ def test_the_model_refuses_what_pydantic_timedelta_would_take(generated: dict[st generated["hold"].HoldCreate(holdFor="PT1H", steps=[value]) -def test_duration_takes_the_inet_filter_band() -> None: - assert ops_for_subtype("duration") == frozenset({"eq", "ne", "in", "isNull"}) - assert set(ops_for_field_ordered(_field("holdFor"))) == {"eq", "ne", "in", "isNull"} +def test_duration_takes_the_ordered_filter_band() -> None: + band = ("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull") + assert ops_for_subtype("duration") == frozenset(band) + assert ops_for_field_ordered(_field("holdFor")) == band + + +def test_a_duration_is_a_sort_key(generated: dict[str, Any]) -> None: + assert {"holdFor", "grace"} <= generated["router"]._SORT_ALLOWLIST def test_a_router_writes_a_duration_through_the_codec(generated: dict[str, Any]) -> None: diff --git a/server/python/tests/integration/test_duration_postgres.py b/server/python/tests/integration/test_duration_postgres.py new file mode 100644 index 0000000000..b2d76ddf92 --- /dev/null +++ b/server/python/tests/integration/test_duration_postgres.py @@ -0,0 +1,69 @@ +"""field.duration on a live Postgres through the ObjectManager: a native ``interval`` column, +bound and read as a ``timedelta`` by pg8000, orders and range-filters as a span (sort plus +gt / gte / lt / lte), and a negative or more-than-a-day value round-trips canonically.""" +from __future__ import annotations + +import datetime as dt +import json +from contextlib import closing +from typing import Any + +import pg8000.dbapi as pg8000 + +from metaobjects import load_string +from metaobjects.codegen.runtime.duration_wire import format_duration +from metaobjects.naming import NamingRules +from metaobjects.runtime import ObjectManager, PostgresDriver + +from .postgres_container import PostgresContainer + +_META = { + "metadata.root": { + "package": "acme::ops", + "children": [ + { + "object.entity": { + "name": "Hold", + "children": [ + {"source.rdb": {"@table": "holds"}}, + {"field.long": {"name": "id"}}, + {"field.duration": {"name": "holdFor"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"], "@generation": "increment"}}, + ], + } + } + ], + } +} + + +def _spans(rows: list[dict[str, Any]]) -> list[str | None]: + return [None if r["holdFor"] is None else format_duration(r["holdFor"]) for r in rows] + + +def test_postgres_orders_and_range_filters_a_duration() -> None: + root: Any = load_string(json.dumps(_META)).root + root.naming = NamingRules(columns="literal") + with PostgresContainer() as pg: + info = pg.info() + with closing(pg8000.connect( + host=info.host, port=info.port, user=info.user, password=info.password, database=info.database, + )) as conn: + cur = conn.cursor() + cur.execute('CREATE TABLE "holds" ("id" BIGSERIAL PRIMARY KEY, "holdFor" INTERVAL)') + conn.commit() + om = ObjectManager(root, PostgresDriver(conn)) + for d in ["PT2H", "-PT1M30S", "PT90M", "PT45S", "P1D", "PT0S", "PT256204779H"]: + om.create("Hold", {"holdFor": d}) + om.create("Hold", {}) + + asc = om.find_many("Hold", sort=[("holdFor", "asc")]) + assert _spans(asc) == [ + "-PT1M30S", "PT0S", "PT45S", "PT1H30M", "PT2H", "PT24H", "PT256204779H", None, + ] + ranged = om.find_many("Hold", {"holdFor": {"gt": "PT0S", "lte": "PT120M"}}, sort=[("holdFor", "desc")]) + assert _spans(ranged) == ["PT2H", "PT1H30M", "PT45S"] + assert _spans(om.find_many("Hold", {"holdFor": {"lt": "PT0S"}})) == ["-PT1M30S"] + assert om.count("Hold", {"holdFor": {"gte": "P1D"}}) == 2 + (neg,) = om.find_many("Hold", {"holdFor": {"eq": "-PT90S"}}) + assert neg["holdFor"] == dt.timedelta(seconds=-90) diff --git a/server/python/tests/runtime/test_duration_wire.py b/server/python/tests/runtime/test_duration_wire.py index 87c6dfe77d..3cacd643c7 100644 --- a/server/python/tests/runtime/test_duration_wire.py +++ b/server/python/tests/runtime/test_duration_wire.py @@ -13,10 +13,13 @@ duration_from_driver, format_duration, format_postgres_interval, + from_stored_micros, is_duration_literal, + micros_of, parse_duration, parse_duration_input, parse_postgres_interval, + to_stored_micros, ) _VECTORS = json.loads( @@ -92,13 +95,40 @@ def test_an_out_of_range_duration_is_a_value_error() -> None: parse_duration("PT99999999999999999999H") -def test_a_timedelta_past_the_bound_is_refused_on_input_and_on_read() -> None: - edge = dt.timedelta(hours=256_204_778) - assert duration_from_driver(edge) == edge - assert parse_duration_input(-edge) == -edge - over = edge + dt.timedelta(microseconds=1) - for value in (over, -over): - with pytest.raises(ValueError, match="out of range"): - duration_from_driver(value) +@pytest.mark.parametrize("v", _VECTORS["storedMicros"], ids=lambda v: v["in"]) +def test_stored_micros(v: dict[str, str]) -> None: + td = parse_duration(v["in"]) + assert to_stored_micros(td) == int(v["out"]) + assert format_duration(from_stored_micros(int(v["out"]))) == v["in"] + assert format_duration(duration_from_driver(int(v["out"]))) == v["in"] + + +# ── this port's own limits (not shared vectors) ────────────────────────────── + + +def test_the_timedelta_range_is_the_only_limit_and_past_it_is_refused() -> None: + # Far past what another port's native type holds: Python takes it. + assert format_duration(parse_duration("PT256204779H")) == "PT256204779H" + edge = f"P{999_999_999}DT23H59M59.999999S" + assert parse_duration(edge) == dt.timedelta.max + assert parse_duration(f"-P{999_999_999}D") == dt.timedelta.min + for text in (f"P{1_000_000_000}D", f"P{999_999_999}DT24H", f"-P{999_999_999}DT0.000001S"): + assert not is_duration_literal(text) + assert canonical_duration(text) is None with pytest.raises(ValueError, match="out of range"): - parse_duration_input(value) + parse_duration(text) + with pytest.raises(ValueError, match="out of range"): + from_stored_micros(micros_of(dt.timedelta.max) + 1) + + +def test_a_stored_micro_count_past_64_bits_is_refused() -> None: + assert to_stored_micros(dt.timedelta(microseconds=2**63 - 1)) == 2**63 - 1 + assert to_stored_micros(dt.timedelta(microseconds=-(2**63))) == -(2**63) + for td in (dt.timedelta(microseconds=2**63), dt.timedelta(microseconds=-(2**63) - 1), dt.timedelta.max): + with pytest.raises(ValueError, match="64-bit"): + to_stored_micros(td) + + +def test_a_bool_is_not_a_stored_micro_count() -> None: + with pytest.raises(ValueError): + duration_from_driver(True) diff --git a/server/python/tests/runtime/test_object_manager_duration.py b/server/python/tests/runtime/test_object_manager_duration.py index f0695cb0ab..6b08834ef9 100644 --- a/server/python/tests/runtime/test_object_manager_duration.py +++ b/server/python/tests/runtime/test_object_manager_duration.py @@ -1,7 +1,8 @@ """field.duration through the ObjectManager: the write codec (an accepted ISO-8601 string becomes a ``timedelta``; anything else is refused), the per-engine binding (pg8000 binds the ``timedelta`` -as an interval, SQLite and MySQL a TEXT column holding the canonical string) and the read codec -(every engine reads back a ``timedelta``; an interval with a month part is refused). +as an interval, SQLite and MySQL an integer column holding the microsecond count, so it orders) +and the read codec (every engine reads back a ``timedelta``; an interval with a month part is +refused). A duration inside a jsonb value object stays the canonical ISO string. The live Postgres lane is ``tests/integration/test_query_scenarios.py`` (``roundtrip-all-types``, ``update-delete-all-types``). @@ -54,7 +55,7 @@ def _field(name: str) -> Any: def _sqlite_om() -> tuple[ObjectManager, sqlite3.Connection]: conn = sqlite3.connect(":memory:") - conn.execute('CREATE TABLE "holds" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "holdFor" TEXT, "steps" TEXT)') + conn.execute('CREATE TABLE "holds" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "holdFor" INTEGER, "steps" TEXT)') return ObjectManager(_root(), SqliteDriver(conn)), conn @@ -78,14 +79,17 @@ def test_postgres_binds_the_native_timedelta() -> None: @pytest.mark.parametrize("dialect", [SQLITE, MYSQL], ids=lambda d: d.name) -def test_a_text_engine_binds_the_canonical_string(dialect: Any) -> None: +def test_an_integer_engine_binds_the_microsecond_count(dialect: Any) -> None: f = _field("holdFor") - assert dialect.encode_param(_coerce_write_value(f, "P1DT0.5S")) == "PT24H0.5S" - assert dialect.encode_param(_coerce_write_value(f, dt.timedelta(seconds=-90))) == "-PT1M30S" + assert dialect.encode_param(_coerce_write_value(f, "P1DT0.5S")) == 86_400_500_000 + assert dialect.encode_param(_coerce_write_value(f, dt.timedelta(seconds=-90))) == -90_000_000 + # Past the 64-bit column is refused (the column's limit), never wrapped. + with pytest.raises(ValueError, match="64-bit"): + dialect.encode_param(_coerce_write_value(f, dt.timedelta.max)) @pytest.mark.parametrize("dialect", [SQLITE, MYSQL], ids=lambda d: d.name) -def test_the_text_binding_is_by_field_not_by_value(dialect: Any) -> None: +def test_the_integer_binding_is_by_field_not_by_value(dialect: Any) -> None: # A timedelta the duration write codec did not make (a caller's value for some other # column, an operand on an undeclared one) binds exactly as it did before. td = dt.timedelta(minutes=5) @@ -93,23 +97,20 @@ def test_the_text_binding_is_by_field_not_by_value(dialect: Any) -> None: assert isinstance(_coerce_write_value(_field("holdFor"), "PT5M"), DurationParam) -def test_a_duration_past_the_shared_bound_is_refused_on_write_and_read() -> None: +def test_only_the_timedelta_range_limits_a_duration() -> None: f = _field("holdFor") - assert _coerce_write_value(f, "PT256204778H") == dt.timedelta(hours=256_204_778) + assert _coerce_write_value(f, "PT256204779H") == dt.timedelta(hours=256_204_779) + assert _decode_read_value(f, "256204779:00:00") == dt.timedelta(hours=256_204_779) + with pytest.raises(ValueError, match="cannot be written.*out of range"): + _coerce_write_value(f, "P1000000000D") with pytest.raises(ValueError, match="out of range"): - _coerce_write_value(f, dt.timedelta(hours=256_204_778, microseconds=1)) - with pytest.raises(ValueError, match="cannot be written"): - _coerce_write_value(f, "PT256204779H") - with pytest.raises(ValueError, match="out of range"): - _decode_read_value(f, dt.timedelta(hours=256_204_779)) - with pytest.raises(ValueError, match="out of range"): - _decode_read_value(f, "256204779:00:00") + _decode_read_value(f, 10**20) def test_every_engine_reads_back_a_timedelta() -> None: f = _field("holdFor") assert _decode_read_value(f, dt.timedelta(hours=26)) == dt.timedelta(hours=26) # pg8000 - assert _decode_read_value(f, "-PT1M30S") == dt.timedelta(seconds=-90) # a TEXT column + assert _decode_read_value(f, -90_000_000) == dt.timedelta(seconds=-90) # an integer column assert _decode_read_value(f, "1 day 02:00:00") == dt.timedelta(hours=26) # interval text assert _decode_read_value(_field("steps"), [dt.timedelta(minutes=1), None]) == [dt.timedelta(minutes=1), None] @@ -122,17 +123,43 @@ def test_an_interval_with_a_month_part_is_refused_on_read() -> None: _decode_read_value(_field("holdFor"), "1 mon 00:00:01") -def test_sqlite_round_trip_stores_the_canonical_string() -> None: +def test_sqlite_round_trip_stores_the_microsecond_count() -> None: om, conn = _sqlite_om() created = om.create("Hold", {"holdFor": "P1DT0.5S"}) assert created["holdFor"] == dt.timedelta(days=1, milliseconds=500) - assert conn.execute('SELECT "holdFor" FROM "holds"').fetchone() == ("PT24H0.5S",) + assert conn.execute('SELECT "holdFor" FROM "holds"').fetchone() == (86_400_500_000,) (row,) = om.find_many("Hold", {"holdFor": {"eq": "PT24H0.5S"}}) assert row["holdFor"] == dt.timedelta(hours=24, milliseconds=500) - # Equal spans are equal strings, so a filter in another accepted spelling still matches. + # Equal spans are equal integers, so a filter in another accepted spelling still matches. assert len(om.find_many("Hold", {"holdFor": {"in": ["P1DT0.5S", "PT1H"]}})) == 1 +def test_sqlite_orders_and_range_filters_a_duration() -> None: + om, _ = _sqlite_om() + # Inserted out of order, and spelled so that text order would differ from span order. + for d in ["PT2H", "-PT1M30S", "PT90M", "PT45S", "P1D", "PT0S"]: + om.create("Hold", {"holdFor": d}) + om.create("Hold", {}) + + def spans(rows: list[dict[str, Any]]) -> list[str | None]: + from metaobjects.codegen.runtime.duration_wire import format_duration + + return [None if r["holdFor"] is None else format_duration(r["holdFor"]) for r in rows] + + asc = om.find_many("Hold", sort=[("holdFor", "asc")]) + assert spans(asc) == ["-PT1M30S", "PT0S", "PT45S", "PT1H30M", "PT2H", "PT24H", None] + desc = om.find_many("Hold", sort=[("holdFor", "desc")]) + assert spans(desc) == [None, "PT24H", "PT2H", "PT1H30M", "PT45S", "PT0S", "-PT1M30S"] + + ranged = om.find_many( + "Hold", {"holdFor": {"gt": "PT0S", "lte": "PT120M"}}, sort=[("holdFor", "asc")] + ) + assert spans(ranged) == ["PT45S", "PT1H30M", "PT2H"] + assert spans(om.find_many("Hold", {"holdFor": {"gte": "PT2H"}}, sort=[("holdFor", "asc")])) == ["PT2H", "PT24H"] + assert spans(om.find_many("Hold", {"holdFor": {"lt": "PT0S"}})) == ["-PT1M30S"] + assert om.count("Hold", {"holdFor": {"ne": "PT90M"}}) == 5 + + # ── a duration inside a jsonb value object ─────────────────────────────────── _VO_META = { @@ -222,4 +249,4 @@ def test_a_value_object_member_that_is_not_a_duration_is_refused_on_write() -> N with pytest.raises(ValueError, match="field.duration 'timeout' cannot be written"): om.create("Plan", {"settings": {"timeout": "P1M"}}) with pytest.raises(ValueError, match="field.duration 'wait' cannot be written"): - om.create("Plan", {"windows": [{"inner": {"wait": "PT256204779H"}}]}) + om.create("Plan", {"windows": [{"inner": {"wait": "P1000000000D"}}]}) diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index b6315fde43..f0a16e07f0 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -247,10 +247,10 @@ export interface EnumIntCustomType { /** * A `field.duration` column: a generated Drizzle `customType` (the module-local const - * {@link DURATION_COLUMN_FN}) whose `toDriver` binds the dialect's spelling — the Postgres - * interval text `[-]HH:MM:SS[.f]` (Postgres refuses a signed ISO-8601 duration), the canonical - * ISO-8601 string on SQLite / MySQL — and whose `fromDriver` reads any of them back as the - * canonical ISO-8601 form. Drizzle's own pg-core `interval()` reads Postgres's text spelling + * {@link DURATION_COLUMN_FN}) whose `toDriver` binds what the column holds — the Postgres + * interval text `[-]HH:MM:SS[.f]` (Postgres refuses a signed ISO-8601 duration), a 64-bit integer + * count of microseconds on SQLite / D1 / MySQL (it orders and compares as the span) — and whose + * `fromDriver` reads either back as the canonical ISO-8601 form. Drizzle's own pg-core `interval()` reads Postgres's text spelling * (`01:30:00`), which is not the wire form. One declaration per module serves every duration * column in it (templates/duration-wire-helper.ts). */ @@ -479,8 +479,8 @@ export const PG_IDENTITY_CAPABLE_FNS: ReadonlySet = new Set([ * indexed column (primary/secondary/reference identity, `index.lookup`, `@unique`) or one * with a `@default` (a `TEXT` column cannot take a literal default). Those are * `VARCHAR(255)`. - * - `field.uuid` is `VARCHAR(36)`, `field.inet` `VARCHAR(45)` and `field.duration` `VARCHAR(64)` - * (through the local duration codec): MySQL has none of those types. + * - `field.uuid` is `VARCHAR(36)` and `field.inet` `VARCHAR(45)`: MySQL has neither type. + * `field.duration` is a `BIGINT` count of microseconds, through the local duration codec. * - A string enum is `VARCHAR(n)`, `n` the longest member, typed as the member union. * - `field.timestamp` is `DATETIME(3)` in Drizzle's "date" mode (see normalizeTimestampMode). * - Arrays, `field.object`, `field.map` and `@dbColumnType: jsonb` are `JSON`. @@ -529,8 +529,8 @@ function mapMysqlColumn( case FIELD_SUBTYPE_INET: return varchar(45); case FIELD_SUBTYPE_DURATION: - // VARCHAR(64) holding the canonical ISO-8601 string (MySQL has no interval type; a bounded - // column can be keyed). The column function is the local duration codec. + // A BIGINT count of microseconds (MySQL has no interval type; an integer orders as the span). + // The column function is the local duration codec. return { fnName: DURATION_COLUMN_FN }; case FIELD_SUBTYPE_OBJECT: case FIELD_SUBTYPE_MAP: @@ -679,7 +679,7 @@ export function mapColumnType( fnName = "text"; break; case FIELD_SUBTYPE_DURATION: - // TEXT holding the canonical ISO-8601 string, through the local duration codec. + // A 64-bit INTEGER count of microseconds, through the local duration codec. fnName = DURATION_COLUMN_FN; break; default: diff --git a/server/typescript/packages/codegen-ts/src/contract/field-schema.ts b/server/typescript/packages/codegen-ts/src/contract/field-schema.ts index 66588effa1..32738fbb3c 100644 --- a/server/typescript/packages/codegen-ts/src/contract/field-schema.ts +++ b/server/typescript/packages/codegen-ts/src/contract/field-schema.ts @@ -79,7 +79,6 @@ export type RefFor = (target: MetaObject, shape: ContractShape) => string; * alone, where `T` is followed by at least one of hours, minutes and seconds, in that order. Digits * are `[0-9]` and groups capture, which I-Regexp also requires; the anchors make JSON Schema's search * a full match. test/contract/duration-json-schema-pattern.test.ts holds the two to the same verdicts. - * The 256204778-hour bound is the code's, not a pattern's. */ export const DURATION_JSON_SCHEMA_PATTERN = (() => { const seconds = "[0-9]+(\\.[0-9]{1,9})?S"; diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts index 4644b2aad1..5971c61a25 100644 --- a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts +++ b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts @@ -63,17 +63,18 @@ const NUMBER_SUBTYPES: ReadonlySet = new Set([ FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, ]); -// uri, inet and duration are strings on the wire, and Cube has no URI, network-address or interval -// dimension type, so each is a string dimension over its column. +// uri and inet are strings on the wire, and Cube has no URI or network-address dimension type, so +// each is a string dimension over its column. const STRING_SUBTYPES: ReadonlySet = new Set([ FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_UUID, FIELD_SUBTYPE_TIME, FIELD_SUBTYPE_URI, - FIELD_SUBTYPE_INET, FIELD_SUBTYPE_DURATION, + FIELD_SUBTYPE_INET, ]); // The subtypes `dimensionOfField` maps, in the order the refusal below lists them — derived from // the dispatch sets and checks, so the message cannot go stale when a mapping is added or removed. const MAPPED_DIMENSION_SUBTYPES: readonly string[] = [ - ...STRING_SUBTYPES, ...NUMBER_SUBTYPES, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, + ...STRING_SUBTYPES, ...NUMBER_SUBTYPES, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, + FIELD_SUBTYPE_TIMESTAMP, ]; /** `.`: a member's address, as `@of` and `@via` spell it. */ @@ -131,6 +132,14 @@ export function dimensionColumn( } if (STRING_SUBTYPES.has(field.subType)) return { sql: col, type: "string" }; if (NUMBER_SUBTYPES.has(field.subType)) return { sql: col, type: "number" }; + if (field.subType === FIELD_SUBTYPE_DURATION) { + // Cube has no interval dimension type; a number of SECONDS sorts and filters by the span. + // Postgres: EXTRACT(EPOCH FROM interval) is an exact numeric. MySQL stores a BIGINT count of + // microseconds; its `/` keeps only the dividend's scale plus div_precision_increment (4 by + // default), so the dividend is widened to six fractional digits first to keep every microsecond. + const sql = d === "postgres" ? `EXTRACT(EPOCH FROM ${col})` : `CAST(${col} AS DECIMAL(65, 6)) / 1000000`; + return { sql, type: "number" }; + } if (field.subType === FIELD_SUBTYPE_BOOLEAN) return { sql: col, type: "boolean" }; if (field.subType === FIELD_SUBTYPE_TIMESTAMP) return { sql: col, type: "time" }; if (field.subType === FIELD_SUBTYPE_DATE) { diff --git a/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts b/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts index 91b94c5ca2..0d2107acbf 100644 --- a/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts +++ b/server/typescript/packages/codegen-ts/src/prisma/build-prisma-schema.ts @@ -337,9 +337,9 @@ function mysqlColumnType(t: SqlType, field: MetaField, needsLength: boolean): Co return varchar(36); case FIELD_SUBTYPE_INET: return varchar(45); - // The canonical ISO-8601 string, in the column the Drizzle generator's MySQL arm writes. + // A BIGINT count of microseconds, the column the Drizzle generator's MySQL arm writes. case FIELD_SUBTYPE_DURATION: - return varchar(64); + return { scalar: "BigInt", list: false }; case FIELD_SUBTYPE_TIMESTAMP: return { scalar: "DateTime", list: false, native: "@db.DateTime(3)" }; case FIELD_SUBTYPE_TIME: diff --git a/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts b/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts index 15b69241b7..125ffd7670 100644 --- a/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts +++ b/server/typescript/packages/codegen-ts/src/templates/duration-wire-helper.ts @@ -6,8 +6,12 @@ // // Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left // out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. -// The emitted code holds a span as whole seconds plus microseconds (two JS numbers of one sign), -// so it needs no bigint and is exact for any span below 2^53 seconds. +// +// The emitted code counts a span in microseconds as a `bigint`, so it has no limit of its own: a +// span is as long as the stack it is stored in allows. The only limit here is a column's — the +// 64-bit integer a SQLite, D1 or MySQL column holds (refused past it, never wrapped). Postgres's +// interval has its own range, which Postgres enforces. The emitted code calls `BigInt(...)` and +// writes no bigint literal, so it needs the ES2020 `BigInt` global and nothing newer. import { code, imp, type Code } from "ts-poet"; import { DURATION_PATTERN } from "@metaobjectsdev/metadata"; @@ -23,67 +27,82 @@ export const ZOD_DURATION_EXPR = `z.string().regex(${DURATION_REGEX_LITERAL})`; export const DURATION_WRITE_HELPER = "durationWrite"; /** The Zod expression of a duration WRITE field: the accepted form, rewritten to the canonical one, - * so equal spans are stored as equal strings on every dialect. */ + * so equal spans are equal strings on the wire and in a jsonb value object. */ export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; -/** The largest span a field.duration holds, in whole seconds: 256204778 hours, the largest whole - * hour a .NET TimeSpan holds (fixtures/duration-wire). Every port refuses one microsecond more, so - * a value one port accepts every port can read. It also bounds the emitted arithmetic: 9.2e11 - * seconds is far below 2^53, so seconds and microseconds stay exact JS integers and never format - * in exponent notation. */ -export const DURATION_MAX_SECONDS = 256204778 * 3600; - /** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ -const ISO_PARTS_SOURCE = "/^([-+])?P(?!$)(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d{1,9}))?S)?)?$/"; +const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$/`; + +/** The default (`IntervalStyle = postgres`) text of a Postgres interval: signed year / mon / day + * parts, then an optionally signed `H:MM:SS[.ffffff]`. */ +const PG_INTERVAL_SOURCE = String.raw`/^(?:([-+]?\d+) years? ?)?(?:([-+]?\d+) mons? ?)?(?:([-+]?\d+) days? ?)?(?:([-+])?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/`; + +/** Indent every line of `block` by `n` spaces (blank lines stay blank). */ +function indent(block: string, n: number): string { + const pad = " ".repeat(n); + return block.split("\n").map((l) => (l === "" ? l : pad + l)).join("\n"); +} + +/** Microsecond unit constants, as `BigInt(...)` calls (no bigint literal). */ +const UNIT_LINES = [ + "const ZERO = BigInt(0);", + "const SECOND = BigInt(1000000);", + "const MINUTE = BigInt(60000000);", + "const HOUR = BigInt(3600000000);", + "const DAY = BigInt(86400000000);", +].join("\n"); -/** Lines formatting a span of `s` whole seconds plus `us` microseconds (one sign) canonically. */ -const ISO_FORMAT_LINES = [ - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - " const h = Math.floor(a / 3600);", - " const m = Math.floor((a % 3600) / 60);", - " const sec = a % 60;", +/** `parseIso(text)`: the microseconds of an accepted ISO-8601 duration, or undefined. */ +const PARSE_ISO_FN = [ + "const parseIso = (text: string): bigint | undefined => {", + ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, + " if (p === null) return undefined;", + " const mag = BigInt(p[2] ?? 0) * DAY + BigInt(p[3] ?? 0) * HOUR + BigInt(p[4] ?? 0) * MINUTE", + ' + BigInt(p[5] ?? 0) * SECOND + BigInt((p[6] ?? "").padEnd(6, "0").slice(0, 6));', + ' return p[1] === "-" ? -mag : mag;', + "};", +].join("\n"); + +/** `isoText(micros)`: the canonical wire form. */ +const ISO_TEXT_FN = [ + "const isoText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + " const s = rest / SECOND;", + " const f = rest % SECOND;", ' let out = "PT";', - ' if (h > 0) out += h + "H";', - ' if (m > 0) out += m + "M";', - ' if (sec > 0 || f > 0) out += sec + (f > 0 ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', + ' if (h > ZERO) out += String(h) + "H";', + ' if (m > ZERO) out += String(m) + "M";', + ' if (s > ZERO || f > ZERO) out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', ' if (out === "PT") return "PT0S";', ' return neg ? "-" + out : out;', -]; - -/** Lines matching `text` against the accepted form: `p` (null when it is not one), then `mag` whole - * seconds and `frac` microseconds of the span's magnitude. Read only after a null check on `p`. */ -const ISO_MATCH_LINES = [ - ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, - " const mag = p === null ? 0 : Number(p[2] ?? 0) * 86400 + Number(p[3] ?? 0) * 3600 + Number(p[4] ?? 0) * 60 + Number(p[5] ?? 0);", - ' const frac = p === null ? 0 : Number((p[6] ?? "").padEnd(6, "0").slice(0, 6));', -]; + "};", +].join("\n"); export const DURATION_WRITE_HELPER_DECL = [ "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", - " * fractional digits (truncated), one leading \"-\" for a negative span. A span past 256204778 hours", - " * (the bound every port holds) is a validation issue. Generated. */", - `function ${DURATION_WRITE_HELPER}(text: string, ctx: z.RefinementCtx): string {`, - ...ISO_MATCH_LINES, - " if (p === null) return text;", - ` if (mag > ${DURATION_MAX_SECONDS} || (mag === ${DURATION_MAX_SECONDS} && frac > 0)) {`, - ' ctx.addIssue({ code: "custom", message: "Duration out of range: at most 256204778 hours" });', - " return z.NEVER;", - " }", - ' const s = p[1] === "-" ? -mag : mag;', - ' const us = p[1] === "-" ? -frac : frac;', - ...ISO_FORMAT_LINES, + " * fractional digits (truncated), one leading \"-\" for a negative span. Counted in bigint", + " * microseconds, so any length is exact. Generated. */", + `function ${DURATION_WRITE_HELPER}(text: string): string {`, + indent(UNIT_LINES, 2), + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + " const micros = parseIso(text);", + " return micros === undefined ? text : isoText(micros);", "}", ].join("\n"); /** The physical column type a duration column's `customType` declares, per dialect: the - * Postgres-native interval; TEXT on SQLite; VARCHAR(64) on MySQL (the persistence corpus's - * canonical schemas, and what `meta migrate` writes). */ + * Postgres-native interval; a 64-bit integer count of microseconds on SQLite / D1 (INTEGER) and + * MySQL (BIGINT) — the persistence corpus's canonical schemas, and what `meta migrate` writes. */ export function durationColumnDataType(dialect: Dialect): string { - return dialect === "postgres" ? "interval" : dialect === "mysql" ? "varchar(64)" : "text"; + return dialect === "postgres" ? "interval" : dialect === "mysql" ? "bigint" : "integer"; } /** @@ -92,92 +111,87 @@ export function durationColumnDataType(dialect: Dialect): string { * declaration. Exported so a test can evaluate the exact text a generated module carries. * * - `toDriver` binds what the column holds: on Postgres the interval spelling `[-]HH:MM:SS[.f]` - * (Postgres refuses a signed ISO-8601 duration as interval input, and returns a value written - * this way in exactly this spelling); on SQLite and MySQL the canonical ISO-8601 string, so equal - * spans are equal strings. It takes the value in either spelling — an ISO-8601 duration (what the - * generated write schema hands it), or the Postgres interval text runtime-ts already binds a - * filter operand or a write in — and throws for anything else. - * - `fromDriver` reads what the driver returns — ISO-8601 text, Postgres interval text in the - * default `IntervalStyle`, or a node-postgres interval object — as the canonical ISO-8601 form. - * An interval with a year or month part is not a fixed-length span: reading one throws. + * (Postgres refuses a signed ISO-8601 duration, and returns a value written this way in exactly + * this spelling); on SQLite, D1 and MySQL the microsecond count — a number when it is a safe + * integer, else a bigint — refused past the 64-bit range, which is that column's limit. It takes + * the value as an ISO-8601 duration (what the generated write schema hands it), or as what + * runtime-ts already binds a filter operand in (the Postgres text; the microsecond integer), and + * throws for anything else. + * - `fromDriver` reads what the driver returns — the microsecond integer (a number, a bigint or a + * digit string), ISO-8601 text, Postgres interval text in the default `IntervalStyle`, or a + * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or + * month part is not a fixed-length span: reading one throws. */ export function durationColumnDeclParts(dialect: Dialect): [string, string] { - const bindPostgres = dialect === "postgres"; + const postgres = dialect === "postgres"; const before = [ - "/** A field.duration column. Binds " + (bindPostgres - ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration)," - : "the canonical ISO-8601 duration,"), - " * reads any interval back as the canonical ISO-8601 duration, and refuses an interval with a", - " * year or month part. Generated. */", + "/** A field.duration column. Binds " + (postgres + ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" + : "the span as a 64-bit integer count of microseconds (refused past that range);"), + " * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month", + " * part. Counted in bigint microseconds, so the column is the only limit. Generated. */", `const ${DURATION_COLUMN_FN} = (() => {`, - " const MICROS = 1000000;", - ` const MAX_SECONDS = ${DURATION_MAX_SECONDS};`, - " // A span normalised to one sign, refused past 256204778 hours (the bound every port holds).", - " const span = (s: number, us: number): [number, number] => {", - " s += Math.trunc(us / MICROS);", - " us %= MICROS;", - " if (s > 0 && us < 0) {", - " s -= 1;", - " us += MICROS;", - " } else if (s < 0 && us > 0) {", - " s += 1;", - " us -= MICROS;", - " }", - " const a = Math.abs(s);", - " if (!(a < MAX_SECONDS || (a === MAX_SECONDS && us === 0))) {", - ' throw new Error("a field.duration holds at most 256204778 hours (one microsecond more is refused)");', - " }", - " return [s, us];", - " };", - " const iso = (text: string): [number, number] | undefined => {", - ...ISO_MATCH_LINES.map((l) => " " + l), - " if (p === null) return undefined;", - ' return p[1] === "-" ? [-mag, -frac] : [mag, frac];', - " };", - " const isoText = ([s, us]: [number, number]): string => {", - ...ISO_FORMAT_LINES.map((l) => " " + l), - " };", - " const pgText = ([s, us]: [number, number]): string => {", - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - ' const two = (n: number): string => String(n).padStart(2, "0");', - ' let out = two(Math.floor(a / 3600)) + ":" + two(Math.floor((a % 3600) / 60)) + ":" + two(a % 60);', - ' if (f > 0) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', - ' return neg ? "-" + out : out;', - " };", - " const notFixed = (v: unknown): Error =>", - ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', - " const read = (v: unknown): [number, number] => {", - ' if (typeof v === "string") {', - " const fromIso = iso(v);", - " if (fromIso !== undefined) return span(fromIso[0], fromIso[1]);", - " const p = v.length === 0 ? null", - " : /^(?:([-+]?\\d+) years? ?)?(?:([-+]?\\d+) mons? ?)?(?:([-+]?\\d+) days? ?)?(?:([-+])?(\\d+):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?)?$/.exec(v);", - ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', - " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", - ' const t = p[5] === undefined ? 0 : Number(p[5]) * 3600 + Number(p[6]) * 60 + Number(p[7]);', - ' const tu = Number((p[8] ?? "").padEnd(6, "0"));', - ' const sign = p[4] === "-" ? -1 : 1;', - " return span(Number(p[3] ?? 0) * 86400 + sign * t, sign * tu);", - " }", - ' if (v !== null && typeof v === "object") {', - " const o = v as Record;", - " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", - " const whole = (n: number | undefined): number => Math.trunc(n ?? 0);", - " return span(", - " whole(o.days) * 86400 + whole(o.hours) * 3600 + whole(o.minutes) * 60 + whole(o.seconds),", - " Math.round((o.milliseconds ?? 0) * 1000),", - " );", - " }", - ' throw new Error("not a field.duration value: " + JSON.stringify(v));', - " };", + indent(UNIT_LINES, 2), + ` const INT64_MAX = BigInt("9223372036854775807");`, + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + indent([ + "const pgText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + ' const two = (n: bigint): string => String(n).padStart(2, "0");', + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + ' let out = two(h) + ":" + two(m) + ":" + two(rest / SECOND);', + " const f = rest % SECOND;", + ' if (f > ZERO) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', + ' return neg ? "-" + out : out;', + "};", + "const stored = (micros: bigint): number | bigint => {", + " if (micros > INT64_MAX || micros < -INT64_MAX - BigInt(1)) {", + ' throw new Error("the span " + isoText(micros) + " does not fit the 64-bit microsecond column a field.duration is stored in");', + " }", + " const n = Number(micros);", + " return Number.isSafeInteger(n) ? n : micros;", + "};", + "const notFixed = (v: unknown): Error =>", + ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', + "const read = (v: unknown): bigint => {", + ' if (typeof v === "bigint") return v;', + ' if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);', + ' if (typeof v === "string") {', + " if (/^-?\\d+$/.test(v)) return BigInt(v);", + " const iso = parseIso(v);", + " if (iso !== undefined) return iso;", + ` const p = v.length === 0 ? null : ${PG_INTERVAL_SOURCE}.exec(v);`, + ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', + " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", + " let time = ZERO;", + " if (p[5] !== undefined) {", + ' time = BigInt(p[5]) * HOUR + BigInt(p[6] ?? 0) * MINUTE + BigInt(p[7] ?? 0) * SECOND + BigInt((p[8] ?? "").padEnd(6, "0"));', + ' if (p[4] === "-") time = -time;', + " }", + " return BigInt(p[3] ?? 0) * DAY + time;", + " }", + ' if (v !== null && typeof v === "object") {', + " const o = v as Record;", + " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", + " const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0));", + " // postgres-interval carries microseconds as a fractional millisecond count.", + " return whole(o.days) * DAY + whole(o.hours) * HOUR + whole(o.minutes) * MINUTE + whole(o.seconds) * SECOND", + " + BigInt(Math.round((o.milliseconds ?? 0) * 1000));", + " }", + ' throw new Error("not a field.duration value: " + JSON.stringify(v));', + "};", + ].join("\n"), 2), " return ", ].join("\n"); const after = [ - "<{ data: string; driverData: string }>({", + `<{ data: string; driverData: ${postgres ? "string" : "number | bigint | string"} }>({`, ` dataType: () => ${JSON.stringify(durationColumnDataType(dialect))},`, - ` toDriver: (value) => ${bindPostgres ? "pgText" : "isoText"}(read(value)),`, + ` toDriver: (value) => ${postgres ? "pgText" : "stored"}(read(value)),`, " fromDriver: (value) => isoText(read(value)),", " });", "})();", diff --git a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts index 8f3e43a275..87c2dac54b 100644 --- a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts +++ b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts @@ -775,8 +775,8 @@ function zodFieldExpr( case FIELD_SUBTYPE_DURATION: // An ISO-8601 duration (days, hours, minutes, seconds; no years, months or weeks). A WRITE // shape rewrites it to the canonical form (duration-wire-helper.ts), so equal spans are - // equal strings in a text column and in a jsonb value object; the TPH read shape parses - // rows the column codec has already put in that form. + // equal strings on the wire and in a jsonb value object (the column codec binds the + // column's own form); the TPH read shape parses rows the codec has already put in it. if (readShape) { baseStr = ZOD_DURATION_EXPR; break; diff --git a/server/typescript/packages/codegen-ts/test/contract/duration-json-schema-pattern.test.ts b/server/typescript/packages/codegen-ts/test/contract/duration-json-schema-pattern.test.ts index ee1f66d9ac..ec16c41207 100644 --- a/server/typescript/packages/codegen-ts/test/contract/duration-json-schema-pattern.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/duration-json-schema-pattern.test.ts @@ -1,7 +1,6 @@ // The JSON Schema `pattern` of a field.duration is DURATION_PATTERN spelled without lookaround (not // I-Regexp; RE2-based validators refuse it). The two must give the same verdict on every duration -// vector. The 256204778-hour bound is enforced by code, not by either pattern, so the over-bound -// refused vectors MATCH both — they are checked for agreement, and left out of the "refused" check. +// vector, and on shapes around each lookahead the plain pattern replaces. import { describe, test, expect } from "bun:test"; import { readFileSync } from "node:fs"; @@ -14,9 +13,6 @@ const vectors = JSON.parse( readFileSync(join(import.meta.dir, "..", "..", "..", "..", "..", "..", "fixtures", "duration-wire", "vectors.json"), "utf8"), ) as Vectors; -/** Refused only because of the magnitude bound: syntactically they are durations. */ -const OVER_BOUND = new Set(["PT256204778H0.000001S", "PT256204779H", "P10675200D", "-PT256204779H"]); - const lookahead = new RegExp(DURATION_PATTERN); const plain = new RegExp(DURATION_JSON_SCHEMA_PATTERN); @@ -40,10 +36,7 @@ describe("the JSON Schema duration pattern", () => { for (const v of vectors.parse) { test(`accepts ${v.in}`, () => expect(plain.test(v.in)).toBe(true)); } - for (const v of vectors.refused.filter((r) => !OVER_BOUND.has(r))) { + for (const v of vectors.refused) { test(`refuses ${JSON.stringify(v)}`, () => expect(plain.test(v)).toBe(false)); } - test("every over-bound vector is still refused by the vectors (the exclusion list is not stale)", () => { - for (const v of OVER_BOUND) expect(vectors.refused).toContain(v); - }); }); diff --git a/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts b/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts index 5a06ae6b63..2aa37d6a30 100644 --- a/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts @@ -280,11 +280,19 @@ describe("Table C — dimension types", () => { ["time", { "field.time": { name: "x" } }], ["uri", { "field.uri": { name: "x" } }], ["inet", { "field.inet": { name: "x" } }], - ["duration", { "field.duration": { name: "x" } }], ])("%s → string, the column", async (_label, field) => { expect(await dimensionOf(field)).toEqual({ name: "d", sql: '{CUBE}."x"', type: "string" }); }); + test("duration → number, its span in seconds (exact), so it sorts and filters by length", async () => { + const field = { "field.duration": { name: "x" } }; + expect(await dimensionOf(field)).toEqual({ name: "d", sql: 'EXTRACT(EPOCH FROM {CUBE}."x")', type: "number" }); + // MySQL holds a BIGINT of microseconds; widening the dividend keeps all six fractional digits. + expect(await dimensionOf(field, {}, "mysql")).toEqual({ + name: "d", sql: "CAST({CUBE}.`x` AS DECIMAL(65, 6)) / 1000000", type: "number", + }); + }); + test("enum with @intValueMap → string, a CASE that carries the member symbol", async () => { expect( await dimensionOf({ "field.enum": { name: "x", "@values": ["A", "B"], "@intValueMap": { A: 1, B: 2 } } }), diff --git a/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts index bf4ec853c3..f7a0bd9ecd 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-duration-column.test.ts @@ -125,7 +125,7 @@ describe("generated field.duration columns", () => { expect(content).toContain(`durationColumn(`); } const hold = files.find((f) => f.path === "Hold.ts")!.content; - expect(hold).toContain(dialect === "postgres" ? 'dataType: () => "interval"' : dialect === "mysql" ? 'dataType: () => "varchar(64)"' : 'dataType: () => "text"'); + expect(hold).toContain(dialect === "postgres" ? 'dataType: () => "interval"' : dialect === "mysql" ? 'dataType: () => "bigint"' : 'dataType: () => "integer"'); // The write schemas carry the canonicalizing helper, once. expect(occurrences(hold, "function durationWrite(")).toBe(1); if (dialect === "postgres") expect(hold).toMatch(/laps: durationColumn\([^)]*\)\.array\(\)/); @@ -138,7 +138,7 @@ describe("generated field.duration columns", () => { }); } - test("sqlite: a duration round-trips through the generated table in its canonical form", async () => { + test("sqlite: a duration is stored as integer microseconds, reads back canonical, and orders as a span", async () => { const dir = mkdtempSync(join(import.meta.dir, "tmp-duration-sqlite-run-")); try { const files = await generate("sqlite", dir); @@ -147,9 +147,9 @@ describe("generated field.duration columns", () => { // drizzle alone, which resolves from this package. const mod = (await import(pathToFileURL(join(dir, "Hold.ts")).href)) as Record; const { drizzle } = await import("drizzle-orm/bun-sqlite"); - const { eq } = await import("drizzle-orm"); + const { asc, eq, gt, lt } = await import("drizzle-orm"); const sqlite = new Database(":memory:"); - sqlite.run("CREATE TABLE hold (id INTEGER PRIMARY KEY, hold_for TEXT NOT NULL, grace TEXT, laps TEXT)"); + sqlite.run("CREATE TABLE hold (id INTEGER PRIMARY KEY, hold_for INTEGER NOT NULL, grace INTEGER, laps TEXT)"); const db = drizzle(sqlite); // biome-ignore lint/suspicious/noExplicitAny: the generated table, imported dynamically const table = mod.holds as any; @@ -157,10 +157,25 @@ describe("generated field.duration columns", () => { id: 1, holdFor: "P1DT0.5S", grace: "-PT90S", laps: ["PT90M"], }); await db.insert(table).values(insert); - expect(sqlite.query("SELECT hold_for, grace FROM hold").get()).toEqual({ hold_for: "PT24H0.5S", grace: "-PT1M30S" }); + expect(sqlite.query("SELECT hold_for, grace FROM hold").get()).toEqual({ hold_for: 86400500000, grace: -90000000 }); // A filter value binds through the codec too: a spelling of the same span matches. const rows = await db.select().from(table).where(eq(table.holdFor, "P1DT0.5S")); expect(rows).toEqual([{ id: 1, holdFor: "PT24H0.5S", grace: "-PT1M30S", laps: ["PT1H30M"] }]); + // Ordering is the span's, not the text's: PT9S < PT10S < PT1H (as text, "PT10S" < "PT1H" < "PT9S"). + const parse = (mod.HoldInsertSchema as { parse(v: unknown): Record }).parse; + for (const [id, holdFor] of [[2, "PT10S"], [3, "PT9S"], [4, "PT1H"], [5, "-PT1M"]] as const) { + await db.insert(table).values(parse({ id, holdFor })); + } + const sorted = await db.select({ holdFor: table.holdFor }).from(table).orderBy(asc(table.holdFor)); + expect(sorted.map((r: { holdFor: string }) => r.holdFor)).toEqual(["-PT1M", "PT9S", "PT10S", "PT1H", "PT24H0.5S"]); + const between = await db.select({ id: table.id }).from(table) + .where(gt(table.holdFor, "PT9S")).orderBy(asc(table.holdFor)); + expect(between.map((r: { id: number }) => r.id)).toEqual([2, 4, 1]); + const under = await db.select({ id: table.id }).from(table).where(lt(table.holdFor, "PT10S")).orderBy(asc(table.id)); + expect(under.map((r: { id: number }) => r.id)).toEqual([3, 5]); + // runtime-ts binds a SQLite operand as the microsecond integer; the codec passes it through. + const byMicros = await db.select({ id: table.id }).from(table).where(eq(table.holdFor, 10000000 as never)); + expect(byMicros).toEqual([{ id: 2 }]); sqlite.close(); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts b/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts index 4f981e3417..9dd8c1f505 100644 --- a/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts +++ b/server/typescript/packages/codegen-ts/test/duration-wire-helper.test.ts @@ -23,6 +23,7 @@ interface Vectors { postgres: Array<{ in: string; out: string }>; postgresRefused: string[]; postgresText: Array<{ in: string; out: string }>; + storedMicros: Array<{ in: string; out: string }>; } const vectors = JSON.parse( readFileSync(join(import.meta.dir, "..", "..", "..", "..", "..", "fixtures", "duration-wire", "vectors.json"), "utf8"), @@ -37,7 +38,7 @@ function writeSchema(): z.ZodType { return new Function("z", body)(z) as z.ZodType; } -interface Codec { dataType(): string; toDriver(v: string): string; fromDriver(v: unknown): string } +interface Codec { dataType(): string; toDriver(v: string): string | number | bigint; fromDriver(v: unknown): string } /** The column codec exactly as a generated module spells it; `customType` hands back its config. */ function columnCodec(dialect: Dialect): Codec { @@ -64,15 +65,12 @@ describe("generated duration write schema", () => { expect(schema.safeParse(v).success).toBe(false); }); } - test("the 256204778-hour bound: exactly at it is kept, one microsecond over is refused, and no value is formatted in exponent notation", () => { - expect(schema.parse("PT256204778H")).toBe("PT256204778H"); - expect(schema.parse("-PT922337200800S")).toBe("-PT256204778H"); - expect(schema.parse("PT256204777H59M59.999999S")).toBe("PT256204777H59M59.999999S"); - for (const over of ["PT256204778H0.000001S", "-PT256204778H0.000001S", "PT922337200801S", "P99999999999999999999999D", "PT1" + "0".repeat(400) + "S"]) { - const r = schema.safeParse(over); - expect(r.success, over).toBe(false); - expect(JSON.stringify(r.success ? "" : r.error.issues), over).toContain("256204778 hours"); - } + test("no limit of its own: a span past every 64-bit or TimeSpan range is exact, never in exponent notation", () => { + expect(schema.parse("PT256204779H")).toBe("PT256204779H"); + expect(schema.parse("P99999999999999999999999D")).toBe("PT2399999999999999999999976H"); + expect(schema.parse("PT1" + "0".repeat(40) + ".000001S")).toBe( + "PT2777777777777777777777777777777777777H46M40.000001S", + ); }); test("a non-string is refused", () => { expect(schema.safeParse(90).success).toBe(false); @@ -85,42 +83,54 @@ describe("generated duration column codec", () => { const sqlite = columnCodec("sqlite"); const mysql = columnCodec("mysql"); - test("the physical column type per dialect", () => { + test("the physical column type per dialect: interval; a 64-bit integer of microseconds elsewhere", () => { expect(pg.dataType()).toBe("interval"); - expect(sqlite.dataType()).toBe("text"); - expect(mysql.dataType()).toBe("varchar(64)"); + expect(sqlite.dataType()).toBe("integer"); + expect(mysql.dataType()).toBe("bigint"); }); for (const v of vectors.postgresText) { - test(`Postgres binds ${v.in} as ${v.out}`, () => { + test(`Postgres binds ${v.in} as ${v.out}, and reads it back`, () => { expect(pg.toDriver(v.in)).toBe(v.out); + expect(pg.fromDriver(v.out)).toBe(v.in); }); } - for (const v of vectors.parse) { - test(`SQLite / MySQL bind ${v.in} as ${v.out}; Postgres reads its own spelling back`, () => { - expect(sqlite.toDriver(v.in)).toBe(v.out); - expect(mysql.toDriver(v.in)).toBe(v.out); - expect(pg.fromDriver(pg.toDriver(v.in))).toBe(v.out); - expect(sqlite.fromDriver(v.in)).toBe(v.out); - }); - } - // The codec also takes the Postgres spelling, which runtime-ts binds a filter operand in; of the - // refused ISO inputs only `1:30:00` is that spelling (one hour thirty), so it alone binds. - for (const v of vectors.refused.filter((r) => r !== "1:30:00")) { - test(`binding ${JSON.stringify(v)} throws`, () => { - expect(() => pg.toDriver(v)).toThrow(); - expect(() => sqlite.toDriver(v)).toThrow(); + for (const v of vectors.storedMicros) { + test(`SQLite / MySQL store ${v.in} as ${v.out} microseconds, and read it back`, () => { + for (const codec of [sqlite, mysql]) { + expect(String(codec.toDriver(v.in))).toBe(v.out); + // A driver hands the integer back as a number, a bigint or a digit string. + expect(codec.fromDriver(Number(v.out))).toBe(v.in); + expect(codec.fromDriver(BigInt(v.out))).toBe(v.in); + expect(codec.fromDriver(v.out)).toBe(v.in); + } }); } - for (const v of vectors.postgresText) { - test(`binding the Postgres spelling ${v.out} is the same span`, () => { - expect(pg.toDriver(v.out)).toBe(v.out); - expect(sqlite.toDriver(v.out)).toBe(v.in); + for (const v of vectors.parse) { + test(`${v.in} round-trips as ${v.out} on every dialect`, () => { + for (const codec of [pg, sqlite, mysql]) expect(codec.fromDriver(codec.toDriver(v.in))).toBe(v.out); }); } - for (const v of vectors.postgresRefused) { - test(`binding ${v} throws (a year or month part, or not an interval)`, () => { - expect(() => pg.toDriver(v)).toThrow(); + test("a safe microsecond count binds as a number; past 2^53 as a bigint; past the 64-bit range it is refused", () => { + expect(sqlite.toDriver("PT876000H")).toBe(3153600000000000); + expect(sqlite.toDriver("PT2562047788H")).toBe(BigInt("9223372036800000000")); + expect(sqlite.fromDriver(BigInt("9223372036800000000"))).toBe("PT2562047788H"); + expect(() => sqlite.toDriver("PT2562047789H")).toThrow(/64-bit/); + expect(() => mysql.toDriver("-PT2562047789H")).toThrow(/64-bit/); + // Postgres has no such limit in the codec: its interval range is Postgres's to enforce. + expect(pg.toDriver("PT2562047789H")).toBe("2562047789:00:00"); + }); + test("runtime-ts's filter operands bind through the codec unchanged: the micros on SQLite / MySQL, the interval text on Postgres", () => { + expect(sqlite.toDriver(5400000000 as never)).toBe(5400000000); + expect(mysql.toDriver(BigInt("-90000000") as never)).toBe(-90000000); + expect(pg.toDriver("01:30:00")).toBe("01:30:00"); + }); + for (const v of vectors.refused) { + test(`binding ${JSON.stringify(v)} throws`, () => { + // The codec takes the Postgres spelling too (runtime-ts binds a Postgres operand in it), and + // `1:30:00` is that spelling — one hour thirty — so on Postgres it binds. + if (v !== "1:30:00") expect(() => pg.toDriver(v)).toThrow(); + expect(() => sqlite.toDriver(v === "1:30:00" ? "1:30" : v)).toThrow(); }); } for (const v of vectors.postgres) { @@ -129,28 +139,17 @@ describe("generated duration column codec", () => { }); } for (const v of vectors.postgresRefused) { - test(`Postgres text ${v} is refused on read`, () => { + test(`Postgres text ${v} is refused on read and on bind`, () => { expect(() => pg.fromDriver(v)).toThrow(); + expect(() => pg.toDriver(v)).toThrow(); }); } - test("the codec holds the same bound on bind and on read", () => { - expect(pg.toDriver("PT256204778H")).toBe("256204778:00:00"); - expect(pg.toDriver("-PT256204778H")).toBe("-256204778:00:00"); - expect(sqlite.toDriver("-P10675199DT2H")).toBe("-PT256204778H"); - for (const over of ["PT256204778H0.000001S", "P99999999999999999999999D", "256204778:00:00.000001", "10675199 days 02:00:01"]) { - expect(() => pg.toDriver(over), over).toThrow(/256204778 hours/); - expect(() => sqlite.toDriver(over), over).toThrow(/256204778 hours/); - expect(() => pg.fromDriver(over), over).toThrow(/256204778 hours/); - } - expect(() => pg.fromDriver({ days: 10675200 })).toThrow(/256204778 hours/); - // Mixed signs that net back inside the bound read fine. - expect(pg.fromDriver("10675200 days -24:00:00")).toBe("PT256204776H"); - }); test("a node-postgres interval object reads as the canonical form; a month part is refused", () => { expect(pg.fromDriver({ days: 1, hours: 2 })).toBe("PT26H"); expect(pg.fromDriver({ minutes: -1, seconds: -30 })).toBe("-PT1M30S"); expect(pg.fromDriver({ seconds: 1, milliseconds: 500.25 })).toBe("PT1.50025S"); expect(() => pg.fromDriver({ months: 1 })).toThrow(/year or month/); - expect(() => pg.fromDriver(42)).toThrow(); + expect(() => pg.fromDriver(1.5)).toThrow(); + expect(() => pg.fromDriver(true)).toThrow(); }); }); diff --git a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts index 919761d068..334392ef74 100644 --- a/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts +++ b/server/typescript/packages/codegen-ts/test/prisma/prisma-schema.test.ts @@ -137,7 +137,7 @@ describe("prisma-schema — what the schema says", () => { } }); - test("a field.duration: Unsupported(\"interval\") on Postgres, VarChar(64) on MySQL, String on SQLite", async () => { + test("a field.duration: Unsupported(\"interval\") on Postgres, BigInt microseconds on MySQL and SQLite", async () => { const root = await loadJson(model([entity("Hold", [ { "source.rdb": { "@table": "holds" } }, longId, { "field.duration": { name: "holdFor", "@required": true } }, @@ -148,8 +148,9 @@ describe("prisma-schema — what the schema says", () => { const pg = fieldsOf("postgresql"); expect(pg.find((f) => f.name === "holdFor")).toMatchObject({ type: 'Unsupported("interval")', list: false }); expect(pg.find((f) => f.name === "laps")).toMatchObject({ type: 'Unsupported("interval[]")', list: false }); - expect(fieldsOf("mysql").find((f) => f.name === "holdFor")!.attributes).toContain("@db.VarChar(64)"); - expect(fieldsOf("sqlite").find((f) => f.name === "holdFor")).toMatchObject({ type: "String", list: false }); + // SQLite and MySQL store a 64-bit integer count of microseconds. + expect(fieldsOf("mysql").find((f) => f.name === "holdFor")).toMatchObject({ type: "BigInt", list: false }); + expect(fieldsOf("sqlite").find((f) => f.name === "holdFor")).toMatchObject({ type: "BigInt", list: false }); }); test("a self relation is named, so its two ends pair", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/filter-allowlist.test.ts b/server/typescript/packages/codegen-ts/test/templates/filter-allowlist.test.ts index 055a278a1a..c12514556a 100644 --- a/server/typescript/packages/codegen-ts/test/templates/filter-allowlist.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/filter-allowlist.test.ts @@ -31,6 +31,23 @@ describe("renderFilterAllowlist", () => { expect(out).toMatch(/createdAt:\s*\{[^}]*"gte"/); }); + test("a field.duration carries the ordered band and its wire format, and is sortable", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ + "metadata.root": { package: "t", children: [{ "object.entity": { name: "Hold", children: [ + { "source.rdb": { "@table": "hold" } }, + { "field.long": { name: "id" } }, + { "field.duration": { name: "holdFor", "@filterable": true } }, + { "identity.primary": { name: "pk", "@fields": "id" } }, + ] } }] }, + }))]); + expect(errors).toEqual([]); + const hold = root.objects().find((c) => c.name === "Hold")!; + const out = renderFilterAllowlist(hold).toString(); + expect(out).toMatch(/holdFor:\s*\{[^}]*ops: \["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"\]/); + expect(out).toMatch(/holdFor:\s*\{[^}]*format: "duration"/); + expect(renderSortAllowlist(hold).toString()).toContain("holdFor"); + }); + test("only @filterable fields appear in allowlist", async () => { const entity = await loadEntity("Subscriber"); const out = renderFilterAllowlist(entity).toString(); diff --git a/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts b/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts index 2139dc65c2..862721211a 100644 --- a/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts +++ b/server/typescript/packages/codegen-ts/test/zod-validators-execution.test.ts @@ -264,9 +264,9 @@ describe("field.duration — the accepted ISO-8601 form, stored canonically", () expect(schema.parse({ holdFor: "P1DT2H" }).holdFor).toBe("PT26H"); expect(schema.parse({ holdFor: "-PT90S" }).holdFor).toBe("-PT1M30S"); expect(schema.parse({ holdFor: "PT1.123456789S" }).holdFor).toBe("PT1.123456S"); - // The shared bound: 256204778 hours, one microsecond more refused. - expect(schema.parse({ holdFor: "-P10675199DT2H" }).holdFor).toBe("-PT256204778H"); - for (const bad of ["P1M", "P1Y", "P2W", "1:30:00", "PT1.5H", "pt1h", "PT", "", "PT256204779H", "PT256204778H0.000001S"]) { + // No cross-port bound: the helper counts in bigint, so a span past any 64-bit range is exact. + expect(schema.parse({ holdFor: "PT256204779H" }).holdFor).toBe("PT256204779H"); + for (const bad of ["P1M", "P1Y", "P2W", "1:30:00", "PT1.5H", "pt1h", "PT", ""]) { expect(accepts(schema, { holdFor: bad })).toBe(false); } }); diff --git a/server/typescript/packages/integration-tests/src/canonical-schema-mysql.ts b/server/typescript/packages/integration-tests/src/canonical-schema-mysql.ts index 79e247a45f..85e0896ed4 100644 --- a/server/typescript/packages/integration-tests/src/canonical-schema-mysql.ts +++ b/server/typescript/packages/integration-tests/src/canonical-schema-mysql.ts @@ -118,7 +118,7 @@ const TABLES = [ \`uriVal\` VARCHAR(255) NOT NULL, \`inetVal\` VARCHAR(45) NOT NULL, \`inet6Val\` VARCHAR(45) NOT NULL, - \`durationVal\` VARCHAR(64), + \`durationVal\` BIGINT, \`settings\` JSON, \`labels\` JSON )`, diff --git a/server/typescript/packages/metadata/src/core/field/duration-wire.ts b/server/typescript/packages/metadata/src/core/field/duration-wire.ts index f872d909d1..50fa17cacc 100644 --- a/server/typescript/packages/metadata/src/core/field/duration-wire.ts +++ b/server/typescript/packages/metadata/src/core/field/duration-wire.ts @@ -28,22 +28,9 @@ const MICROS_PER_MINUTE = 60n * MICROS_PER_SECOND; const MICROS_PER_HOUR = 60n * MICROS_PER_MINUTE; const MICROS_PER_DAY = 24n * MICROS_PER_HOUR; -/** The largest magnitude a duration may have: 256204778 hours, the largest whole hour a .NET - * TimeSpan holds, so a span any port accepts every port can read back. One microsecond more is - * refused on input and on read. */ -export const DURATION_MAX_HOURS = 256204778n; -const MAX_MICROS = DURATION_MAX_HOURS * MICROS_PER_HOUR; - -function withinBound(micros: bigint): boolean { - return micros <= MAX_MICROS && micros >= -MAX_MICROS; -} - -function bounded(micros: bigint, what: string): bigint { - if (!withinBound(micros)) { - throw new Error(`${what} is longer than ${DURATION_MAX_HOURS} hours, the longest field.duration every port can hold`); - } - return micros; -} +/** A 64-bit integer column (SQLite, D1, MySQL `BIGINT`) stores a duration as microseconds; it holds + * this many either way. A database's own limit, so it is checked only when binding to one. */ +const INT64_MAX = 9223372036854775807n; /** Up to nine fractional-second digits as microseconds, truncated toward zero. */ function fractionMicros(digits: string | undefined): bigint { @@ -63,7 +50,6 @@ export function parseDurationLiteral(text: string): bigint | undefined { BigInt(min ?? "0") * MICROS_PER_MINUTE + BigInt(s ?? "0") * MICROS_PER_SECOND + fractionMicros(f); - if (magnitude > MAX_MICROS) return undefined; return sign === "-" ? -magnitude : magnitude; } @@ -137,7 +123,7 @@ export function parsePostgresInterval(text: string): bigint { time = BigInt(h) * MICROS_PER_HOUR + BigInt(min!) * MICROS_PER_MINUTE + BigInt(s!) * MICROS_PER_SECOND + fractionMicros(f); if (timeSign === "-") time = -time; } - return bounded(BigInt(days ?? "0") * MICROS_PER_DAY + time, `the interval ${JSON.stringify(text)}`); + return BigInt(days ?? "0") * MICROS_PER_DAY + time; } /** The fields node-postgres's default interval parser (`postgres-interval`) hands back. */ @@ -159,14 +145,33 @@ function intervalObjectMicros(v: PostgresIntervalLike): bigint { const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0)); // postgres-interval carries microseconds as a fractional millisecond count. const micros = BigInt(Math.round((v.milliseconds ?? 0) * 1000)); - return bounded(whole(v.days) * MICROS_PER_DAY + whole(v.hours) * MICROS_PER_HOUR - + whole(v.minutes) * MICROS_PER_MINUTE + whole(v.seconds) * MICROS_PER_SECOND + micros, `the interval ${JSON.stringify(v)}`); + return whole(v.days) * MICROS_PER_DAY + whole(v.hours) * MICROS_PER_HOUR + + whole(v.minutes) * MICROS_PER_MINUTE + whole(v.seconds) * MICROS_PER_SECOND + micros; +} + +/** + * Write side, for a 64-bit integer column (SQLite, D1, MySQL): the span as the microsecond count the + * column stores — a number when it is a safe integer, else a bigint. Throws past the 64-bit range, + * which is that column's limit and no other database's. + */ +export function durationToStoredMicros(micros: bigint): number | bigint { + if (micros > INT64_MAX || micros < -INT64_MAX - 1n) { + throw new Error(`a span of ${formatDuration(micros)} does not fit the 64-bit microsecond column this database stores a field.duration in`); + } + const n = Number(micros); + return Number.isSafeInteger(n) ? n : micros; } -/** Read side: what a driver hands back for a duration column — an ISO string (a text column, or - * Postgres under `IntervalStyle = iso_8601`), the default Postgres interval text, or a - * node-postgres interval object — as the canonical wire string. Throws for anything else. */ +/** Read side: what a driver hands back for a duration column — the microsecond integer of a SQLite, + * D1 or MySQL column, an ISO string (Postgres under `IntervalStyle = iso_8601`), the default + * Postgres interval text, or a node-postgres interval object — as the canonical wire string. + * Throws for anything else. */ export function durationToWire(value: unknown): string { + // A 64-bit integer column (SQLite, D1, MySQL) holds microseconds; a driver may return it as a + // number, a bigint or a digit string. + if (typeof value === "bigint") return formatDuration(value); + if (typeof value === "number" && Number.isInteger(value)) return formatDuration(BigInt(value)); + if (typeof value === "string" && /^-?\d+$/.test(value)) return formatDuration(BigInt(value)); if (typeof value === "string") { const iso = canonicalDuration(value); return iso ?? formatDuration(parsePostgresInterval(value)); diff --git a/server/typescript/packages/metadata/src/core/field/field-constants.ts b/server/typescript/packages/metadata/src/core/field/field-constants.ts index b4e89fcc4c..0c340412a1 100644 --- a/server/typescript/packages/metadata/src/core/field/field-constants.ts +++ b/server/typescript/packages/metadata/src/core/field/field-constants.ts @@ -38,7 +38,7 @@ export const FIELD_SUBTYPE_INET = "inet"; * native type + behavior → a subtype. TS binds to `string` (an ISO-8601 * duration; TS has no native duration type); other ports bind to native * (TimeSpan / java.time.Duration / timedelta). DB column is Postgres-native - * `interval`, text elsewhere. Years, months and weeks are refused. */ + * `interval`, a 64-bit microsecond integer elsewhere. Years, months and weeks are refused. */ export const FIELD_SUBTYPE_DURATION = "duration"; export const FIELD_SUBTYPES = [ diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index 948b012633..a63aad472f 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -352,7 +352,7 @@ export const FIELD_DEFINITION: ProviderDefinition = { "subType": "duration", "dataType": "string", "extendsBase": true, - "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit." } ] diff --git a/server/typescript/packages/metadata/src/core/query/query-constants.ts b/server/typescript/packages/metadata/src/core/query/query-constants.ts index 102235a13e..df65704691 100644 --- a/server/typescript/packages/metadata/src/core/query/query-constants.ts +++ b/server/typescript/packages/metadata/src/core/query/query-constants.ts @@ -61,10 +61,9 @@ export const OPS_BY_SUBTYPE: Readonly> = { // inet: an IP address — identity-comparison ops only (no `like`; ordering // gt/lt is not exposed). Same op band as uuid. [FIELD_SUBTYPE_INET]: [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_IN, FILTER_OP_IS_NULL], - // duration: identity-comparison ops only for now. Ordering is not exposed: a - // text column (SQLite, MySQL) cannot order ISO-8601 strings. Adding it later - // is additive. - [FIELD_SUBTYPE_DURATION]: [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_IN, FILTER_OP_IS_NULL], + // duration: ordered on every database — a Postgres interval, and the 64-bit + // microsecond integer SQLite / D1 / MySQL store it as. + [FIELD_SUBTYPE_DURATION]: [FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, FILTER_OP_IN, FILTER_OP_IS_NULL], } as const; export function opsForSubType(subType: string): readonly FilterOp[] { diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts index 9e5d9d4915..61ab0fe8ab 100644 --- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts +++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts @@ -565,7 +565,7 @@ export function sqliteType(t: SqlType, identity: ColumnDescriptor["identity"]): case "blob": return "BLOB"; case "uuid": return "TEXT"; case "inet": return "TEXT"; // SQLite has no inet type; store as text - case "interval": return "TEXT"; // the canonical ISO-8601 duration string + case "interval": return "INTEGER"; // the duration's microseconds (orders as the span does) case "array": return "TEXT"; // SQLite has no array type; store as JSON text } } diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index f30ef61235..642d866e07 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -51,7 +51,6 @@ import { FIELD_SUBTYPE_URI, FIELD_SUBTYPE_INET, FIELD_SUBTYPE_DURATION, - formatDuration, formatPostgresInterval, parseDurationLiteral, parsePostgresInterval, @@ -332,10 +331,10 @@ export function buildExpectedSchemaWithProvenance( const normalized = normalizeBooleanLiteralForSqlite(col.default.value); if (normalized !== undefined) col.default = { kind: "literal", value: normalized }; } - // A duration's default is built in the Postgres interval spelling; a TEXT column holds - // the canonical ISO-8601 form, which is what the runtime writes there. + // A duration's default is built in the Postgres interval spelling; the SQLite column holds + // the microsecond integer, which is what the runtime writes there. if (kindBefore === "interval" && col.default?.kind === "literal") { - col.default = { kind: "literal", value: formatDuration(parsePostgresInterval(col.default.value)) }; + col.default = { kind: "literal", value: String(parsePostgresInterval(col.default.value)) }; } // `now()` is Postgres-only; SQLite has no such function, so a // `DEFAULT now()` (the @autoSet insert-time default, and any authored @@ -500,8 +499,10 @@ function normalizeForSqlite(sqlType: SqlType): SqlType { case "timestamp": case "date": case "time": - case "interval": return { kind: "text" }; + case "interval": + // A duration is the 64-bit microsecond count: an integer orders and compares as the span. + return { kind: "integer", bits: 64 }; case "integer": // SQLite stores every INTEGER as a 64-bit value and Drizzle's int() emits // plain "INTEGER" regardless of source bit-width. Collapse 32 → 64 so the diff --git a/server/typescript/packages/migrate-ts/test/unit/duration-column.test.ts b/server/typescript/packages/migrate-ts/test/unit/duration-column.test.ts new file mode 100644 index 0000000000..5f19b05e7a --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/unit/duration-column.test.ts @@ -0,0 +1,39 @@ +/** + * field.duration's column: a native INTERVAL on Postgres (a @default in Postgres's own interval + * spelling, which it reads back unchanged), and on SQLite the 64-bit microsecond INTEGER the + * runtimes store, so it orders and compares as the span does (a @default is that integer too). + */ +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../../src/expected-schema.js"; +import { emit } from "../../src/emit/index.js"; +import { diff } from "../../src/diff/index.js"; + +const DOC = JSON.stringify({ "metadata.root": { package: "acme", children: [{ "object.entity": { name: "Timer", children: [ + { "source.rdb": { "@table": "timers" } }, + { "field.long": { name: "id" } }, + { "field.duration": { name: "grace", "@default": "-PT90M" } }, + { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, +] } }] } }); + +async function column(dialect: "postgres" | "sqlite") { + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(DOC)]); + const schema = buildExpectedSchema(root, { dialect }); + return { schema, col: schema.tables[0]!.columns.find((c) => c.name === "grace")! }; +} + +describe("field.duration column", () => { + test("Postgres: INTERVAL, default in the interval spelling", async () => { + const { col } = await column("postgres"); + expect(col.sqlType).toEqual({ kind: "interval" }); + expect(col.default).toEqual({ kind: "literal", value: "-01:30:00" }); + }); + + test("SQLite: a 64-bit INTEGER of microseconds, default included", async () => { + const { schema, col } = await column("sqlite"); + expect(col.sqlType).toEqual({ kind: "integer", bits: 64 }); + expect(col.default).toEqual({ kind: "literal", value: "-5400000000" }); + const { changes } = await diff({ expected: schema, actual: { tables: [], views: [] }, dialect: "sqlite" }); + expect(emit(changes, { dialect: "sqlite", expectedSchema: schema }).up).toContain('"grace" INTEGER DEFAULT -5400000000'); + }); +}); diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts index 4a438c3e9c..00d2177ab1 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/filter-parser.ts @@ -17,7 +17,7 @@ import { } from "./filter-value-format.js"; import { FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_TIMESTAMP } from "@metaobjectsdev/metadata"; import { canonicalDecimal } from "../decimal-wire.js"; -import { formatDuration, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; +import { durationToStoredMicros, formatPostgresInterval, parseDurationLiteral } from "../duration-wire.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user's Drizzle table type AnyTable = any; @@ -345,12 +345,12 @@ function coerce(value: unknown, rule: FilterFieldRule, col: unknown, field: stri if (dialect === "mysql") return sql`CAST(${canonical} AS DECIMAL(65,30))`; return dialect === "sqlite" ? Number(canonical) : canonical; } - // A duration bound is spelled the way the column stores it: the canonical string on a text - // column (SQLite, MySQL), so `PT90M` equals a stored `PT1H30M`; the interval spelling on - // Postgres, which compares spans and refuses a signed ISO-8601 duration. + // A duration bound is spelled the way the column stores it: the microsecond integer on SQLite / + // D1 / MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). Both + // compare and order as the span does. if (rule.format === FIELD_SUBTYPE_DURATION) { const micros = parseDurationLiteral(s) as bigint; - return dialect === "sqlite" || dialect === "mysql" ? formatDuration(micros) : formatPostgresInterval(micros); + return dialect === "sqlite" || dialect === "mysql" ? durationToStoredMicros(micros) : formatPostgresInterval(micros); } // A timestamp bound is compared in the same UTC spelling the generated schemas store: // on SQLite/D1 the column is TEXT and compares as text. An instant field (`instant`, i.e. diff --git a/server/typescript/packages/runtime-ts/src/duration-wire.ts b/server/typescript/packages/runtime-ts/src/duration-wire.ts index dc820cd628..7f5ea68bde 100644 --- a/server/typescript/packages/runtime-ts/src/duration-wire.ts +++ b/server/typescript/packages/runtime-ts/src/duration-wire.ts @@ -2,5 +2,5 @@ // re-exported here so the runtime's callers import it beside the decimal wire helpers. export { DURATION_PATTERN, DURATION_RE, parseDurationLiteral, formatDuration, formatPostgresInterval, - canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, + canonicalDuration, parseDurationInput, parsePostgresInterval, durationToWire, durationToStoredMicros, } from "@metaobjectsdev/metadata"; diff --git a/server/typescript/packages/runtime-ts/src/query-builder.ts b/server/typescript/packages/runtime-ts/src/query-builder.ts index 0caaf19a4b..46f0180ff7 100644 --- a/server/typescript/packages/runtime-ts/src/query-builder.ts +++ b/server/typescript/packages/runtime-ts/src/query-builder.ts @@ -7,7 +7,7 @@ import { DEFAULT_COLUMN_NAMING_STRATEGY, FIELD_SUBTYPE_DURATION, resolveTableName, resolveColumnName, - formatDuration, formatPostgresInterval, parseDurationLiteral, + durationToStoredMicros, formatDuration, formatPostgresInterval, parseDurationLiteral, } from "@metaobjectsdev/metadata"; import { MetadataError } from "./errors.js"; import { intValueMapOf } from "./type-coercer.js"; @@ -171,15 +171,17 @@ function compileEntry( * pins `@intValueMap`'s key set to `@values`. */ function encodeFilterValue(field: MetaData, value: T, dialect?: Dialect): T { - // A duration is compared in the spelling its column stores: the canonical ISO string on a text - // column (so `PT90M` equals a stored `PT1H30M`), and the interval spelling on Postgres, which - // refuses a signed ISO-8601 duration. A value that is not a duration is refused, not bound. + // A duration is compared in the form its column stores: the microsecond integer on SQLite / D1 / + // MySQL, the interval spelling on Postgres (which refuses a signed ISO-8601 duration). A value + // that is not a duration is refused, not bound. if (field.subType === FIELD_SUBTYPE_DURATION && typeof value === "string") { const micros = parseDurationLiteral(value); if (micros === undefined) { throw new MetadataError(`filter on field.duration '${field.name}': ${JSON.stringify(value)} is not an ISO-8601 duration`); } - return (dialect === "postgres" ? formatPostgresInterval(micros) : formatDuration(micros)) as T; + if (dialect === "postgres") return formatPostgresInterval(micros) as T; + if (dialect === "sqlite" || dialect === "mysql") return durationToStoredMicros(micros) as T; + return formatDuration(micros) as T; } const intMap = intValueMapOf(field); if (intMap === undefined || typeof value !== "string") return value; diff --git a/server/typescript/packages/runtime-ts/src/type-coercer.ts b/server/typescript/packages/runtime-ts/src/type-coercer.ts index 0ebfabec06..96cf7760f2 100644 --- a/server/typescript/packages/runtime-ts/src/type-coercer.ts +++ b/server/typescript/packages/runtime-ts/src/type-coercer.ts @@ -41,7 +41,9 @@ import { } from "@metaobjectsdev/metadata"; import type { Dialect, Row } from "./persistence-driver.js"; import { decimalFits, decimalToWire, parseDecimalInput } from "./decimal-wire.js"; -import { durationToWire, formatDuration, formatPostgresInterval, parseDurationLiteral } from "./duration-wire.js"; +import { + durationToStoredMicros, durationToWire, formatDuration, formatPostgresInterval, parseDurationLiteral, +} from "./duration-wire.js"; export function coerceRowOnRead(entity: MetaData, row: Row, dialect: Dialect): Row { const hydrated = parseJsonTextArrays(entity, deserializeJsonbObjectFields(entity, row)); @@ -451,16 +453,19 @@ function canonicalizeDurations(entity: MetaData, row: Row): Row { return mapDurations(entity, row, (_field, v) => durationToWire(v)); } -/** Write side: a duration is bound as its canonical ISO-8601 string on a text column (SQLite, - * MySQL), so the column holds one spelling per span, and in the Postgres interval spelling on - * Postgres, which refuses a signed ISO-8601 duration. A value that is not a duration is refused - * here, not by the database. */ +/** Write side: a duration column is bound as the 64-bit microsecond integer SQLite, D1 and MySQL + * store it as, and in the Postgres interval spelling on Postgres, which refuses a signed ISO-8601 + * duration. A duration inside a jsonb value object is JSON, so it is the canonical ISO string. A + * value that is not a duration is refused here, not by the database. */ function bindDurations(entity: MetaData, row: Row, dialect: Dialect): Row { return mapDurations(entity, row, (child, v, top) => { const micros = typeof v === "string" ? parseDurationLiteral(v) : undefined; if (micros === undefined) { throw new Error(`field.duration '${child.name}' cannot be written: ${JSON.stringify(v)} is not an ISO-8601 duration (such as PT1H30M; no years, months or weeks)`); } - return top && dialect === "postgres" ? formatPostgresInterval(micros) : formatDuration(micros); + if (!top) return formatDuration(micros); + if (dialect === "postgres") return formatPostgresInterval(micros); + if (dialect === "sqlite" || dialect === "mysql") return durationToStoredMicros(micros); + return formatDuration(micros); }); } diff --git a/server/typescript/packages/runtime-ts/test/duration-wire-vectors.test.ts b/server/typescript/packages/runtime-ts/test/duration-wire-vectors.test.ts index 5e039f6115..7895f08211 100644 --- a/server/typescript/packages/runtime-ts/test/duration-wire-vectors.test.ts +++ b/server/typescript/packages/runtime-ts/test/duration-wire-vectors.test.ts @@ -7,7 +7,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { canonicalDuration, durationToWire, formatDuration, formatPostgresInterval, parseDurationInput, - parseDurationLiteral, parsePostgresInterval, DURATION_RE, + parseDurationLiteral, parsePostgresInterval, durationToStoredMicros, DURATION_RE, } from "../src/duration-wire.js"; interface Vectors { @@ -16,6 +16,7 @@ interface Vectors { postgres: Array<{ in: string; out: string }>; postgresRefused: string[]; postgresText: Array<{ in: string; out: string }>; + storedMicros: Array<{ in: string; out: string }>; } const vectors = JSON.parse( readFileSync(join(import.meta.dir, "..", "..", "..", "..", "..", "fixtures", "duration-wire", "vectors.json"), "utf8"), @@ -61,6 +62,22 @@ describe("duration wire vectors (production helpers)", () => { }); } + for (const v of vectors.storedMicros) { + test(`stored micros of ${v.in} -> ${v.out}`, () => { + expect(String(durationToStoredMicros(parseDurationLiteral(v.in)!))).toBe(v.out); + // a driver may return the integer as a number, a bigint or a digit string + expect(durationToWire(BigInt(v.out))).toBe(v.in); + expect(durationToWire(v.out)).toBe(v.in); + if (Number.isSafeInteger(Number(v.out))) expect(durationToWire(Number(v.out))).toBe(v.in); + }); + } + + test("past the 64-bit microsecond column, binding to it is refused (and only there)", () => { + const huge = parseDurationLiteral("PT2562047789H")!; + expect(() => durationToStoredMicros(huge)).toThrow(/64-bit microsecond column/); + expect(formatDuration(huge)).toBe("PT2562047789H"); + }); + test("a node-postgres interval object reads as its canonical form", () => { expect(durationToWire({ hours: 1, minutes: 30 })).toBe("PT1H30M"); expect(durationToWire({ days: 1, hours: 2, seconds: 1, milliseconds: 500.001 })).toBe("PT26H1.500001S"); @@ -68,8 +85,10 @@ describe("duration wire vectors (production helpers)", () => { expect(() => durationToWire({ months: 1 })).toThrow(/year or month/); }); - test("a non-string, non-interval value is not a duration", () => { + test("a number is not a duration a caller can send; read back from an integer column it is microseconds", () => { expect(parseDurationInput(90)).toBeUndefined(); - expect(() => durationToWire(90)).toThrow(); + expect(durationToWire(90)).toBe("PT0.00009S"); + expect(() => durationToWire(1.5)).toThrow(); + expect(() => durationToWire(true)).toThrow(); }); }); diff --git a/server/typescript/packages/runtime-ts/test/object-manager-duration.test.ts b/server/typescript/packages/runtime-ts/test/object-manager-duration.test.ts index 4bc13e2ed4..a176fda52d 100644 --- a/server/typescript/packages/runtime-ts/test/object-manager-duration.test.ts +++ b/server/typescript/packages/runtime-ts/test/object-manager-duration.test.ts @@ -1,7 +1,7 @@ -// field.duration through the ObjectManager: a value is written and read in the canonical ISO-8601 -// form (fixtures/duration-wire), a duration inside a jsonb value object is canonical too, and a -// filter operand is spelled the way the column stores it — so `PT90M` finds a stored `PT1H30M` -// on a text column. Postgres (which refuses a signed ISO-8601 duration as interval input) is +// field.duration through the ObjectManager: a value is read in the canonical ISO-8601 form +// (fixtures/duration-wire); on SQLite the column stores the microsecond integer, so sorting, range +// filters and equality follow the span; a duration inside a jsonb value object is the canonical +// string; and a filter operand is in the form the column stores. Postgres (which refuses a signed ISO-8601 duration as interval input) is // covered live by the persistence-conformance roundtrip-all-types scenario. import { test, expect } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; @@ -38,7 +38,7 @@ async function withSqlite(fn: (om: ObjectManager, db: Kysely const dir = mkdtempSync(join(tmpdir(), "om-duration-")); const db = new Kysely>({ dialect: new LibsqlDialect({ url: `file:${join(dir, "t.db")}` }) }); try { - await sql.raw("CREATE TABLE jobs (id INTEGER PRIMARY KEY AUTOINCREMENT, wait TEXT, policy TEXT)").execute(db); + await sql.raw("CREATE TABLE jobs (id INTEGER PRIMARY KEY AUTOINCREMENT, wait INTEGER, policy TEXT)").execute(db); await fn(new ObjectManager({ metadata: await durationRoot(), driver: kyselyDriver({ db, dialect: "sqlite" }) }), db); } finally { await db.destroy(); @@ -46,24 +46,30 @@ async function withSqlite(fn: (om: ObjectManager, db: Kysely } } -test("SQLite: a duration and a duration inside a jsonb value object are stored and read canonical", async () => { +test("SQLite: a duration is stored as microseconds; one inside a jsonb value object as the canonical string", async () => { await withSqlite(async (om, db) => { const created = await om.create("Job", { wait: "PT90M", policy: { timeout: "P1D", steps: ["PT60S", "-PT90S"] } }); expect(created.wait).toBe("PT1H30M"); expect(created.policy).toEqual({ timeout: "PT24H", steps: ["PT1M", "-PT1M30S"] }); const stored = (await sql.raw("SELECT wait, policy FROM jobs").execute(db)).rows[0] as Record; - expect(stored["wait"]).toBe("PT1H30M"); + expect(Number(stored["wait"])).toBe(5_400_000_000); expect(JSON.parse(stored["policy"]!)).toEqual({ timeout: "PT24H", steps: ["PT1M", "-PT1M30S"] }); }); }); -test("SQLite: a filter operand is canonicalised, so equal spans match", async () => { +test("SQLite: equality, range filters and sort follow the span", async () => { await withSqlite(async (om) => { await om.create("Job", { wait: "PT1H30M" }); await om.create("Job", { wait: "-PT1M30S" }); expect((await om.findMany("Job", { wait: "PT90M" })).map((r) => r.wait)).toEqual(["PT1H30M"]); expect((await om.findMany("Job", { wait: { $in: ["-PT90S", "PT5400S"] } })).length).toBe(2); expect(await om.count("Job", { wait: { $ne: "P0D" } })).toBe(2); + await om.create("Job", { wait: "PT9S" }); + await om.create("Job", { wait: "PT10S" }); + expect((await om.findMany("Job", { wait: { $gt: "PT9S" } }, { orderBy: ["wait", "asc"] })).map((r) => r.wait)) + .toEqual(["PT10S", "PT1H30M"]); + expect((await om.findMany("Job", {}, { orderBy: ["wait", "asc"] })).map((r) => r.wait)) + .toEqual(["-PT1M30S", "PT9S", "PT10S", "PT1H30M"]); await expect(om.findMany("Job", { wait: "P1M" })).rejects.toThrow(/not an ISO-8601 duration/); }); }); @@ -72,4 +78,6 @@ test("a filter operand on Postgres is the interval spelling, never a signed ISO const root = await durationRoot(); const spec = buildSelectSpec(root.findObject("Job")!, { wait: "-PT90S" }, {}, undefined, undefined, "postgres"); expect(spec.where).toEqual({ kind: "eq", column: "wait", value: "-00:01:30" }); + const sqlite = buildSelectSpec(root.findObject("Job")!, { wait: "-PT90S" }, {}, undefined, undefined, "sqlite"); + expect(sqlite.where).toEqual({ kind: "eq", column: "wait", value: -90_000_000 }); }); diff --git a/server/typescript/packages/test-generators/src/templates/duration-wire-helper.ts b/server/typescript/packages/test-generators/src/templates/duration-wire-helper.ts index 77267db3f7..a000f6de0e 100644 --- a/server/typescript/packages/test-generators/src/templates/duration-wire-helper.ts +++ b/server/typescript/packages/test-generators/src/templates/duration-wire-helper.ts @@ -6,8 +6,12 @@ // // Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left // out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. -// The emitted code holds a span as whole seconds plus microseconds (two JS numbers of one sign), -// so it needs no bigint and is exact for any span below 2^53 seconds. +// +// The emitted code counts a span in microseconds as a `bigint`, so it has no limit of its own: a +// span is as long as the stack it is stored in allows. The only limit here is a column's — the +// 64-bit integer a SQLite, D1 or MySQL column holds (refused past it, never wrapped). Postgres's +// interval has its own range, which Postgres enforces. The emitted code calls `BigInt(...)` and +// writes no bigint literal, so it needs the ES2020 `BigInt` global and nothing newer. import { code, imp, type Code } from "@metaobjectsdev/codegen-ts/engine"; import { DURATION_PATTERN } from "@metaobjectsdev/metadata"; @@ -23,67 +27,82 @@ export const ZOD_DURATION_EXPR = `z.string().regex(${DURATION_REGEX_LITERAL})`; export const DURATION_WRITE_HELPER = "durationWrite"; /** The Zod expression of a duration WRITE field: the accepted form, rewritten to the canonical one, - * so equal spans are stored as equal strings on every dialect. */ + * so equal spans are equal strings on the wire and in a jsonb value object. */ export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; -/** The largest span a field.duration holds, in whole seconds: 256204778 hours, the largest whole - * hour a .NET TimeSpan holds (fixtures/duration-wire). Every port refuses one microsecond more, so - * a value one port accepts every port can read. It also bounds the emitted arithmetic: 9.2e11 - * seconds is far below 2^53, so seconds and microseconds stay exact JS integers and never format - * in exponent notation. */ -export const DURATION_MAX_SECONDS = 256204778 * 3600; - /** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ -const ISO_PARTS_SOURCE = "/^([-+])?P(?!$)(?:(\\d+)D)?(?:T(?=\\d)(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)(?:\\.(\\d{1,9}))?S)?)?$/"; +const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$/`; + +/** The default (`IntervalStyle = postgres`) text of a Postgres interval: signed year / mon / day + * parts, then an optionally signed `H:MM:SS[.ffffff]`. */ +const PG_INTERVAL_SOURCE = String.raw`/^(?:([-+]?\d+) years? ?)?(?:([-+]?\d+) mons? ?)?(?:([-+]?\d+) days? ?)?(?:([-+])?(\d+):(\d{2}):(\d{2})(?:\.(\d{1,6}))?)?$/`; + +/** Indent every line of `block` by `n` spaces (blank lines stay blank). */ +function indent(block: string, n: number): string { + const pad = " ".repeat(n); + return block.split("\n").map((l) => (l === "" ? l : pad + l)).join("\n"); +} + +/** Microsecond unit constants, as `BigInt(...)` calls (no bigint literal). */ +const UNIT_LINES = [ + "const ZERO = BigInt(0);", + "const SECOND = BigInt(1000000);", + "const MINUTE = BigInt(60000000);", + "const HOUR = BigInt(3600000000);", + "const DAY = BigInt(86400000000);", +].join("\n"); -/** Lines formatting a span of `s` whole seconds plus `us` microseconds (one sign) canonically. */ -const ISO_FORMAT_LINES = [ - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - " const h = Math.floor(a / 3600);", - " const m = Math.floor((a % 3600) / 60);", - " const sec = a % 60;", +/** `parseIso(text)`: the microseconds of an accepted ISO-8601 duration, or undefined. */ +const PARSE_ISO_FN = [ + "const parseIso = (text: string): bigint | undefined => {", + ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, + " if (p === null) return undefined;", + " const mag = BigInt(p[2] ?? 0) * DAY + BigInt(p[3] ?? 0) * HOUR + BigInt(p[4] ?? 0) * MINUTE", + ' + BigInt(p[5] ?? 0) * SECOND + BigInt((p[6] ?? "").padEnd(6, "0").slice(0, 6));', + ' return p[1] === "-" ? -mag : mag;', + "};", +].join("\n"); + +/** `isoText(micros)`: the canonical wire form. */ +const ISO_TEXT_FN = [ + "const isoText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + " const s = rest / SECOND;", + " const f = rest % SECOND;", ' let out = "PT";', - ' if (h > 0) out += h + "H";', - ' if (m > 0) out += m + "M";', - ' if (sec > 0 || f > 0) out += sec + (f > 0 ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', + ' if (h > ZERO) out += String(h) + "H";', + ' if (m > ZERO) out += String(m) + "M";', + ' if (s > ZERO || f > ZERO) out += String(s) + (f > ZERO ? "." + String(f).padStart(6, "0").replace(/0+$/, "") : "") + "S";', ' if (out === "PT") return "PT0S";', ' return neg ? "-" + out : out;', -]; - -/** Lines matching `text` against the accepted form: `p` (null when it is not one), then `mag` whole - * seconds and `frac` microseconds of the span's magnitude. Read only after a null check on `p`. */ -const ISO_MATCH_LINES = [ - ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, - " const mag = p === null ? 0 : Number(p[2] ?? 0) * 86400 + Number(p[3] ?? 0) * 3600 + Number(p[4] ?? 0) * 60 + Number(p[5] ?? 0);", - ' const frac = p === null ? 0 : Number((p[6] ?? "").padEnd(6, "0").slice(0, 6));', -]; + "};", +].join("\n"); export const DURATION_WRITE_HELPER_DECL = [ "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", - " * fractional digits (truncated), one leading \"-\" for a negative span. A span past 256204778 hours", - " * (the bound every port holds) is a validation issue. Generated. */", - `function ${DURATION_WRITE_HELPER}(text: string, ctx: z.RefinementCtx): string {`, - ...ISO_MATCH_LINES, - " if (p === null) return text;", - ` if (mag > ${DURATION_MAX_SECONDS} || (mag === ${DURATION_MAX_SECONDS} && frac > 0)) {`, - ' ctx.addIssue({ code: "custom", message: "Duration out of range: at most 256204778 hours" });', - " return z.NEVER;", - " }", - ' const s = p[1] === "-" ? -mag : mag;', - ' const us = p[1] === "-" ? -frac : frac;', - ...ISO_FORMAT_LINES, + " * fractional digits (truncated), one leading \"-\" for a negative span. Counted in bigint", + " * microseconds, so any length is exact. Generated. */", + `function ${DURATION_WRITE_HELPER}(text: string): string {`, + indent(UNIT_LINES, 2), + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + " const micros = parseIso(text);", + " return micros === undefined ? text : isoText(micros);", "}", ].join("\n"); /** The physical column type a duration column's `customType` declares, per dialect: the - * Postgres-native interval; TEXT on SQLite; VARCHAR(64) on MySQL (the persistence corpus's - * canonical schemas, and what `meta migrate` writes). */ + * Postgres-native interval; a 64-bit integer count of microseconds on SQLite / D1 (INTEGER) and + * MySQL (BIGINT) — the persistence corpus's canonical schemas, and what `meta migrate` writes. */ export function durationColumnDataType(dialect: Dialect): string { - return dialect === "postgres" ? "interval" : dialect === "mysql" ? "varchar(64)" : "text"; + return dialect === "postgres" ? "interval" : dialect === "mysql" ? "bigint" : "integer"; } /** @@ -92,92 +111,87 @@ export function durationColumnDataType(dialect: Dialect): string { * declaration. Exported so a test can evaluate the exact text a generated module carries. * * - `toDriver` binds what the column holds: on Postgres the interval spelling `[-]HH:MM:SS[.f]` - * (Postgres refuses a signed ISO-8601 duration as interval input, and returns a value written - * this way in exactly this spelling); on SQLite and MySQL the canonical ISO-8601 string, so equal - * spans are equal strings. It takes the value in either spelling — an ISO-8601 duration (what the - * generated write schema hands it), or the Postgres interval text runtime-ts already binds a - * filter operand or a write in — and throws for anything else. - * - `fromDriver` reads what the driver returns — ISO-8601 text, Postgres interval text in the - * default `IntervalStyle`, or a node-postgres interval object — as the canonical ISO-8601 form. - * An interval with a year or month part is not a fixed-length span: reading one throws. + * (Postgres refuses a signed ISO-8601 duration, and returns a value written this way in exactly + * this spelling); on SQLite, D1 and MySQL the microsecond count — a number when it is a safe + * integer, else a bigint — refused past the 64-bit range, which is that column's limit. It takes + * the value as an ISO-8601 duration (what the generated write schema hands it), or as what + * runtime-ts already binds a filter operand in (the Postgres text; the microsecond integer), and + * throws for anything else. + * - `fromDriver` reads what the driver returns — the microsecond integer (a number, a bigint or a + * digit string), ISO-8601 text, Postgres interval text in the default `IntervalStyle`, or a + * node-postgres interval object — as the canonical ISO-8601 form. An interval with a year or + * month part is not a fixed-length span: reading one throws. */ export function durationColumnDeclParts(dialect: Dialect): [string, string] { - const bindPostgres = dialect === "postgres"; + const postgres = dialect === "postgres"; const before = [ - "/** A field.duration column. Binds " + (bindPostgres - ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration)," - : "the canonical ISO-8601 duration,"), - " * reads any interval back as the canonical ISO-8601 duration, and refuses an interval with a", - " * year or month part. Generated. */", + "/** A field.duration column. Binds " + (postgres + ? "the Postgres interval spelling [-]HH:MM:SS[.f] (Postgres refuses a signed ISO-8601 duration);" + : "the span as a 64-bit integer count of microseconds (refused past that range);"), + " * reads it back as the canonical ISO-8601 duration, and refuses an interval with a year or month", + " * part. Counted in bigint microseconds, so the column is the only limit. Generated. */", `const ${DURATION_COLUMN_FN} = (() => {`, - " const MICROS = 1000000;", - ` const MAX_SECONDS = ${DURATION_MAX_SECONDS};`, - " // A span normalised to one sign, refused past 256204778 hours (the bound every port holds).", - " const span = (s: number, us: number): [number, number] => {", - " s += Math.trunc(us / MICROS);", - " us %= MICROS;", - " if (s > 0 && us < 0) {", - " s -= 1;", - " us += MICROS;", - " } else if (s < 0 && us > 0) {", - " s += 1;", - " us -= MICROS;", - " }", - " const a = Math.abs(s);", - " if (!(a < MAX_SECONDS || (a === MAX_SECONDS && us === 0))) {", - ' throw new Error("a field.duration holds at most 256204778 hours (one microsecond more is refused)");', - " }", - " return [s, us];", - " };", - " const iso = (text: string): [number, number] | undefined => {", - ...ISO_MATCH_LINES.map((l) => " " + l), - " if (p === null) return undefined;", - ' return p[1] === "-" ? [-mag, -frac] : [mag, frac];', - " };", - " const isoText = ([s, us]: [number, number]): string => {", - ...ISO_FORMAT_LINES.map((l) => " " + l), - " };", - " const pgText = ([s, us]: [number, number]): string => {", - " const neg = s < 0 || us < 0;", - " const a = Math.abs(s);", - " const f = Math.abs(us);", - ' const two = (n: number): string => String(n).padStart(2, "0");', - ' let out = two(Math.floor(a / 3600)) + ":" + two(Math.floor((a % 3600) / 60)) + ":" + two(a % 60);', - ' if (f > 0) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', - ' return neg ? "-" + out : out;', - " };", - " const notFixed = (v: unknown): Error =>", - ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', - " const read = (v: unknown): [number, number] => {", - ' if (typeof v === "string") {', - " const fromIso = iso(v);", - " if (fromIso !== undefined) return span(fromIso[0], fromIso[1]);", - " const p = v.length === 0 ? null", - " : /^(?:([-+]?\\d+) years? ?)?(?:([-+]?\\d+) mons? ?)?(?:([-+]?\\d+) days? ?)?(?:([-+])?(\\d+):(\\d{2}):(\\d{2})(?:\\.(\\d{1,6}))?)?$/.exec(v);", - ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', - " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", - ' const t = p[5] === undefined ? 0 : Number(p[5]) * 3600 + Number(p[6]) * 60 + Number(p[7]);', - ' const tu = Number((p[8] ?? "").padEnd(6, "0"));', - ' const sign = p[4] === "-" ? -1 : 1;', - " return span(Number(p[3] ?? 0) * 86400 + sign * t, sign * tu);", - " }", - ' if (v !== null && typeof v === "object") {', - " const o = v as Record;", - " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", - " const whole = (n: number | undefined): number => Math.trunc(n ?? 0);", - " return span(", - " whole(o.days) * 86400 + whole(o.hours) * 3600 + whole(o.minutes) * 60 + whole(o.seconds),", - " Math.round((o.milliseconds ?? 0) * 1000),", - " );", - " }", - ' throw new Error("not a field.duration value: " + JSON.stringify(v));', - " };", + indent(UNIT_LINES, 2), + ` const INT64_MAX = BigInt("9223372036854775807");`, + indent(PARSE_ISO_FN, 2), + indent(ISO_TEXT_FN, 2), + indent([ + "const pgText = (micros: bigint): string => {", + " const neg = micros < ZERO;", + " let rest = neg ? -micros : micros;", + ' const two = (n: bigint): string => String(n).padStart(2, "0");', + " const h = rest / HOUR;", + " rest %= HOUR;", + " const m = rest / MINUTE;", + " rest %= MINUTE;", + ' let out = two(h) + ":" + two(m) + ":" + two(rest / SECOND);', + " const f = rest % SECOND;", + ' if (f > ZERO) out += "." + String(f).padStart(6, "0").replace(/0+$/, "");', + ' return neg ? "-" + out : out;', + "};", + "const stored = (micros: bigint): number | bigint => {", + " if (micros > INT64_MAX || micros < -INT64_MAX - BigInt(1)) {", + ' throw new Error("the span " + isoText(micros) + " does not fit the 64-bit microsecond column a field.duration is stored in");', + " }", + " const n = Number(micros);", + " return Number.isSafeInteger(n) ? n : micros;", + "};", + "const notFixed = (v: unknown): Error =>", + ' new Error("the interval " + JSON.stringify(v) + " has a year or month part, so it is not a fixed-length field.duration");', + "const read = (v: unknown): bigint => {", + ' if (typeof v === "bigint") return v;', + ' if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);', + ' if (typeof v === "string") {', + " if (/^-?\\d+$/.test(v)) return BigInt(v);", + " const iso = parseIso(v);", + " if (iso !== undefined) return iso;", + ` const p = v.length === 0 ? null : ${PG_INTERVAL_SOURCE}.exec(v);`, + ' if (p === null) throw new Error("not a field.duration value: " + JSON.stringify(v));', + " if (Number(p[1] ?? 0) !== 0 || Number(p[2] ?? 0) !== 0) throw notFixed(v);", + " let time = ZERO;", + " if (p[5] !== undefined) {", + ' time = BigInt(p[5]) * HOUR + BigInt(p[6] ?? 0) * MINUTE + BigInt(p[7] ?? 0) * SECOND + BigInt((p[8] ?? "").padEnd(6, "0"));', + ' if (p[4] === "-") time = -time;', + " }", + " return BigInt(p[3] ?? 0) * DAY + time;", + " }", + ' if (v !== null && typeof v === "object") {', + " const o = v as Record;", + " if ((o.years ?? 0) !== 0 || (o.months ?? 0) !== 0) throw notFixed(v);", + " const whole = (n: number | undefined): bigint => BigInt(Math.trunc(n ?? 0));", + " // postgres-interval carries microseconds as a fractional millisecond count.", + " return whole(o.days) * DAY + whole(o.hours) * HOUR + whole(o.minutes) * MINUTE + whole(o.seconds) * SECOND", + " + BigInt(Math.round((o.milliseconds ?? 0) * 1000));", + " }", + ' throw new Error("not a field.duration value: " + JSON.stringify(v));', + "};", + ].join("\n"), 2), " return ", ].join("\n"); const after = [ - "<{ data: string; driverData: string }>({", + `<{ data: string; driverData: ${postgres ? "string" : "number | bigint | string"} }>({`, ` dataType: () => ${JSON.stringify(durationColumnDataType(dialect))},`, - ` toDriver: (value) => ${bindPostgres ? "pgText" : "isoText"}(read(value)),`, + ` toDriver: (value) => ${postgres ? "pgText" : "stored"}(read(value)),`, " fromDriver: (value) => isoText(read(value)),", " });", "})();", diff --git a/server/typescript/packages/test-generators/src/templates/zod-validators.ts b/server/typescript/packages/test-generators/src/templates/zod-validators.ts index 1edf2ab40b..82c061b07c 100644 --- a/server/typescript/packages/test-generators/src/templates/zod-validators.ts +++ b/server/typescript/packages/test-generators/src/templates/zod-validators.ts @@ -775,8 +775,8 @@ function zodFieldExpr( case FIELD_SUBTYPE_DURATION: // An ISO-8601 duration (days, hours, minutes, seconds; no years, months or weeks). A WRITE // shape rewrites it to the canonical form (duration-wire-helper.ts), so equal spans are - // equal strings in a text column and in a jsonb value object; the TPH read shape parses - // rows the column codec has already put in that form. + // equal strings on the wire and in a jsonb value object (the column codec binds the + // column's own form); the TPH read shape parses rows the codec has already put in it. if (readShape) { baseStr = ZOD_DURATION_EXPR; break; diff --git a/site-reference/index.html b/site-reference/index.html index 3d439c678a..5913b9d91b 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -157,7 +157,7 @@
    field.durationA fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type, text elsewhere. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. types/field.md#fieldduration
    _pkey` records their names (not compared; nothing churns). See `docs/features/migrations-and-drift.md`, "Schema conventions". +- **`migrate.checks.skipRedundant`: leave out the CHECKs a column type already enforces.** Set in + `.metaobjects/config.json` (default `false`), `meta migrate` and `meta verify --db` leave out a + `validator.length` maximum the column's `VARCHAR(n)` enforces (not on SQLite or D1, which do not + enforce one) and a length minimum of 0 or less, for a database whose CHECKs were written by hand + only where the column type does not already enforce the rule. A validator with a declared + `@constraintName` keeps its CHECK. A malformed `checks` block is refused when the config loads. + See `docs/features/migrations-and-drift.md`, "CHECKs from validators". - **A recipe for checking an API change against the last release.** Emit the document at the last tag and at `HEAD`, then run oasdiff. See `docs/recipes/check-api-against-last-release.md`. - **A `pydantic` extra on the Python package.** `pip install "metaobjects[pydantic]"` installs diff --git a/agent-context/skills/metaobjects-authoring/SKILL.md b/agent-context/skills/metaobjects-authoring/SKILL.md index 479ef57fb9..df2eadc0ff 100644 --- a/agent-context/skills/metaobjects-authoring/SKILL.md +++ b/agent-context/skills/metaobjects-authoring/SKILL.md @@ -448,7 +448,7 @@ that becomes a CHECK takes an optional db-provider `@constraintName` naming it. { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } -{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 3b52efc789..b9a1de8b3b 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -38,7 +38,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 59 (53 query + 6 migration) | all 59; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 53 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | | [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 119 (31 core + 10 tph + 9 m2m + 5 jsonb + 2 write-through + 2 secret-fields + 12 projection + 37 report + 11 decimal) | ✓ (Fastify reference + generated lane); `report/` and `decimal/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/` and `decimal/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/` and `decimal/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/` and `decimal/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/` and `decimal/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | -| [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file (parse, refused, Postgres text read and write) | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | +| [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | | [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/object-model-conformance/`](../fixtures/object-model-conformance/) | 1 shared metadata fixture (per-port scenarios) | ✓ | ✓ | ✓ | ✓ | ✓ | @@ -59,7 +59,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 26 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`) | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | -| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | ✓ | +| [`fixtures/enum-length-conformance/`](../fixtures/enum-length-conformance/) (a string-stored enum's column length: `@maxLength`, else `enums.maxLength`) | 5 cases + 1 overflow + 5 refusals; run by a port that sizes the column | ✓ | ✓ | inherits via Java (one config reader, one resolver) | ✓ | — (sizes no column: emits no DDL or column type; the config reader accepts and shape-checks the `enums` block) | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (FR-044 — reporting vocabulary: what is lowered, what stays inert) | 1 model pair (`reporting/with` vs `reporting/without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | | [`fixtures/contract-conformance/`](../fixtures/contract-conformance/) (FR-022 — the `contract-schema` and `openapi` generators' golden trees and refusals) | 19 cases (14 trees + 5 errors) | ✓ (one neutral engine, ADR-0034 Amendment 10; the generated API lanes also hold real traffic to the documents) | — | — | — | — | diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 428aee977b..5c21db1bbf 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -52,10 +52,12 @@ Five rows need a footnote: - **`field.duration`** is a fixed-length span: days, hours, minutes and seconds. A calendar span ("every 3 months") is not one, because a month has no fixed length: model it as an int and a unit. On the wire it is an ISO-8601 duration. Every port writes one canonical form, - `[-]PT[nH][nM][n[.f]S]`: hours are never folded into days (`PT26H`), there are at most six - fractional digits, and zero is `PT0S`. Every port reads that form and also a leading day - count (`P1DT2H`). Years, months and weeks are refused, and so are lowercase designators and - fractional hours. The column is a Postgres `interval`; SQLite, D1 and MySQL store a 64-bit + `[-]PT[nH][nM][n[.f]S]`: hours are never folded into days (`PT26H`), and zero is `PT0S`. A + port writes as many fractional digits as its own type holds (6 in TypeScript and Python, 7 in + C#, 9 in Java and Kotlin) and truncates a longer fraction toward zero; a Postgres `interval` and + the integer column below both hold microseconds. Every port reads that form and also leading + week and day counts (`P1W` is 7 days, `P1DT2H` is 26 hours). Years and months are refused, and + so are lowercase designators and fractional hours. The column is a Postgres `interval`; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, the way Django stores a `DurationField` outside Postgres. Both order and compare as the span does, so every filter operator a number has (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `isNull`) and `sort` work on every database. There is no shared upper @@ -127,7 +129,7 @@ database calls it. `@column` sets the second. It never changes the first. With no `@column`, the physical name comes from the project's **column rule**: `snake_case` (the default), `literal` (the field name verbatim), `kebab-case` or -`PascalCase` (the first letter upper-cased, the rest verbatim: EF Core's names). That +`upperFirst` (the first letter upper-cased, the rest verbatim). That is CONFIG, not metadata, on purpose: the same model has to be able to drive a snake_case Postgres schema and a literal-column one. It is ONE setting for the whole project, `naming` in `.metaobjects/config.json` (ADR-0058): @@ -310,7 +312,7 @@ For `flattened`, the generated table gets `address_street`, `address_city`, Each member's column is a **prefix** followed by the member's own column (its `@column`, else its name under the project's column rule). The prefix defaults to the embedding field's column -and `_` (`address_`; with `@column: "bill"`, `bill_`; under the `PascalCase` rule, `Address_`, +and `_` (`address_`; with `@column: "bill"`, `bill_`; under the `upperFirst` rule, `Address_`, EF Core's own default). **`@flattenedColumnPrefix`** on the embedding field replaces it, verbatim: diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 51093e41a5..82f17c663c 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -420,13 +420,13 @@ attributes shape it, all database-only (no generated code reads them): membership CHECK. Absent, the name is derived (`
    ___chk`, `
    __chk` for an enum), as before. A declared name is refused (`ERR_CHECK_NAME`) when another constraint on the table already has it, or, on Postgres, when it is over 63 bytes - (Postgres would truncate it, and the CHECK would never match its declaration). Under the - `efcore` conventions, a `validator.length` with a declared name is kept even where the column's - length already enforces it. + (Postgres would truncate it, and the CHECK would never match its declaration). A CHECK with a + declared name is always emitted, even where `migrate.checks.skipRedundant` (below) would leave + it out. - **`@condition`** on a cross-field validator (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) is an expression, in the grammar `origin.computed` uses, over the entity's fields. The rule holds only where the condition does: the CHECK is `(NOT condition) OR (rule)`, with - the negation folded in (`kind = 'Clinic'` becomes `kind <> 'Clinic'`). It is checked at load + the negation folded in (`kind = 'Owned'` becomes `kind <> 'Owned'`). It is checked at load (`ERR_BAD_ATTR_VALUE`): every field it names is a field of the entity, it is a boolean expression, a literal compared with a field is of that field's kind (and, for an enum, one of its `@values`), and no comparison has a `null` literal (`x = NULL` is never true: use `isNull` @@ -441,21 +441,37 @@ attributes shape it, all database-only (no generated code reads them): { "source.rdb": { "@table": "Notes" } }, { "field.long": { "name": "id" } }, { "field.enum": { "name": "kind", "@values": ["Owned", "Shared"], "@constraintName": "CK_Notes_Kind" } }, - { "field.long": { "name": "patientId" } }, - { "field.long": { "name": "caseId" } }, + { "field.long": { "name": "customerId" } }, + { "field.long": { "name": "accountId" } }, { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } }, - { "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1, + { "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1, "@constraintName": "CK_Notes_Owner", "@condition": { "op": "eq", "left": { "field": "kind" }, "right": { "value": "Owned" } } } } ] } } ``` -On Postgres the last one is `CK_Notes_Owner CHECK (("kind" <> 'Owned') OR (num_nonnulls("patient_id", "case_id") = 1))`. +On Postgres the last one is `CK_Notes_Owner CHECK (("kind" <> 'Owned') OR (num_nonnulls("customer_id", "account_id") = 1))`. Renaming a CHECK this way is a drop and an add of the same rule on Postgres, under `--allow drop-check`. On SQLite and D1 a CHECK is matched by its expression when the name does not match, so a rename alone proposes nothing and the database keeps the old name. +**Leaving out the CHECKs a column type already enforces.** By default every validator that has +a SQL form becomes a CHECK, including one the column already guarantees. For a database whose +CHECKs were written by hand only where the column type does not already enforce the rule, set: + +```json +{ "schema_version": 1, "migrate": { "checks": { "skipRedundant": true } } } +``` + +`meta migrate` and `meta verify --db` then leave out a `validator.length` maximum the column's +`VARCHAR(n)` enforces (n at most the maximum; not on SQLite or D1, which store a longer value in a +`VARCHAR(n)` column anyway) and a length minimum of 0 or less; the rest of the validator's CHECK +stands. A validator with a declared `@constraintName` keeps its CHECK whole: an explicit +declaration beats a project default, as a declared name beats a convention. Default `false`. A +`checks` that is not an object, a key other than `skipRedundant`, or a non-boolean value is +refused when the config loads. + ## Schema conventions: names for objects no code addresses Some database objects have names that no program ever reads: a primary-key constraint, most @@ -472,10 +488,10 @@ come from the project's **schema conventions**, selected in `.metaobjects/config | Foreign-key constraint name | `
    __fk` | `FK_
    __` | | Index on a foreign key | none | `IX_
    _`, unless the primary key or another index (a partial one included) already starts with the FK's columns; an FK index another FK index covers is dropped, so FK order does not matter | | Unique key (`identity.secondary`, a `@unique` field) | a unique index | a UNIQUE constraint when a foreign key references it, else a unique index | -| A CHECK the column type already guarantees (`skipRedundantChecks`) | emitted | left out: a `validator.length` maximum the column's `VARCHAR(n)` enforces (not on SQLite or D1, which do not enforce a declared length), and a minimum of 0 or less | -`efcore` follows EF Core's own conventions on PostgreSQL (Npgsql), including its truncation of a -name longer than 63 characters to 62 characters and `~`. A database first built by EF Core +`efcore` follows EF Core's own conventions, including, on PostgreSQL (Npgsql), its truncation of a +name longer than 63 characters to 62 characters and `~`. EF Core's SQLite provider truncates +nothing, so on SQLite and D1 neither does `efcore`. A database first built by EF Core migrations and one built by `meta migrate` then agree on these objects. Where the EF Core model carried something its conventions do not (a hand-named key, an index dropped by raw SQL), declare it in metadata. A unique key keeps the name its metadata node declares (EF Core would call an @@ -507,7 +523,10 @@ export default defineConfig({ definition is unchanged and whose name differs is renamed in place (`RENAME CONSTRAINT` / `ALTER INDEX … RENAME`), never dropped and re-created; new FK indexes are created. The PK name and whether a unique key is a constraint or an index are not compared by the diff, so they only -shape what migrate creates. SQLite cannot rename a constraint and rebuilds the table instead. +shape what migrate creates: after a switch, an existing primary key keeps its old name, and +neither `meta migrate` nor `meta verify` reports it. Rename one by hand if you want the new +name (`ALTER TABLE "t" RENAME CONSTRAINT "t_pkey" TO "PK_t"` on Postgres). SQLite cannot rename +a constraint and rebuilds the table instead. ## How CHECK constraints and expression indexes are compared diff --git a/docs/features/migrations/physical-naming.md b/docs/features/migrations/physical-naming.md index d8406c1cc8..e5576c84f0 100644 --- a/docs/features/migrations/physical-naming.md +++ b/docs/features/migrations/physical-naming.md @@ -25,16 +25,17 @@ every runtime `ObjectManager` and `verify` read it, so they always produce the s | Key | Values | Applies to | Default | |---|---|---|---| -| `columns` | `snake_case`, `literal`, `kebab-case`, `PascalCase` | a field with no `@column` | `snake_case` | +| `columns` | `snake_case`, `literal`, `kebab-case`, `upperFirst` | a field with no `@column` | `snake_case` | | `tables` | `snake_case`, `literal` | a source with no `@table`/`@view`/`@proc`/`@function`: its `name`, else the object's name made plural | `snake_case` | An unknown key or value fails when the file is read. Index and constraint names are unchanged. -`PascalCase` upper-cases the field name's first letter and changes nothing -else: `createdAt` becomes `CreatedAt` and `requestURL` becomes `RequestURL`. It is the column -EF Core creates for a property, so a camelCase model over an EF-built schema needs `@column` -only where the database spells a name differently (an acronym the field writes in lower case, -for example). It is a column rule only; `literal` tables already keep a PascalCase object name. +`upperFirst` upper-cases the field name's first letter and changes nothing +else: `createdAt` becomes `CreatedAt`, `requestURL` becomes `RequestURL` and `address_line1` +becomes `Address_line1`. It is not a word split, so it is not PascalCase. A schema whose columns +are the field names with a capital first letter (EF Core's default, for one) then needs `@column` +only where the database spells a name differently. It is a column rule only; `literal` tables +already keep an object name verbatim. **Upgrade every port of an estate together.** A 1.0.x TypeScript tool refuses the new `naming` key, but a 1.0.x C#, Java or Python tool ignores an unknown top-level key silently and keeps the old diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index eca44ae267..8a72b39566 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -369,13 +369,21 @@ attributes or delete `DecimalWire.g.cs` to change the output: they also check in and regenerate. A `field.duration` is a `TimeSpan` carrying `[DurationWire.Iso]`, which reads and writes the -ISO-8601 form every port shares (`PT1H30M`) instead of System.Text.Json's `01:30:00`. On Npgsql it -is an `interval` column. EF reads an interval through Npgsql's own `TimeSpan` conversion, which (as -of Npgsql 8.0.5) silently drops a negative month or year part (`'-1 mons'` reads as `PT0S`) and -wraps a day count past `TimeSpan`'s range, so the generated context maps each duration column -through `NpgsqlInterval` instead and refuses either one on read. On any other provider a value -converter stores the 64-bit microsecond count, so sorting and range filters follow the span. -`TimeSpan`'s own range is the only limit: a longer span is refused, never wrapped. +ISO-8601 form every port shares (`PT1H30M`, and on input `P1W`, `P2DT3H`) instead of +System.Text.Json's `01:30:00`. It writes up to seven fractional digits, a `TimeSpan` tick, and +truncates a longer input fraction toward zero. On Npgsql it is an `interval` column. EF reads an +interval through Npgsql's own `TimeSpan` conversion, which (as of Npgsql 8.0.5) silently drops a +negative month or year part (`'-1 mons'` reads as `PT0S`) and wraps a day count past `TimeSpan`'s +range, so the generated context maps each duration column through `NpgsqlInterval` instead +(`DurationIntervalMapping`, `DurationIntervalArrayMapping`, emitted beside `AppDbContext`) and +refuses either one on read. LINQ still translates as it does on Npgsql's own mapping: `TimeSpan` +members (`TotalSeconds`, `Hours`, ...), a timestamp plus a duration, comparison, ordering, `Min`, +`Max`, `EF.Functions.Sum`, and `Contains` / `Count` / `Any` on a duration array. A compiled model +(`dotnet ef dbcontext optimize`) keeps the mapping and the refusal; EF Core 8's compiled model +carries no element type, so there a duration array reads and writes but is not queryable as a +collection. On any other provider a value converter stores the 64-bit microsecond count, so sorting +and range filters follow the span. Both columns hold microseconds, so a tick below one is dropped +on write. `TimeSpan`'s own range is the only limit: a longer span is refused, never wrapped. `DurationWire.g.cs` is emitted once per namespace that has a duration, and an owned `routes` generator also copies `DurationWire.cs`. @@ -441,6 +449,11 @@ no port's codegen names a primary key (Postgres migrations hardcode `
    _pke emits an unnamed PK), and carrying that would restate a migrate-only formula in the artifact built to stop exactly that. +A `@storage: flattened` value-object field gets one constant per member column +(`ShipToStreetColumn`, keyed `shipTo.street` in `ColumnsByField`). Its own `ShipToColumn` is still +emitted but `[Obsolete]`: the table has no column by that name. Declaring it raises no warning; +reading it does, so a project that never reads it builds clean under `TreatWarningsAsErrors`. + `const`, not `static readonly`: a `[Table("...")]`/`[Column("...")]` attribute argument must be a compile-time constant, and those two attributes are the whole reason this artifact can replace a literal there rather than sit beside @@ -493,7 +506,9 @@ complete on every class, inherited entries included. Column names come from the project's `naming` setting in `.metaobjects/config.json` (ADR-0058), the one every port reads, default `snake_case` (what `meta migrate` creates). A database whose columns are named exactly like the fields declares -`"naming": { "columns": "literal" }`; through 1.0 that was this port's default. `dotnet meta gen` +`"naming": { "columns": "literal" }`; through 1.0 that was this port's default. One whose columns +are the field names with the first letter upper-cased (`requestURL` → `RequestURL`) declares +`"upperFirst"`. `dotnet meta gen` and `dotnet meta verify --codegen` both read the setting, so a plain run and the drift gate resolve the identical column strings; `--column-naming` is refused ([physical-naming.md](../features/migrations/physical-naming.md)). `verify --codegen` says so diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts index 39ee917ec5..cf8a3f1097 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/filter-value-format.ts @@ -60,7 +60,7 @@ export const FORMAT_EXPECTED: Readonly> = { [FIELD_SUBTYPE_TIMESTAMP]: "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", [FIELD_SUBTYPE_UUID]: "uuid (8-4-4-4-12 hex)", [FIELD_SUBTYPE_DECIMAL]: "decimal number (digits, optional fraction, optional exponent)", - [FIELD_SUBTYPE_DURATION]: "duration (ISO 8601, e.g. PT1H30M; no years, months or weeks)", + [FIELD_SUBTYPE_DURATION]: "duration (ISO 8601, e.g. PT1H30M; no years or months)", }; /** `expected` for a temporal rule that does not say WHICH temporal format it is. */ diff --git a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts index a000f6de0e..81aeaac06e 100644 --- a/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts +++ b/examples/advanced-modeling/codegen/templates/duration-wire-helper.ts @@ -4,8 +4,10 @@ // fixtures/duration-wire/vectors.json (test/duration-wire-helper.test.ts evaluates the text // emitted here against them). // -// Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left -// out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. +// Accepted: optional weeks (exactly 7 days) and days, then hours, minutes and seconds; the seconds +// fraction may have any number of digits. Canonical: `[-]PT[H][M][[.]S]` — hours never +// folded into days, zero components left out, zero is `PT0S`, one leading `-`. A span is counted in +// microseconds, so the fraction keeps six digits and the rest is truncated toward zero. // // The emitted code counts a span in microseconds as a `bigint`, so it has no limit of its own: a // span is as long as the stack it is stored in allows. The only limit here is a column's — the @@ -30,9 +32,9 @@ export const DURATION_WRITE_HELPER = "durationWrite"; * so equal spans are equal strings on the wire and in a jsonb value object. */ export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; -/** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. - * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ -const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$/`; +/** The accepted form with its components captured: sign, weeks, days, hours, minutes, seconds, + * fraction. Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ +const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+))?S)?)?$/`; /** The default (`IntervalStyle = postgres`) text of a Postgres interval: signed year / mon / day * parts, then an optionally signed `H:MM:SS[.ffffff]`. */ @@ -51,6 +53,7 @@ const UNIT_LINES = [ "const MINUTE = BigInt(60000000);", "const HOUR = BigInt(3600000000);", "const DAY = BigInt(86400000000);", + "const WEEK = BigInt(604800000000);", ].join("\n"); /** `parseIso(text)`: the microseconds of an accepted ISO-8601 duration, or undefined. */ @@ -58,8 +61,8 @@ const PARSE_ISO_FN = [ "const parseIso = (text: string): bigint | undefined => {", ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, " if (p === null) return undefined;", - " const mag = BigInt(p[2] ?? 0) * DAY + BigInt(p[3] ?? 0) * HOUR + BigInt(p[4] ?? 0) * MINUTE", - ' + BigInt(p[5] ?? 0) * SECOND + BigInt((p[6] ?? "").padEnd(6, "0").slice(0, 6));', + " const mag = BigInt(p[2] ?? 0) * WEEK + BigInt(p[3] ?? 0) * DAY + BigInt(p[4] ?? 0) * HOUR", + ' + BigInt(p[5] ?? 0) * MINUTE + BigInt(p[6] ?? 0) * SECOND + BigInt((p[7] ?? "").padEnd(6, "0").slice(0, 6));', ' return p[1] === "-" ? -mag : mag;', "};", ].join("\n"); @@ -85,10 +88,10 @@ const ISO_TEXT_FN = [ ].join("\n"); export const DURATION_WRITE_HELPER_DECL = [ - "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", - " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", - " * fractional digits (truncated), one leading \"-\" for a negative span. Counted in bigint", - " * microseconds, so any length is exact. Generated. */", + "/** A field.duration on the wire: an ISO-8601 duration (weeks, days, hours, minutes, seconds) rewritten", + " * to its canonical form — hours never folded into days, zero components left out, zero as PT0S, one", + " * leading \"-\" for a negative span. Counted in bigint microseconds, so any length is exact and a", + " * fraction past six digits is truncated toward zero. Generated. */", `function ${DURATION_WRITE_HELPER}(text: string): string {`, indent(UNIT_LINES, 2), indent(PARSE_ISO_FN, 2), diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts index 82c061b07c..eb07f60afe 100644 --- a/examples/advanced-modeling/codegen/templates/zod-validators.ts +++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts @@ -773,7 +773,7 @@ function zodFieldExpr( baseStr = field.attr(FIELD_ATTR_LENIENT) === true ? "z.string()" : ZOD_INET_EXPR; break; case FIELD_SUBTYPE_DURATION: - // An ISO-8601 duration (days, hours, minutes, seconds; no years, months or weeks). A WRITE + // An ISO-8601 duration (weeks, days, hours, minutes, seconds; no years or months). A WRITE // shape rewrites it to the canonical form (duration-wire-helper.ts), so equal spans are // equal strings on the wire and in a jsonb value object (the column codec binds the // column's own form); the TPH read shape parses rows the codec has already put in it. diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/filter-value-format.ts b/examples/showcase/codegen/runtime/drizzle-fastify/filter-value-format.ts index 39ee917ec5..cf8a3f1097 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/filter-value-format.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/filter-value-format.ts @@ -60,7 +60,7 @@ export const FORMAT_EXPECTED: Readonly> = { [FIELD_SUBTYPE_TIMESTAMP]: "timestamp (YYYY-MM-DD[THH:MM[:SS[.fff]]][Z|±HH:MM])", [FIELD_SUBTYPE_UUID]: "uuid (8-4-4-4-12 hex)", [FIELD_SUBTYPE_DECIMAL]: "decimal number (digits, optional fraction, optional exponent)", - [FIELD_SUBTYPE_DURATION]: "duration (ISO 8601, e.g. PT1H30M; no years, months or weeks)", + [FIELD_SUBTYPE_DURATION]: "duration (ISO 8601, e.g. PT1H30M; no years or months)", }; /** `expected` for a temporal rule that does not say WHICH temporal format it is. */ diff --git a/examples/showcase/codegen/templates/duration-wire-helper.ts b/examples/showcase/codegen/templates/duration-wire-helper.ts index a000f6de0e..81aeaac06e 100644 --- a/examples/showcase/codegen/templates/duration-wire-helper.ts +++ b/examples/showcase/codegen/templates/duration-wire-helper.ts @@ -4,8 +4,10 @@ // fixtures/duration-wire/vectors.json (test/duration-wire-helper.test.ts evaluates the text // emitted here against them). // -// Canonical: `[-]PT[H][M][[.]S]` — hours never folded into days, zero components left -// out, zero is `PT0S`, at most six fractional digits (truncated toward zero), one leading `-`. +// Accepted: optional weeks (exactly 7 days) and days, then hours, minutes and seconds; the seconds +// fraction may have any number of digits. Canonical: `[-]PT[H][M][[.]S]` — hours never +// folded into days, zero components left out, zero is `PT0S`, one leading `-`. A span is counted in +// microseconds, so the fraction keeps six digits and the rest is truncated toward zero. // // The emitted code counts a span in microseconds as a `bigint`, so it has no limit of its own: a // span is as long as the stack it is stored in allows. The only limit here is a column's — the @@ -30,9 +32,9 @@ export const DURATION_WRITE_HELPER = "durationWrite"; * so equal spans are equal strings on the wire and in a jsonb value object. */ export const ZOD_DURATION_WRITE_EXPR = `${ZOD_DURATION_EXPR}.transform(${DURATION_WRITE_HELPER})`; -/** The accepted form with its components captured: sign, days, hours, minutes, seconds, fraction. - * Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ -const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d{1,9}))?S)?)?$/`; +/** The accepted form with its components captured: sign, weeks, days, hours, minutes, seconds, + * fraction. Equivalent to DURATION_PATTERN (the same lookaheads refuse `P`, `PT` and `P1DT`). */ +const ISO_PARTS_SOURCE = String.raw`/^([-+])?P(?!$)(?:(\d+)W)?(?:(\d+)D)?(?:T(?=\d)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)(?:\.(\d+))?S)?)?$/`; /** The default (`IntervalStyle = postgres`) text of a Postgres interval: signed year / mon / day * parts, then an optionally signed `H:MM:SS[.ffffff]`. */ @@ -51,6 +53,7 @@ const UNIT_LINES = [ "const MINUTE = BigInt(60000000);", "const HOUR = BigInt(3600000000);", "const DAY = BigInt(86400000000);", + "const WEEK = BigInt(604800000000);", ].join("\n"); /** `parseIso(text)`: the microseconds of an accepted ISO-8601 duration, or undefined. */ @@ -58,8 +61,8 @@ const PARSE_ISO_FN = [ "const parseIso = (text: string): bigint | undefined => {", ` const p = ${ISO_PARTS_SOURCE}.exec(text);`, " if (p === null) return undefined;", - " const mag = BigInt(p[2] ?? 0) * DAY + BigInt(p[3] ?? 0) * HOUR + BigInt(p[4] ?? 0) * MINUTE", - ' + BigInt(p[5] ?? 0) * SECOND + BigInt((p[6] ?? "").padEnd(6, "0").slice(0, 6));', + " const mag = BigInt(p[2] ?? 0) * WEEK + BigInt(p[3] ?? 0) * DAY + BigInt(p[4] ?? 0) * HOUR", + ' + BigInt(p[5] ?? 0) * MINUTE + BigInt(p[6] ?? 0) * SECOND + BigInt((p[7] ?? "").padEnd(6, "0").slice(0, 6));', ' return p[1] === "-" ? -mag : mag;', "};", ].join("\n"); @@ -85,10 +88,10 @@ const ISO_TEXT_FN = [ ].join("\n"); export const DURATION_WRITE_HELPER_DECL = [ - "/** A field.duration on the wire: an ISO-8601 duration (days, hours, minutes, seconds) rewritten to its", - " * canonical form — hours never folded into days, zero components left out, zero as PT0S, at most six", - " * fractional digits (truncated), one leading \"-\" for a negative span. Counted in bigint", - " * microseconds, so any length is exact. Generated. */", + "/** A field.duration on the wire: an ISO-8601 duration (weeks, days, hours, minutes, seconds) rewritten", + " * to its canonical form — hours never folded into days, zero components left out, zero as PT0S, one", + " * leading \"-\" for a negative span. Counted in bigint microseconds, so any length is exact and a", + " * fraction past six digits is truncated toward zero. Generated. */", `function ${DURATION_WRITE_HELPER}(text: string): string {`, indent(UNIT_LINES, 2), indent(PARSE_ISO_FN, 2), diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts index 82c061b07c..eb07f60afe 100644 --- a/examples/showcase/codegen/templates/zod-validators.ts +++ b/examples/showcase/codegen/templates/zod-validators.ts @@ -773,7 +773,7 @@ function zodFieldExpr( baseStr = field.attr(FIELD_ATTR_LENIENT) === true ? "z.string()" : ZOD_INET_EXPR; break; case FIELD_SUBTYPE_DURATION: - // An ISO-8601 duration (days, hours, minutes, seconds; no years, months or weeks). A WRITE + // An ISO-8601 duration (weeks, days, hours, minutes, seconds; no years or months). A WRITE // shape rewrites it to the canonical form (duration-wire-helper.ts), so equal spans are // equal strings on the wire and in a jsonb value object (the column codec binds the // column's own form); the TPH read shape parses rows the codec has already put in it. diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index 479ef57fb9..df2eadc0ff 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -448,7 +448,7 @@ that becomes a CHECK takes an optional db-provider `@constraintName` naming it. { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } -{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md index 479ef57fb9..df2eadc0ff 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -448,7 +448,7 @@ that becomes a CHECK takes an optional db-provider `@constraintName` naming it. { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } -{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md index 479ef57fb9..df2eadc0ff 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -448,7 +448,7 @@ that becomes a CHECK takes an optional db-provider `@constraintName` naming it. { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } -{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md index 479ef57fb9..df2eadc0ff 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -448,7 +448,7 @@ that becomes a CHECK takes an optional db-provider `@constraintName` naming it. { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } -{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md index 479ef57fb9..df2eadc0ff 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/SKILL.md @@ -448,7 +448,7 @@ that becomes a CHECK takes an optional db-provider `@constraintName` naming it. { "validator.requiredWhen": { "name": "reasonIfRejected", "@field": "rejectReason", "@when": "status", "@equals": "rejected" } } { "validator.presentIff": { "name": "usedAtWhenUsed", "@field": "usedAt", "@when": "isUsed", "@equals": "true" } } { "validator.atLeastOne": { "name": "emailOrPhone", "@fields": ["email", "phone"] } } -{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["patientId", "caseId"], "@max": 1 } } +{ "validator.atLeastOne": { "name": "oneOwner", "@fields": ["customerId", "accountId"], "@max": 1 } } ``` These are children of `object.entity`, alongside its fields and identities. diff --git a/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json b/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json index f99b2161d4..04158bd523 100644 --- a/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json +++ b/fixtures/conformance/error-validator-at-least-one-max-zero/input/meta.checks.json @@ -16,12 +16,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -48,8 +48,8 @@ "validator.atLeastOne": { "name": "none", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@max": 0 } diff --git a/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json b/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json index 973d719d09..45033335d3 100644 --- a/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json +++ b/fixtures/conformance/error-validator-at-least-one-max/input/meta.checks.json @@ -16,12 +16,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -34,8 +34,8 @@ "validator.atLeastOne": { "name": "oneSource", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@max": 3 } diff --git a/fixtures/conformance/error-validator-condition-type/input/meta.checks.json b/fixtures/conformance/error-validator-condition-type/input/meta.checks.json index 2e6a63b835..d900247e36 100644 --- a/fixtures/conformance/error-validator-condition-type/input/meta.checks.json +++ b/fixtures/conformance/error-validator-condition-type/input/meta.checks.json @@ -16,12 +16,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -48,11 +48,11 @@ "validator.atLeastOne": { "name": "notBoolean", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@condition": { - "field": "patientId" + "field": "storeId" } } }, @@ -60,8 +60,8 @@ "validator.atLeastOne": { "name": "booleanAsString", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@condition": { "op": "eq", @@ -78,13 +78,13 @@ "validator.atLeastOne": { "name": "nullLiteral", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@condition": { "op": "ne", "left": { - "field": "patientId" + "field": "storeId" }, "right": { "value": null @@ -96,8 +96,8 @@ "validator.atLeastOne": { "name": "notAMember", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@condition": { "op": "eq", @@ -114,8 +114,8 @@ "validator.atLeastOne": { "name": "numberAsString", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@condition": { "op": "eq", @@ -123,7 +123,7 @@ "value": "5" }, "right": { - "field": "patientId" + "field": "storeId" } } } diff --git a/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json b/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json index 7b1c87b8db..d5c768ea92 100644 --- a/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json +++ b/fixtures/conformance/error-validator-condition-unknown-field/input/meta.checks.json @@ -16,12 +16,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -34,8 +34,8 @@ "validator.atLeastOne": { "name": "oneSource", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@condition": { "op": "isNotNull", diff --git a/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json b/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json index 9c3acba6d8..b6e333729a 100644 --- a/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json +++ b/fixtures/conformance/error-validator-condition-unknown-fields/input/meta.checks.json @@ -16,12 +16,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -47,7 +47,7 @@ { "validator.requiredWhen": { "name": "rw", - "@field": "patientId", + "@field": "storeId", "@when": "kind", "@equals": "Owned", "@condition": { @@ -72,7 +72,7 @@ { "validator.presentIff": { "name": "pi", - "@field": "caregiverId", + "@field": "kioskId", "@when": "kind", "@equals": "Shared", "@condition": { @@ -86,9 +86,9 @@ { "validator.comparison": { "name": "cmp", - "@left": "patientId", + "@left": "storeId", "@op": "lt", - "@right": "caregiverId", + "@right": "kioskId", "@condition": { "op": "isNotNull", "arg": { diff --git a/fixtures/conformance/validator-constraint-name-condition-max/expected.json b/fixtures/conformance/validator-constraint-name-condition-max/expected.json index bce39ccc29..5165e6f849 100644 --- a/fixtures/conformance/validator-constraint-name-condition-max/expected.json +++ b/fixtures/conformance/validator-constraint-name-condition-max/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "OfficeHours", + "name": "StoreHours", "children": [ { "source.rdb": { - "@table": "OfficeHours" + "@table": "StoreHours" } }, { @@ -19,9 +19,9 @@ { "field.enum": { "name": "kind", - "@constraintName": "CK_OfficeHours_Kind", + "@constraintName": "CK_StoreHours_Kind", "@values": [ - "Clinic", + "InStore", "Phone" ] } @@ -33,7 +33,7 @@ { "validator.numeric": { "name": "weekday", - "@constraintName": "CK_OfficeHours_StartDay", + "@constraintName": "CK_StoreHours_StartDay", "@max": 6, "@min": 0 } @@ -63,14 +63,14 @@ { "validator.length": { "name": "len", - "@constraintName": "CK_OfficeHours_Code", + "@constraintName": "CK_StoreHours_Code", "@max": 8 } }, { "validator.regex": { "name": "shape", - "@constraintName": "CK_OfficeHours_CodeShape", + "@constraintName": "CK_StoreHours_CodeShape", "@pattern": "^[A-Z0-9]+$" } } @@ -79,12 +79,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -108,7 +108,7 @@ "field": "endDay" } }, - "@constraintName": "CK_OfficeHours_SameDayValidation", + "@constraintName": "CK_StoreHours_SameDayTimes", "@left": "endTime", "@op": "gt", "@right": "startTime" @@ -117,10 +117,10 @@ { "validator.atLeastOne": { "name": "oneSource", - "@constraintName": "CK_OfficeHours_ExactlyOneSource", + "@constraintName": "CK_StoreHours_ExactlyOneLocation", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@max": 1 } diff --git a/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json b/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json index 89e4161635..8f235f0d12 100644 --- a/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json +++ b/fixtures/conformance/validator-constraint-name-condition-max/input/meta.checks.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "OfficeHours", + "name": "StoreHours", "children": [ { "source.rdb": { - "@table": "OfficeHours" + "@table": "StoreHours" } }, { @@ -20,10 +20,10 @@ "field.enum": { "name": "kind", "@values": [ - "Clinic", + "InStore", "Phone" ], - "@constraintName": "CK_OfficeHours_Kind" + "@constraintName": "CK_StoreHours_Kind" } }, { @@ -35,7 +35,7 @@ "name": "weekday", "@min": 0, "@max": 6, - "@constraintName": "CK_OfficeHours_StartDay" + "@constraintName": "CK_StoreHours_StartDay" } } ] @@ -64,14 +64,14 @@ "validator.length": { "name": "len", "@max": 8, - "@constraintName": "CK_OfficeHours_Code" + "@constraintName": "CK_StoreHours_Code" } }, { "validator.regex": { "name": "shape", "@pattern": "^[A-Z0-9]+$", - "@constraintName": "CK_OfficeHours_CodeShape" + "@constraintName": "CK_StoreHours_CodeShape" } } ] @@ -79,12 +79,12 @@ }, { "field.long": { - "name": "patientId" + "name": "storeId" } }, { "field.long": { - "name": "caregiverId" + "name": "kioskId" } }, { @@ -100,7 +100,7 @@ "@left": "endTime", "@op": "gt", "@right": "startTime", - "@constraintName": "CK_OfficeHours_SameDayValidation", + "@constraintName": "CK_StoreHours_SameDayTimes", "@condition": { "op": "eq", "left": { @@ -116,11 +116,11 @@ "validator.atLeastOne": { "name": "oneSource", "@fields": [ - "patientId", - "caregiverId" + "storeId", + "kioskId" ], "@max": 1, - "@constraintName": "CK_OfficeHours_ExactlyOneSource" + "@constraintName": "CK_StoreHours_ExactlyOneLocation" } } ] diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json index 1b5946bbc8..abb6483b2d 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/openapi.json @@ -863,8 +863,8 @@ "description": "Sugar for the eq operator.", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -872,8 +872,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -881,8 +881,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -890,8 +890,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -899,8 +899,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -908,8 +908,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -917,8 +917,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -1803,8 +1803,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ @@ -2006,8 +2006,8 @@ }, "holdFor": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "$ref": "#/components/schemas/AddressCreate" @@ -2217,8 +2217,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.create.schema.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.create.schema.json index 841a4cde3e..6b274c2876 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.create.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.create.schema.json @@ -105,8 +105,8 @@ }, "holdFor": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "$ref": "./Address.create.schema.json" diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.schema.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.schema.json index f18454787b..2336826976 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.schema.json @@ -156,8 +156,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.strict.schema.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.strict.schema.json index 476cdea894..3f403bcb48 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.strict.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.strict.schema.json @@ -130,7 +130,7 @@ ] }, "holdFor": { - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks). Pattern: ^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$.", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months). Pattern: ^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$.", "type": [ "string", "null" diff --git a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.update.schema.json b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.update.schema.json index a7d9ff35dd..9b3af60d63 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.update.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-emit/expected/schemas/acme/contract/AllFields.update.schema.json @@ -155,8 +155,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json index 654aa92256..0df2287e3d 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/openapi.json @@ -863,8 +863,8 @@ "description": "Sugar for the eq operator.", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -872,8 +872,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -881,8 +881,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -890,8 +890,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -899,8 +899,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -908,8 +908,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -917,8 +917,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -1795,8 +1795,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ @@ -1998,8 +1998,8 @@ }, "holdFor": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "$ref": "#/components/schemas/AddressCreate" @@ -2209,8 +2209,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.create.schema.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.create.schema.json index 841a4cde3e..6b274c2876 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.create.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.create.schema.json @@ -105,8 +105,8 @@ }, "holdFor": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "$ref": "./Address.create.schema.json" diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.schema.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.schema.json index f18454787b..2336826976 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.schema.json @@ -156,8 +156,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.strict.schema.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.strict.schema.json index 476cdea894..3f403bcb48 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.strict.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.strict.schema.json @@ -130,7 +130,7 @@ ] }, "holdFor": { - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks). Pattern: ^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$.", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months). Pattern: ^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$.", "type": [ "string", "null" diff --git a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.update.schema.json b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.update.schema.json index a7d9ff35dd..9b3af60d63 100644 --- a/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.update.schema.json +++ b/fixtures/contract-conformance/all-fields-wire-string-omit/expected/schemas/acme/contract/AllFields.update.schema.json @@ -155,8 +155,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields/expected/openapi.json b/fixtures/contract-conformance/all-fields/expected/openapi.json index d1fe3174fb..f9c82e3690 100644 --- a/fixtures/contract-conformance/all-fields/expected/openapi.json +++ b/fixtures/contract-conformance/all-fields/expected/openapi.json @@ -863,8 +863,8 @@ "description": "Sugar for the eq operator.", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -872,8 +872,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -881,8 +881,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -890,8 +890,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -899,8 +899,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -908,8 +908,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -917,8 +917,8 @@ "in": "query", "schema": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." } }, { @@ -1803,8 +1803,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ @@ -2006,8 +2006,8 @@ }, "holdFor": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "$ref": "#/components/schemas/AddressCreate" @@ -2217,8 +2217,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.create.schema.json b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.create.schema.json index 841a4cde3e..6b274c2876 100644 --- a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.create.schema.json +++ b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.create.schema.json @@ -105,8 +105,8 @@ }, "holdFor": { "type": "string", - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "$ref": "./Address.create.schema.json" diff --git a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.schema.json b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.schema.json index 3fb62e2687..ffb9312fb2 100644 --- a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.schema.json +++ b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.schema.json @@ -157,8 +157,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.strict.schema.json b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.strict.schema.json index 476cdea894..3f403bcb48 100644 --- a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.strict.schema.json +++ b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.strict.schema.json @@ -130,7 +130,7 @@ ] }, "holdFor": { - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks). Pattern: ^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$.", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months). Pattern: ^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$.", "type": [ "string", "null" diff --git a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.update.schema.json b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.update.schema.json index a7d9ff35dd..9b3af60d63 100644 --- a/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.update.schema.json +++ b/fixtures/contract-conformance/all-fields/expected/schemas/acme/contract/AllFields.update.schema.json @@ -155,8 +155,8 @@ "string", "null" ], - "pattern": "^[-+]?P([0-9]+D(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+M([0-9]+(\\.[0-9]{1,9})?S)?|[0-9]+(\\.[0-9]{1,9})?S))$", - "description": "An ISO-8601 duration: days, hours, minutes and seconds (no years, months or weeks)." + "pattern": "^[-+]?P(([0-9]+W([0-9]+D)?|[0-9]+D)(T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))?|T([0-9]+H([0-9]+M)?([0-9]+(\\.[0-9]+)?S)?|[0-9]+M([0-9]+(\\.[0-9]+)?S)?|[0-9]+(\\.[0-9]+)?S))$", + "description": "An ISO-8601 duration: weeks, days, hours, minutes and seconds (no years or months)." }, "shipTo": { "anyOf": [ diff --git a/fixtures/duration-wire/README.md b/fixtures/duration-wire/README.md index a640f95d83..5033b54ad4 100644 --- a/fixtures/duration-wire/README.md +++ b/fixtures/duration-wire/README.md @@ -1,33 +1,44 @@ # field.duration wire vectors -The wire rule for `field.duration` (a fixed-length span of time), shared by every port so they -agree on every input, not only the ones a persistence scenario happens to write. - -- **`parse`**: an ISO-8601 duration a caller may send, and the canonical form every port answers - for it. The canonical form is `[-]PT[H][M][[.]S]`: hours are never folded into days, - zero components are left out, zero is `PT0S`, there are at most six fractional digits (the - precision of a Postgres `interval`; more are truncated toward zero, never rounded), and a - negative duration has one leading `-`. A day (`D`) is exactly 24 hours. There is no shared - upper bound: each port is limited only by its own type (a .NET `TimeSpan`, a `timedelta`) and - each database by its own column, and refuses what it cannot hold rather than wrapping it. -- **`refused`**: input that is not a duration. Years, months and weeks are refused because a - calendar span has no fixed length. So are lowercase designators, fractional hours or minutes, - a comma decimal separator, per-component signs, out-of-order components and whitespace. -- **`postgres`**: the text a Postgres `interval` column returns under the default - `IntervalStyle` (`postgres`), and its canonical form. A port reading through a driver that - hands back a native value (Npgsql `TimeSpan`, a JDBC `PGInterval`) checks the same rule - against that value. -- **`postgresRefused`**: an interval with a year or month part is not a duration; reading one - is an error, never a guess at the length of a month. -- **`postgresText`**: a canonical duration and its Postgres interval spelling, `[-]HH:MM:SS[.f]` - with unbounded hours and no day part. Postgres refuses an ISO-8601 duration with a leading sign - (`-PT1M30S` is "invalid input syntax for type interval"), so a port that binds a duration to - Postgres as TEXT uses this spelling, and so does `meta migrate` for a declared `@default`. An - interval written this way is returned in exactly this spelling, so a default never drifts and a - value reads back as it was written. A port whose driver binds a native type (Npgsql `TimeSpan`, - a JDBC `PGInterval`, a Python `timedelta`) does not need it. -- **`storedMicros`**: a canonical duration and the integer count of microseconds a SQLite, D1 or - MySQL column stores for it (`BIGINT`; Postgres keeps its native `interval`). An integer orders and - compares as the span does, so sorting, range filters and equality are right on every database. - This is how Django stores a `DurationField` outside Postgres. The 64-bit column holds about - 2.56 billion hours; a port refuses to bind a longer span there. +The wire rule for `field.duration` (a fixed-length span of time), and the codecs some ports need +to store one. [`vectors.json`](./vectors.json) has two parts. + +## `wire`: every port passes every vector + +The ISO-8601 text a caller sends and a port answers. Clients depend on it, so every port agrees. + +- **`parse`**: a duration a caller may send, and the canonical form a port answers for it. The + canonical form is `[-]PT[H][M][[.]S]`: hours are never folded into days, zero + components are left out, zero is `PT0S`, trailing zeros of the fraction are dropped, and a + negative duration has one leading `-`. A day (`D`) is exactly 24 hours and a week (`W`) exactly + 7 days. +- **`precision`**: the fraction may have any number of digits. A port keeps as many as its own + duration type holds and truncates the rest toward zero, never rounding. `out` is keyed by that + number of digits, and a port checks the entry for its own: 6 for TypeScript and Python + (microseconds), 7 for C# (a `TimeSpan` tick is 100 ns), 9 for Java and Kotlin (`java.time.Duration`). +- **`refused`**: input that is not a duration. Years and months are refused because a calendar + span has no fixed length. So are lowercase designators, fractional hours, minutes or weeks, a + comma decimal separator, per-component signs, out-of-order components and whitespace. + +There is no shared upper bound. Each port is limited only by its own type (a .NET `TimeSpan`, a +`timedelta`) and each database by its own column; a port refuses what it cannot hold rather than +wrapping it, and tests that limit in its own suite. + +## `codecs`: a port passes a group only when it has that codec + +| Group | What it pins | Passed by | +|---|---|---| +| `postgres` | the text a Postgres `interval` column returns under the default `IntervalStyle` (`postgres`), and its canonical form | a port that reads an interval as text, or checks a native value (Npgsql `TimeSpan`, a JDBC `PGInterval`) against the same rule | +| `postgresRefused` | an interval with a year or month part; reading one is an error, never a guess at the length of a month | the same ports | +| `postgresText` | a canonical duration and its Postgres spelling, `[-]HH:MM:SS[.f]` with unbounded hours and no day part | a port that binds a duration to Postgres as text, and `meta migrate` for a declared `@default`. Postgres refuses a signed ISO-8601 duration (`-PT1M30S` is "invalid input syntax for type interval"), and returns an interval written this way in the same spelling, so a default never drifts | +| `storedMicros` | a duration and the integer count of microseconds a SQLite, D1 or MySQL column stores for it (`BIGINT`), sub-microsecond digits truncated toward zero | a port that stores durations on one of those databases | + +An integer column orders and compares as the span does, so sorting, range filters and equality are +right on every database. This is how Django stores a `DurationField` outside Postgres. The 64-bit +column holds about 2.56 billion hours; a port refuses to bind a longer span there. Postgres keeps its +native `interval`, which holds microseconds. + +The Postgres text readers assume the server's default `IntervalStyle`, `postgres`. A session set to +`iso_8601`, `sql_standard` or `postgres_verbose` returns another spelling. A reader accepts it only +where it means the same span (an unsigned `iso_8601` value is plain ISO-8601) and refuses the rest, +such as `iso_8601`'s per-component signs (`PT-1M-30S`), rather than misreading it. diff --git a/fixtures/duration-wire/vectors.json b/fixtures/duration-wire/vectors.json index 2bf300c4ce..bd284d12e0 100644 --- a/fixtures/duration-wire/vectors.json +++ b/fixtures/duration-wire/vectors.json @@ -1,87 +1,105 @@ { - "$comment": "The field.duration wire rule. Each port's production duration helper must pass every vector; see README.md.", - "parse": [ - { "in": "PT1H30M", "out": "PT1H30M" }, - { "in": "PT90M", "out": "PT1H30M" }, - { "in": "PT5400S", "out": "PT1H30M" }, - { "in": "P1D", "out": "PT24H" }, - { "in": "P1DT2H", "out": "PT26H" }, - { "in": "P10DT0.5S", "out": "PT240H0.5S" }, - { "in": "PT1.5S", "out": "PT1.5S" }, - { "in": "PT0.000001S", "out": "PT0.000001S" }, - { "in": "PT1.123456789S", "out": "PT1.123456S" }, - { "in": "PT1.100S", "out": "PT1.1S" }, - { "in": "PT1H5S", "out": "PT1H5S" }, - { "in": "PT0S", "out": "PT0S" }, - { "in": "P0D", "out": "PT0S" }, - { "in": "-PT0S", "out": "PT0S" }, - { "in": "+PT2M", "out": "PT2M" }, - { "in": "-PT90S", "out": "-PT1M30S" }, - { "in": "-P1DT1H", "out": "-PT25H" }, - { "in": "PT0.0000001S", "out": "PT0S" }, - { "in": "PT876000H", "out": "PT876000H" } - ], - "refused": [ - "", - "P", - "PT", - "P1DT", - "P1Y", - "P1M", - "P1W", - "P1Y2M3D", - "pt1h", - "PT1.5H", - "PT1,5S", - "PT1.S", - "PT.5S", - "PT1.1234567890S", - "1:30:00", - "PT1H 30M", - " PT1H", - "PT-1H", - "--PT1H", - "PT1M1H" - ], - "postgres": [ - { "in": "01:30:00", "out": "PT1H30M" }, - { "in": "00:00:00", "out": "PT0S" }, - { "in": "00:00:01.5", "out": "PT1.5S" }, - { "in": "00:00:00.000001", "out": "PT0.000001S" }, - { "in": "-00:01:30", "out": "-PT1M30S" }, - { "in": "26:00:00", "out": "PT26H" }, - { "in": "1 day", "out": "PT24H" }, - { "in": "1 day 02:00:00", "out": "PT26H" }, - { "in": "3 days", "out": "PT72H" }, - { "in": "-1 days", "out": "-PT24H" }, - { "in": "-1 days +02:00:00", "out": "-PT22H" }, - { "in": "1 day -01:00:00", "out": "PT23H" }, - { "in": "876000:00:00", "out": "PT876000H" } - ], - "postgresRefused": [ - "1 year", - "2 mons", - "1 year 2 mons 3 days 04:05:06", - "1 mon 00:00:01", - "abc" - ], - "postgresText": [ - { "in": "PT1H30M", "out": "01:30:00" }, - { "in": "PT0S", "out": "00:00:00" }, - { "in": "PT1.5S", "out": "00:00:01.5" }, - { "in": "PT0.000001S", "out": "00:00:00.000001" }, - { "in": "-PT1M30S", "out": "-00:01:30" }, - { "in": "PT26H", "out": "26:00:00" }, - { "in": "-PT26H0.5S", "out": "-26:00:00.5" }, - { "in": "PT876000H", "out": "876000:00:00" } - ], - "storedMicros": [ - { "in": "PT0S", "out": "0" }, - { "in": "PT0.000001S", "out": "1" }, - { "in": "PT1.5S", "out": "1500000" }, - { "in": "PT1H30M", "out": "5400000000" }, - { "in": "-PT1M30S", "out": "-90000000" }, - { "in": "PT26H", "out": "93600000000" }, - { "in": "PT876000H", "out": "3153600000000000" } - ] + "$comment": "The field.duration wire rule and the codecs some ports need. Every port passes `wire`; a port passes a `codecs` group only when it has that codec. See README.md.", + "wire": { + "parse": [ + { "in": "PT1H30M", "out": "PT1H30M" }, + { "in": "PT90M", "out": "PT1H30M" }, + { "in": "PT5400S", "out": "PT1H30M" }, + { "in": "P1D", "out": "PT24H" }, + { "in": "P1DT2H", "out": "PT26H" }, + { "in": "P10DT0.5S", "out": "PT240H0.5S" }, + { "in": "PT1.5S", "out": "PT1.5S" }, + { "in": "PT0.000001S", "out": "PT0.000001S" }, + { "in": "PT1.100S", "out": "PT1.1S" }, + { "in": "PT1H5S", "out": "PT1H5S" }, + { "in": "PT0S", "out": "PT0S" }, + { "in": "P0D", "out": "PT0S" }, + { "in": "-PT0S", "out": "PT0S" }, + { "in": "+PT2M", "out": "PT2M" }, + { "in": "-PT90S", "out": "-PT1M30S" }, + { "in": "-P1DT1H", "out": "-PT25H" }, + { "in": "PT876000H", "out": "PT876000H" }, + { "in": "P1W", "out": "PT168H" }, + { "in": "P2W", "out": "PT336H" }, + { "in": "P1W1DT1H", "out": "PT193H" }, + { "in": "-P1W", "out": "-PT168H" } + ], + "precision": [ + { "in": "PT1.123456789S", "out": { "6": "PT1.123456S", "7": "PT1.1234567S", "9": "PT1.123456789S" } }, + { "in": "PT0.0000001S", "out": { "6": "PT0S", "7": "PT0.0000001S", "9": "PT0.0000001S" } }, + { "in": "PT0.000000001S", "out": { "6": "PT0S", "7": "PT0S", "9": "PT0.000000001S" } }, + { "in": "PT1.1234567890123S", "out": { "6": "PT1.123456S", "7": "PT1.1234567S", "9": "PT1.123456789S" } }, + { "in": "PT0.99999999999999S", "out": { "6": "PT0.999999S", "7": "PT0.9999999S", "9": "PT0.999999999S" } }, + { "in": "-PT1.9999999999S", "out": { "6": "-PT1.999999S", "7": "-PT1.9999999S", "9": "-PT1.999999999S" } }, + { "in": "PT1.10000000S", "out": { "6": "PT1.1S", "7": "PT1.1S", "9": "PT1.1S" } } + ], + "refused": [ + "", + "P", + "PT", + "P1DT", + "P1Y", + "P1M", + "P1Y2M3D", + "pt1h", + "PT1.5H", + "PT1,5S", + "PT1.S", + "PT.5S", + "1:30:00", + "PT1H 30M", + " PT1H", + "PT-1H", + "--PT1H", + "PT1M1H", + "P1D1W", + "P1.5W", + "PT1W" + ] + }, + "codecs": { + "postgres": [ + { "in": "01:30:00", "out": "PT1H30M" }, + { "in": "00:00:00", "out": "PT0S" }, + { "in": "00:00:01.5", "out": "PT1.5S" }, + { "in": "00:00:00.000001", "out": "PT0.000001S" }, + { "in": "-00:01:30", "out": "-PT1M30S" }, + { "in": "26:00:00", "out": "PT26H" }, + { "in": "1 day", "out": "PT24H" }, + { "in": "1 day 02:00:00", "out": "PT26H" }, + { "in": "3 days", "out": "PT72H" }, + { "in": "-1 days", "out": "-PT24H" }, + { "in": "-1 days +02:00:00", "out": "-PT22H" }, + { "in": "1 day -01:00:00", "out": "PT23H" }, + { "in": "876000:00:00", "out": "PT876000H" } + ], + "postgresRefused": [ + "1 year", + "2 mons", + "1 year 2 mons 3 days 04:05:06", + "1 mon 00:00:01", + "abc" + ], + "postgresText": [ + { "in": "PT1H30M", "out": "01:30:00" }, + { "in": "PT0S", "out": "00:00:00" }, + { "in": "PT1.5S", "out": "00:00:01.5" }, + { "in": "PT0.000001S", "out": "00:00:00.000001" }, + { "in": "-PT1M30S", "out": "-00:01:30" }, + { "in": "PT26H", "out": "26:00:00" }, + { "in": "-PT26H0.5S", "out": "-26:00:00.5" }, + { "in": "PT876000H", "out": "876000:00:00" } + ], + "storedMicros": [ + { "in": "PT0S", "out": "0" }, + { "in": "PT0.000001S", "out": "1" }, + { "in": "PT1.5S", "out": "1500000" }, + { "in": "PT1H30M", "out": "5400000000" }, + { "in": "-PT1M30S", "out": "-90000000" }, + { "in": "PT26H", "out": "93600000000" }, + { "in": "PT876000H", "out": "3153600000000000" }, + { "in": "PT1.123456789S", "out": "1123456" }, + { "in": "-PT1.0000015S", "out": "-1000001" } + ] + } } diff --git a/fixtures/enum-length-conformance/README.md b/fixtures/enum-length-conformance/README.md index da80e553ed..593a0b2862 100644 --- a/fixtures/enum-length-conformance/README.md +++ b/fixtures/enum-length-conformance/README.md @@ -6,21 +6,25 @@ neither it stays an unbounded text column, as before. An `@intValueMap` enum is column and takes no length. Every member must fit: the loader refuses an `@maxLength` a member is longer than (`ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH`, pinned in `fixtures/conformance/`), and the core resolver refuses a member longer than the project default, so every consumer that sizes -the column refuses the same model. +the column refuses the same model. The `@maxLength` refusals are metamodel rules every port's +loader applies; the corpus here is for a port that sizes the column. -[`cases.json`](./cases.json) holds the `enums` blocks every port must accept, with the length -each enum in [`meta.enums.json`](./meta.enums.json) resolves to under them, the overflow every -port must refuse, and the blocks every port must refuse when it reads the file. A whole +[`cases.json`](./cases.json) holds the `enums` blocks a port must accept, with the length +each enum in [`meta.enums.json`](./meta.enums.json) resolves to under them, the overflow a +port must refuse, and the blocks a port must refuse when it reads the file. A whole number is accepted however JSON spells it (`32`, `32.0`, `1e2`), because a JSON reader that -parses numbers as doubles cannot tell those apart. Each port runs -it through its own config reader and core resolver: +parses numbers as doubles cannot tell those apart. Each port that sizes the column runs it +through its own config reader and core resolver: | Port | Test | |---|---| | TypeScript | `server/typescript/packages/sdk/test/enum-length-conformance.test.ts` | | C# | `server/csharp/MetaObjects.Codegen.Tests/EnumLengthConformanceTests.cs` | | Java / Kotlin | `server/java/metadata/src/test/java/com/metaobjects/database/EnumLengthConformanceTest.java` | -| Python | `server/python/tests/conformance/test_enum_length_conformance.py` | + +Python does not run it: no Python generator or run-time path emits a column type or DDL, so +nothing there has a column to size. Its config reader still accepts an `enums` block (a project +shared with another port has one) and refuses a malformed one, and reads nothing from it. The column each port's bindings emit is described in [`docs/features/field-types.md`](../../docs/features/field-types.md). diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 2e118b6217..b21ebf108f 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -34,7 +34,7 @@ children and the cardinality of that subtype. Documentation attributes | `field.date` | Calendar date (no time-of-day). Binds to the native date/temporal type; DB column is DATE. | [types/field.md#fielddate](types/field.md#fielddate) | | `field.decimal` | Precision-exact decimal (use @precision/@scale). Native TS binding is string (lossless); DB column is NUMERIC(p,s); the wire form is a string. Classified DATA_TYPE_STRING so an exact decimal is never silently rounded through a double. | [types/field.md#fielddecimal](types/field.md#fielddecimal) | | `field.double` | Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/number type; DB column is DOUBLE PRECISION. Not for money — use field.currency or field.decimal. | [types/field.md#fielddouble](types/field.md#fielddouble) | -| `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. | [types/field.md#fieldduration](types/field.md#fieldduration) | +| `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, as many fractional digits as its native type holds, zero is PT0S) and reads that form plus leading week and day counts (nW, exactly 7 days; nD, exactly 24 hours) and a fraction of any length, truncated toward zero. Years and months are refused: a calendar span is not a fixed length. | [types/field.md#fieldduration](types/field.md#fieldduration) | | `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. | [types/field.md#fieldenum](types/field.md#fieldenum) | | `field.float` | Single-precision floating point. Binds to the native double/number type (TS has no distinct float); DB column is REAL. Not for money. | [types/field.md#fieldfloat](types/field.md#fieldfloat) | | `field.inet` | An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IPv4-or-IPv6 literal validator (a Zod regex union in TS — z.string().ip() was removed in Zod 4 — native IP-type parsing in the other ports); add @lenient to bind a plain string with no validator. v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4\|ipv6 value-constraint. | [types/field.md#fieldinet](types/field.md#fieldinet) | diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index 637f59fb34..d26330c317 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -216,7 +216,7 @@ Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/nu ### field.duration -A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length. +A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, as many fractional digits as its native type holds, zero is PT0S) and reads that form plus leading week and day counts (nW, exactly 7 days; nD, exactly 24 hours) and a fraction of any length, truncated toward zero. Years and months are refused: a calendar span is not a fixed length. **Owning provider:** metaobjects-core-types diff --git a/fixtures/naming-conformance/physical-names/cases.json b/fixtures/naming-conformance/physical-names/cases.json index 9567aa4c9b..4a8444d1d5 100644 --- a/fixtures/naming-conformance/physical-names/cases.json +++ b/fixtures/naming-conformance/physical-names/cases.json @@ -1,5 +1,5 @@ { - "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `PascalCase` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`): the names EF Core and most C# schemas use. A key `..` names a member of a `@storage: flattened` value object: its column is the flattened prefix (`@flattenedColumnPrefix` on the embedding field, verbatim, `\"\"` allowed; else that field's resolved column and `_`) followed by the member's resolved column; a prefix inherited through `extends` counts.", + "_comment": "Cross-port physical naming (ADR-0058). Each case is the `naming` block of a project's .metaobjects/config.json. A port parses it with the reader it uses for that file, loads meta.naming.json, and resolves every table and column below through the resolver its codegen, migrate (TypeScript), runtime and verify use. `tables` keys are object names; `columns` keys are `.`. Overrides (@table, a source's structural name, @column) win under every rule; the entity-name fallback keeps the frozen legacy pluralizer under every rule. `invalid` blocks must be refused when the config is read. `upperFirst` upper-cases the field name's first letter and changes nothing else (`requestURL` → `RequestURL`). A key `..` names a member of a `@storage: flattened` value object: its column is the flattened prefix (`@flattenedColumnPrefix` on the embedding field, verbatim, `\"\"` allowed; else that field's resolved column and `_`) followed by the member's resolved column; a prefix inherited through `extends` counts.", "cases": [ { "name": "default", @@ -67,8 +67,8 @@ } }, { - "name": "PascalCase columns, literal tables", - "naming": { "columns": "PascalCase", "tables": "literal" }, + "name": "upperFirst columns, literal tables", + "naming": { "columns": "upperFirst", "tables": "literal" }, "tables": { "OrderItem": "OrderItems", "Person": "people", "AuditEntry": "AuditLog", "Category": "Categories", "HTTPRequest": "HTTPRequests", "Shipment": "Shipments" }, "columns": { "OrderItem.id": "Id", "OrderItem.createdAt": "CreatedAt", "OrderItem.unitPriceCents": "UnitPriceCents", "OrderItem.sku": "SKU_CODE", @@ -83,7 +83,7 @@ "invalid": [ { "name": "unknown column rule", "naming": { "columns": "camelCase" } }, { "name": "kebab-case is not a table rule", "naming": { "tables": "kebab-case" } }, - { "name": "PascalCase is not a table rule", "naming": { "tables": "PascalCase" } }, + { "name": "upperFirst is not a table rule", "naming": { "tables": "upperFirst" } }, { "name": "unknown key", "naming": { "column": "literal" } }, { "name": "not an object", "naming": "snake_case"} ] diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 59a8ee972a..1c498fbb18 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1027,7 +1027,7 @@ { "type": "field", "subType": "duration", - "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, up to 6 fractional digits, zero is PT0S) and reads that form plus a leading day count (nD, exactly 24 hours). Years, months and weeks are refused: a calendar span is not a fixed length.", + "description": "A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, as many fractional digits as its native type holds, zero is PT0S) and reads that form plus leading week and day counts (nW, exactly 7 days; nD, exactly 24 hours) and a fraction of any length, truncated toward zero. Years and months are refused: a calendar span is not a fixed length.", "whenToUse": "A field holds an elapsed time, a timeout or a delay. Use it for a native Postgres interval column and a native duration type instead of a string or a number of seconds. A calendar span (\"every 3 months\") is not a duration: model it as an int and a unit.", "attrs": [ { diff --git a/fixtures/validation-conformance/cases.json b/fixtures/validation-conformance/cases.json index f2d46e7303..04b8b49be9 100644 --- a/fixtures/validation-conformance/cases.json +++ b/fixtures/validation-conformance/cases.json @@ -117,7 +117,7 @@ { "name": "duration-accept-zero", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT0S" }, "expectValid": true }, { "name": "duration-reject-months", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P1M" }, "expectValid": false }, { "name": "duration-reject-years", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P1Y" }, "expectValid": false }, - { "name": "duration-reject-weeks", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P2W" }, "expectValid": false }, + { "name": "duration-accept-weeks", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "P2W" }, "expectValid": true }, { "name": "duration-reject-clock", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "1:30:00" }, "expectValid": false }, { "name": "duration-reject-fractional-hours", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "PT1.5H" }, "expectValid": false }, { "name": "duration-reject-lowercase", "payload": { "name": "Acme", "code": "ABC", "score": 50, "tags": ["x"], "note": "ok", "holdFor": "pt1h" }, "expectValid": false }, diff --git a/fixtures/validation-conformance/runtime-errors.json b/fixtures/validation-conformance/runtime-errors.json index acc01d2df8..4ee0515d58 100644 --- a/fixtures/validation-conformance/runtime-errors.json +++ b/fixtures/validation-conformance/runtime-errors.json @@ -212,7 +212,7 @@ { "field": "holdFor", "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years or months)", "expected": "duration", "received": "P1M" } @@ -221,25 +221,16 @@ { "field": "holdFor", "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years or months)", "expected": "duration", "received": "P1Y" } ], - "duration-reject-weeks": [ - { - "field": "holdFor", - "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", - "expected": "duration", - "received": "P2W" - } - ], "duration-reject-clock": [ { "field": "holdFor", "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years or months)", "expected": "duration", "received": "1:30:00" } @@ -248,7 +239,7 @@ { "field": "holdFor", "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years or months)", "expected": "duration", "received": "PT1.5H" } @@ -257,7 +248,7 @@ { "field": "holdFor", "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years or months)", "expected": "duration", "received": "pt1h" } @@ -266,7 +257,7 @@ { "field": "holdFor", "rule": "format", - "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years, months or weeks)", + "message": "'holdFor' must be an ISO-8601 duration such as PT1H30M (no years or months)", "expected": "duration", "received": "PT" } diff --git a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs index 6bdbf7d40d..53450e4cdc 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/DurationWireTests.cs @@ -1,9 +1,12 @@ // field.duration — the C# half of the duration wire rule, gated against the shared vectors in // fixtures/duration-wire/vectors.json. No database: the production wire helper // (Runtime/DurationWire.cs, the SAME text the entity generator emits into every generated project) -// runs every vector, and the emitted text is proven identical to it. The Postgres vectors (what an -// interval column reads back as, through Npgsql's native TimeSpan) are gated against a live -// database in MetaObjects.IntegrationTests/DurationPostgresTests. +// runs every `wire` vector (the `precision` ones at seven digits: a TimeSpan tick is 100 ns), and +// the emitted text is proven identical to it. Of the `codecs` groups C# has two in production: +// `storedMicros` (the generated value converter on SQLite and MySQL, here) and the Postgres read +// (`postgres` and `postgresRefused`, through the generated NpgsqlInterval mapping, gated against a +// live database in MetaObjects.IntegrationTests/Api/DurationWireGeneratedApiTests). C# never spells +// a duration as Postgres text (Npgsql binds a TimeSpan natively), so `postgresText` is not its codec. using System.Reflection; using System.Text.Json; @@ -25,18 +28,31 @@ private static JsonElement Vectors() => JsonDocument.Parse(File.ReadAllText(Path.Combine( CorpusPaths.RepoRoot(), "fixtures", "duration-wire", "vectors.json"))).RootElement; + private static JsonElement Wire(string group) => Vectors().GetProperty("wire").GetProperty(group); + + // The `precision` key for this port: the fractional digits a TimeSpan holds. + private const string PrecisionKey = "7"; + public static TheoryData ParseVectors() { var data = new TheoryData(); - foreach (var v in Vectors().GetProperty("parse").EnumerateArray()) + foreach (var v in Wire("parse").EnumerateArray()) data.Add(v.GetProperty("in").GetString()!, v.GetProperty("out").GetString()!); return data; } + public static TheoryData PrecisionVectors() + { + var data = new TheoryData(); + foreach (var v in Wire("precision").EnumerateArray()) + data.Add(v.GetProperty("in").GetString()!, v.GetProperty("out").GetProperty(PrecisionKey).GetString()!); + return data; + } + public static TheoryData RefusedVectors() { var data = new TheoryData(); - foreach (var v in Vectors().GetProperty("refused").EnumerateArray()) data.Add(v.GetString()!); + foreach (var v in Wire("refused").EnumerateArray()) data.Add(v.GetString()!); return data; } @@ -57,7 +73,15 @@ public void An_accepted_duration_parses_to_its_canonical_form(string input, stri Assert.Equal(canonical, DurationWire.Format(DurationWire.Parse(canonical))); } - [Theory, MemberData(nameof(ParseVectors))] + [Theory, MemberData(nameof(PrecisionVectors))] + public void A_fraction_keeps_whole_ticks_and_truncates_the_rest_toward_zero(string input, string canonical) + { + Assert.True(DurationWire.TryParse(input, out var span), $"'{input}' was refused"); + Assert.Equal(canonical, DurationWire.Format(span)); + Assert.Equal(canonical, DurationWire.Format(DurationWire.Parse(canonical))); + } + + [Theory, MemberData(nameof(ParseVectors)), MemberData(nameof(PrecisionVectors))] public void A_property_reads_the_accepted_form_and_writes_the_canonical_one(string input, string canonical) { var h = JsonSerializer.Deserialize($"{{\"Span\":\"{input}\",\"Maybe\":\"{input}\",\"Many\":[\"{input}\"]}}")!; @@ -86,45 +110,53 @@ public void A_non_duration_token_is_refused(string json) => Assert.ThrowsAny(() => JsonSerializer.Deserialize($"{{\"Span\":{json}}}")); [Fact] - public void Null_crosses_as_null_and_a_tick_below_a_microsecond_truncates_toward_zero() + public void Null_crosses_as_null_and_every_tick_is_written() { Assert.Null(JsonSerializer.Deserialize("{\"Maybe\":null}")!.Maybe); Assert.Contains("\"Maybe\":null", JsonSerializer.Serialize(new Holder())); - Assert.Equal("PT0S", DurationWire.Format(TimeSpan.FromTicks(9))); - Assert.Equal("PT0S", DurationWire.Format(TimeSpan.FromTicks(-9))); - Assert.Equal("PT0.000001S", DurationWire.Format(TimeSpan.FromTicks(19))); - Assert.Equal("-PT0.000001S", DurationWire.Format(TimeSpan.FromTicks(-19))); + Assert.Equal("PT0.0000009S", DurationWire.Format(TimeSpan.FromTicks(9))); + Assert.Equal("-PT0.0000009S", DurationWire.Format(TimeSpan.FromTicks(-9))); + Assert.Equal("PT0.0000019S", DurationWire.Format(TimeSpan.FromTicks(19))); + Assert.Equal("-PT0.0000019S", DurationWire.Format(TimeSpan.FromTicks(-19))); Assert.Equal("-PT1M30S", DurationWire.Format(TimeSpan.FromSeconds(-90))); + Assert.Equal(TimeSpan.FromTicks(-19), DurationWire.Parse("-PT0.00000199S")); // truncated toward zero } public static TheoryData StoredMicrosVectors() { var data = new TheoryData(); - foreach (var v in Vectors().GetProperty("storedMicros").EnumerateArray()) + foreach (var v in Vectors().GetProperty("codecs").GetProperty("storedMicros").EnumerateArray()) data.Add(v.GetProperty("in").GetString()!, v.GetProperty("out").GetString()!); return data; } [Theory, MemberData(nameof(StoredMicrosVectors))] - public void On_a_database_without_an_interval_a_duration_is_its_microsecond_count(string canonical, string micros) + public void On_a_database_without_an_interval_a_duration_is_its_microsecond_count(string duration, string micros) { var count = long.Parse(micros, System.Globalization.CultureInfo.InvariantCulture); - Assert.Equal(count, DurationWire.ToMicros(DurationWire.Parse(canonical))); - Assert.Equal(canonical, DurationWire.Format(DurationWire.FromMicros(count))); + Assert.Equal(count, DurationWire.ToMicros(DurationWire.Parse(duration))); + // The column's precision is a microsecond: what reads back is the span to the microsecond. + Assert.Equal(TimeSpan.FromTicks(count * 10), DurationWire.FromMicros(count)); + Assert.Equal(count, DurationWire.ToMicros(DurationWire.FromMicros(count))); } // C#'s own limit — a TimeSpan's range, about 10.7 million days — not a cross-port one: a span - // past it is refused, never wrapped, on parse and on a stored microsecond count. + // past it is refused, never wrapped, on parse and on a stored microsecond count. The whole + // range is reachable, to the tick, MinValue (one tick longer than MaxValue) included. [Fact] public void A_span_past_a_timespan_is_refused_never_wrapped() { - Assert.Equal("PT256204778H48M5.47758S", DurationWire.Format(TimeSpan.MaxValue)); - Assert.Equal("-PT256204778H48M5.47758S", DurationWire.Format(TimeSpan.MinValue)); + Assert.Equal("PT256204778H48M5.4775807S", DurationWire.Format(TimeSpan.MaxValue)); + Assert.Equal("-PT256204778H48M5.4775808S", DurationWire.Format(TimeSpan.MinValue)); + Assert.Equal(TimeSpan.MaxValue, DurationWire.Parse("PT256204778H48M5.4775807S")); + Assert.Equal(TimeSpan.MaxValue, DurationWire.Parse("PT256204778H48M5.47758079999S")); // truncated, not rounded past + Assert.Equal(TimeSpan.MinValue, DurationWire.Parse("-PT256204778H48M5.4775808S")); Assert.Equal("PT256204778H", DurationWire.Format(DurationWire.Parse("PT256204778H"))); Assert.Equal("-PT256204778H", DurationWire.Format(DurationWire.Parse("-P10675199DT2H"))); - Assert.True(DurationWire.TryParse("PT256204778H48M5.47758S", out var top)); - Assert.Equal(TimeSpan.MaxValue.Ticks / 10, top.Ticks / 10); - foreach (var past in new[] { "PT256204778H48M5.477581S", "PT256204779H", "P10675200D", "-PT256204779H", "PT99999999999999999999S" }) + Assert.Equal("PT256204704H", DurationWire.Format(DurationWire.Parse("P1525028W"))); + foreach (var past in new[] { + "PT256204778H48M5.4775808S", "-PT256204778H48M5.4775809S", "PT256204779H", "P10675200D", + "P1525029W", "P1525028W4D", "-PT256204779H", "PT99999999999999999999S", "P99999999999999999999W" }) Assert.False(DurationWire.TryParse(past, out _), past); Assert.Equal(TimeSpan.MaxValue.Ticks / 10, DurationWire.ToMicros(TimeSpan.MaxValue)); Assert.Throws(() => DurationWire.FromMicros(long.MaxValue)); @@ -156,7 +188,7 @@ public void A_good_duration_operand_passes_and_an_in_list_is_checked_element_wis { Assert.Null(Check("wait", "eq", "PT90M").ErrorEnvelope); Assert.Null(Check("grace", "ne", "-P1DT0.5S").ErrorEnvelope); - Assert.Null(Check("wait", "in", new List { "PT1H", "P2D" }).ErrorEnvelope); + Assert.Null(Check("wait", "in", new List { "PT1H", "P2D", "P1W" }).ErrorEnvelope); Assert.Equal("invalid_filter_value", Check("wait", "in", new List { "PT1H", "P1Y" }).ErrorEnvelope); } @@ -290,7 +322,7 @@ public void A_duration_is_a_TimeSpan_with_the_wire_converter_an_interval_on_Post public void The_npgsql_mapping_names_what_is_missing_when_the_interval_shape_has_changed() { var asm = Compile(Emit()); - var shape = asm.GetType("Acme.Ops.AppDbContext+DurationInterval+IntervalShape")!; + var shape = asm.GetType("Acme.Ops.DurationInterval+IntervalShape")!; var problem = shape.GetMethod("Problem", BindingFlags.NonPublic | BindingFlags.Static)!; string? Check(Type? t) => (string?)problem.Invoke(null, [t]); @@ -326,6 +358,6 @@ public void The_generated_entity_compiles_and_crosses_json_in_the_canonical_form Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Timeout\":\"01:30:00\"}", timer)); Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Grace\":\"P1M\"}", timer)); - Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Backoff\":[\"P1W\"]}", timer)); + Assert.ThrowsAny(() => JsonSerializer.Deserialize("{\"Backoff\":[\"P1Y\"]}", timer)); } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs index 15b9706ab2..7cc13b2834 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs @@ -915,10 +915,40 @@ public void A_flattened_member_gets_a_column_constant_beside_its_field_constants Assert.Contains("public const string ShipToColumn = \"ship_to\";", content); Assert.Contains("public const string PayloadColumn = \"payload\";", content); Assert.Contains("[\"shipTo\"] = ShipToColumn,", content); + // ...but the flattened field's own column constant names no column of the table: deprecated. + Assert.Contains( + " [System.Obsolete(\"A flattened field has no column of its own; use the member constants.\")]\n" + + " public const string ShipToColumn = \"ship_to\";", content.Replace("\r\n", "\n")); + Assert.Single(System.Text.RegularExpressions.Regex.Matches(content, "Obsolete")); Assert.Contains("[\"shipTo.street\"] = ShipToStreetColumn,", content); Assert.Contains("[\"shipTo.postalCode\"] = ShipToPostalCodeColumn,", content); } + // [Obsolete] on a declaration warns nothing; only a use does. A project that never reads the + // flattened field's own constant (TreatWarningsAsErrors, say) gets no new warning from the + // artifact itself, ColumnsByField included; one that reads it is told to use the members. + [Fact] + public void The_deprecated_flattened_column_constant_warns_only_where_it_is_used() + { + var content = new NamesGenerator().Generate(Ctx(Load(FlattenedModel))).Single(f => f.Path == "ShipmentNames.g.cs").Content; + IEnumerable Warnings(string use) + { + var trees = new[] { content, "namespace Acme.Generated; public static class Use { public static string Read() => " + use + "; }" } + .Select(t => Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(t)); + var comp = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create("names_" + Guid.NewGuid().ToString("N"), trees, + DbContextCompileTests.BuildReferences(), + new Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary)); + var diagnostics = comp.GetDiagnostics(); + Assert.DoesNotContain(diagnostics, d => d.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error); + return diagnostics.Where(d => d.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Warning); + } + + Assert.Empty(Warnings("ShipmentNames.ShipToStreetColumn + ShipmentNames.ColumnsByField[\"shipTo\"] + ShipmentNames.PayloadColumn")); + var used = Assert.Single(Warnings("ShipmentNames.ShipToColumn")); + Assert.Equal("CS0618", used.Id); + Assert.Contains("use the member constants", used.GetMessage()); + } + [Fact] public void A_flattened_member_constant_that_collides_with_a_field_constant_is_left_out_with_a_warning() { diff --git a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs index 06405ce5f3..9a36fe8c73 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs @@ -101,7 +101,7 @@ public void Referenced_value_object_is_emitted_as_a_plain_poco() // `meta migrate` creates for the same model (core naming's ResolveFlattenedColumnPrefix). [Theory] [InlineData(ColumnNamingStrategy.Literal, "street", "Officestreet", "homeAddress_street")] - [InlineData(ColumnNamingStrategy.PascalCase, "Street", "OfficeStreet", "HomeAddress_Street")] + [InlineData(ColumnNamingStrategy.UpperFirst, "Street", "OfficeStreet", "HomeAddress_Street")] public void DbContext_flattened_columns_follow_column_prefix_and_the_column_rule( ColumnNamingStrategy strategy, string plain, string prefixed, string byDefault) { diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs index de02d50045..66313734d7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs @@ -187,8 +187,8 @@ public void A_duration_column_is_written_in_its_canonical_form_and_never_guarded { Assert.Contains("case TimeSpan ts: return new(Duration(ts), false);", Writer(DurationModel)); var h = Compile(new ReportExportGenerator(), model: DurationModel); - Assert.Equal("w\r\nPT26H\r\n-PT1M30S\r\nPT0.5S\r\nPT0S\r\n\r\n", - Csv(h, [[TimeSpan.FromHours(26)], [TimeSpan.FromSeconds(-90)], [TimeSpan.FromMilliseconds(500)], [TimeSpan.FromTicks(5)], [null]], "w")); + Assert.Equal("w\r\nPT26H\r\n-PT1M30S\r\nPT0.5S\r\nPT0.0000005S\r\nPT0S\r\n-PT256204778H48M5.4775808S\r\n\r\n", + Csv(h, [[TimeSpan.FromHours(26)], [TimeSpan.FromSeconds(-90)], [TimeSpan.FromMilliseconds(500)], [TimeSpan.FromTicks(5)], [TimeSpan.Zero], [TimeSpan.MinValue], [null]], "w")); Assert.Contains("-PT1M30S", Xml(h, [[TimeSpan.FromSeconds(-90)]], "w")); } diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index c6c1c60c8f..f51c93e554 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -455,7 +455,7 @@ public static string Column(MetaField field, ColumnNamingStrategy strategy = Col ColumnNamingStrategy.Literal => name, ColumnNamingStrategy.SnakeCase => ToSnakeCase(name), ColumnNamingStrategy.KebabCase => ToSnakeCase(name).Replace('_', '-'), - ColumnNamingStrategy.PascalCase => PhysicalNaming.ToPascalCaseColumn(name), + ColumnNamingStrategy.UpperFirst => PhysicalNaming.ToUpperFirstColumn(name), _ => name, }; diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 6261dd983c..4bcf22447b 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -482,7 +482,7 @@ private static int Unknown(string cmd) { ColumnNamingStrategy.SnakeCase => "snake_case", ColumnNamingStrategy.KebabCase => "kebab-case", - ColumnNamingStrategy.PascalCase => "PascalCase", + ColumnNamingStrategy.UpperFirst => "upperFirst", _ => "literal", }; @@ -810,12 +810,12 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) /// Every naming other than , in the order verify probes them (the /// Python port probes the same order): the used table rule first, so a different column /// rule alone is tried before a different table rule; within each, the used column rule - /// first, then snake_case, literal, kebab-case, PascalCase. + /// first, then snake_case, literal, kebab-case, upperFirst. /// private static IEnumerable NamingCandidates(PhysicalNaming used) { ColumnNamingStrategy[] columns = - [ColumnNamingStrategy.SnakeCase, ColumnNamingStrategy.Literal, ColumnNamingStrategy.KebabCase, ColumnNamingStrategy.PascalCase]; + [ColumnNamingStrategy.SnakeCase, ColumnNamingStrategy.Literal, ColumnNamingStrategy.KebabCase, ColumnNamingStrategy.UpperFirst]; TableNamingRule[] tables = [TableNamingRule.SnakeCase, TableNamingRule.Literal]; foreach (var t in tables.OrderBy(t => t == used.Tables ? 0 : 1)) foreach (var c in columns.OrderBy(c => c == used.Columns ? 0 : 1)) diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index d358b95bce..06b8fbb41f 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -276,8 +276,8 @@ public virtual IEnumerable Generate(GenContext ctx) // three emission sites, and had already been wrong twice: it undercounted them, and it // did not model jsonbObjectsOnly suppressing the flattened arm on a read model. if (modelLines.Any(l => l.Contains(MapJsonbHelperName))) EmitMapJsonbHelper(sb); - if (modelLines.Any(l => l.Contains(DurationIntervalHelperName + "."))) EmitDurationIntervalHelper(sb); sb.AppendLine("}"); + if (modelLines.Any(l => l.Contains(DurationIntervalHelperName + "."))) EmitDurationIntervalHelper(sb); return [new EmittedFile("AppDbContext.g.cs", sb.ToString())]; } @@ -1103,9 +1103,9 @@ private void EmitFieldTypeConfig( // field.duration — a System.TimeSpan. Npgsql maps it to the native `interval` (and an array // to `interval[]`), reading an interval with a month or year part as an error. Every other - // provider stores the canonical ISO-8601 string in a text column (the TS-owned SQLite / MySQL - // schemas), through the entity namespace's DurationWire; EF's own TimeSpan text ("01:30:00") - // would not be the cross-port form, and MySQL's `time` cannot hold more than 838 hours. + // provider stores a 64-bit count of microseconds in an integer column (the TS-owned SQLite / + // MySQL schemas), through the entity namespace's DurationWire; EF's own TimeSpan text + // ("01:30:00") does not order as the span, and MySQL's `time` cannot hold more than 838 hours. private static void AddDurationConfig( string className, MetaObject entity, IEnumerable fields, GenContext ctx, List modelLines) { @@ -1165,125 +1165,140 @@ private static string DurationMicrosConverter(MetaObject owner, GenContext ctx) // and adds the day part unchecked (so a day count past a TimeSpan wraps); this mapping reads the // value as NpgsqlInterval instead and refuses both. Npgsql is reached by reflection only, so the // generated context compiles, and runs, in a project with no Npgsql reference; the class is first - // touched in the Npgsql branch of OnModelCreating. - private static void EmitDurationIntervalHelper(StringBuilder sb) => sb.Append(DurationIntervalHelperSource); + // touched in the Npgsql branch of OnModelCreating. Emitted after the context class: the two + // mapping types must be public and top-level for a compiled model (`dotnet ef dbcontext + // optimize`), which re-creates a property's mapping as `.Default.Clone(...)` and + // refuses a nested or non-public one. DurationIntervalEfCoreTests (integration) gates LINQ, + // interval arithmetic and a compiled model against a live Postgres. + private static void EmitDurationIntervalHelper(StringBuilder sb) => sb.AppendLine(DurationIntervalHelperSource); private const string DurationIntervalHelperSource = """ - /// - /// field.duration on Npgsql: an interval column read through NpgsqlInterval, so a month - /// or year part, or a day count past what a TimeSpan holds, is refused rather than read wrong. - /// Npgsql is reached by reflection: a project on another provider needs no Npgsql reference. - /// - internal static class DurationInterval +/// +/// field.duration on Npgsql: an interval column read through NpgsqlInterval, so a month +/// or year part, or a day count past what a TimeSpan holds, is refused rather than read wrong. +/// Npgsql is reached by reflection: a project on another provider needs no Npgsql reference. +/// +internal static class DurationInterval +{ + // The Npgsql shape this mapping reads, resolved and checked when the model is built (the + // first touch is SetTypeMapping in OnModelCreating, or the first query on a compiled model), + // so a missing or changed type fails there, naming what is missing, rather than on a row. + internal static readonly System.Type IntervalType = Resolve(); + private static readonly System.Reflection.PropertyInfo Months = IntervalType.GetProperty("Months")!; + private static readonly System.Reflection.PropertyInfo Days = IntervalType.GetProperty("Days")!; + private static readonly System.Reflection.PropertyInfo Time = IntervalType.GetProperty("Time")!; + internal static readonly System.Reflection.MethodInfo GetFieldValue = + typeof(System.Data.Common.DbDataReader).GetMethod(nameof(System.Data.Common.DbDataReader.GetFieldValue))!; + + internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Mapping = DurationIntervalMapping.Default; + internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping ArrayMapping = DurationIntervalArrayMapping.Default; + + private static System.Type Resolve() { - // The Npgsql shape this mapping reads, resolved and checked when the model is built (the - // first touch is SetTypeMapping in OnModelCreating), so a missing or changed type fails - // there, naming what is missing, rather than on the first row read. - private static readonly System.Type IntervalType = Resolve(); - private static readonly System.Reflection.PropertyInfo Months = IntervalType.GetProperty("Months")!; - private static readonly System.Reflection.PropertyInfo Days = IntervalType.GetProperty("Days")!; - private static readonly System.Reflection.PropertyInfo Time = IntervalType.GetProperty("Time")!; - private static readonly System.Reflection.MethodInfo GetFieldValue = - typeof(System.Data.Common.DbDataReader).GetMethod(nameof(System.Data.Common.DbDataReader.GetFieldValue))!; - - internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Mapping = new ScalarMapping(); - internal static readonly Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping ArrayMapping = new ListMapping(); - - private static System.Type Resolve() - { - var type = System.Type.GetType(IntervalShape.TypeName, throwOnError: false); - if (IntervalShape.Problem(type) is { } problem) throw new System.InvalidOperationException(problem); - return type!; - } + var type = System.Type.GetType(IntervalShape.TypeName, throwOnError: false); + if (IntervalShape.Problem(type) is { } problem) throw new System.InvalidOperationException(problem); + return type!; + } - /// The check of the NpgsqlInterval shape, kept apart from the state above so it can run against any type. - internal static class IntervalShape - { - internal const string TypeName = "NpgsqlTypes.NpgsqlInterval, Npgsql"; + /// The check of the NpgsqlInterval shape, kept apart from the state above so it can run against any type. + internal static class IntervalShape + { + internal const string TypeName = "NpgsqlTypes.NpgsqlInterval, Npgsql"; - /// Null when has the shape the mapping reads, else a message naming what is missing. - internal static string? Problem(System.Type? type) + /// Null when has the shape the mapping reads, else a message naming what is missing. + internal static string? Problem(System.Type? type) + { + const string Lead = "field.duration on Npgsql: the generated DurationInterval mapping reads an interval column as " + + "NpgsqlTypes.NpgsqlInterval (an Int32 Months, an Int32 Days and an Int64 Time in microseconds; " + + "tested with Npgsql 8.0.5), but "; + if (type is null) return Lead + "no type NpgsqlTypes.NpgsqlInterval was found in the loaded Npgsql assembly."; + var missing = new System.Collections.Generic.List(); + foreach (var (name, want) in new[] { ("Months", typeof(int)), ("Days", typeof(int)), ("Time", typeof(long)) }) { - const string Lead = "field.duration on Npgsql: the generated DurationInterval mapping reads an interval column as " + - "NpgsqlTypes.NpgsqlInterval (an Int32 Months, an Int32 Days and an Int64 Time in microseconds; " + - "tested with Npgsql 8.0.5), but "; - if (type is null) return Lead + "no type NpgsqlTypes.NpgsqlInterval was found in the loaded Npgsql assembly."; - var missing = new System.Collections.Generic.List(); - foreach (var (name, want) in new[] { ("Months", typeof(int)), ("Days", typeof(int)), ("Time", typeof(long)) }) - { - var property = type.GetProperty(name); - if (property is null || property.PropertyType != want) - missing.Add(want.Name + " " + name); - } - return missing.Count == 0 - ? null - : Lead + type.FullName + " has no " + string.Join(", no ", missing) + " property. Check the Npgsql version the project references."; + var property = type.GetProperty(name); + if (property is null || property.PropertyType != want) + missing.Add(want.Name + " " + name); } + return missing.Count == 0 + ? null + : Lead + type.FullName + " has no " + string.Join(", no ", missing) + " property. Check the Npgsql version the project references."; } + } - /// An NpgsqlInterval as a TimeSpan: refused when it has a month or year part, or a span a TimeSpan cannot hold. - public static System.TimeSpan FromInterval(object interval) - { - if ((int)Months.GetValue(interval)! != 0) - throw new System.InvalidCastException("field.duration: the interval has a month or year part, so it is not a fixed-length span"); - var days = (int)Days.GetValue(interval)!; - var micros = (long)Time.GetValue(interval)!; - return System.TimeSpan.FromTicks(checked(days * System.TimeSpan.TicksPerDay + micros * 10)); - } + /// An NpgsqlInterval as a TimeSpan: refused when it has a month or year part, or a span a TimeSpan cannot hold. + public static System.TimeSpan FromInterval(object interval) + { + if ((int)Months.GetValue(interval)! != 0) + throw new System.InvalidCastException("field.duration: the interval has a month or year part, so it is not a fixed-length span"); + var days = (int)Days.GetValue(interval)!; + var micros = (long)Time.GetValue(interval)!; + return System.TimeSpan.FromTicks(checked(days * System.TimeSpan.TicksPerDay + micros * 10)); + } - /// An interval[] (an NpgsqlInterval array) as the list a duration array property holds. - public static System.Collections.Generic.IList FromIntervals(object intervals) - { - var list = new System.Collections.Generic.List(); - foreach (var interval in (System.Array)intervals) list.Add(FromInterval(interval!)); - return list; - } + /// An interval[] (an NpgsqlInterval array) as the list a duration array property holds. + public static System.Collections.Generic.IList FromIntervals(object intervals) + { + var list = new System.Collections.Generic.List(); + foreach (var interval in (System.Array)intervals) list.Add(FromInterval(interval!)); + return list; + } - // A span as Postgres interval input: [-]HH:MM:SS[.f], hours unbounded, no day part. - private static string Literal(System.TimeSpan value) - { - long micros = value.Ticks / 10; - bool negative = micros < 0; - long rest = negative ? -micros : micros; - long frac = rest % 1_000_000L, s = rest / 1_000_000L % 60, m = rest / 60_000_000L % 60, h = rest / 3_600_000_000L; - var text = h.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + ":" + m.ToString("00", System.Globalization.CultureInfo.InvariantCulture) - + ":" + s.ToString("00", System.Globalization.CultureInfo.InvariantCulture); - if (frac > 0) text += "." + frac.ToString("D6", System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0'); - return "INTERVAL '" + (negative ? "-" : "") + text + "'"; - } + // A span as Postgres interval input: [-]HH:MM:SS[.f], hours unbounded, no day part. The column + // holds microseconds, so sub-microsecond ticks are truncated toward zero. + internal static string Literal(System.TimeSpan value) + { + long micros = value.Ticks / 10; + bool negative = micros < 0; + ulong rest = negative ? (ulong)(-(micros + 1)) + 1UL : (ulong)micros; + ulong frac = rest % 1_000_000UL, s = rest / 1_000_000UL % 60, m = rest / 60_000_000UL % 60, h = rest / 3_600_000_000UL; + var text = h.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + ":" + m.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + + ":" + s.ToString("00", System.Globalization.CultureInfo.InvariantCulture); + if (frac > 0) text += "." + frac.ToString("D6", System.Globalization.CultureInfo.InvariantCulture).TrimEnd('0'); + return "INTERVAL '" + (negative ? "-" : "") + text + "'"; + } +} - private sealed class ScalarMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping - { - public ScalarMapping() : base("interval", typeof(System.TimeSpan)) { } - private ScalarMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } - protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new ScalarMapping(parameters); - public override System.Reflection.MethodInfo GetDataReaderMethod() => GetFieldValue.MakeGenericMethod(IntervalType); - public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => - System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(FromInterval))!, - System.Linq.Expressions.Expression.Convert(expression, typeof(object))); - protected override string GenerateNonNullSqlLiteral(object value) => Literal((System.TimeSpan)value); - } +/// The type mapping of a field.duration column on Npgsql (an interval, read through ). +public sealed class DurationIntervalMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping +{ + public static DurationIntervalMapping Default { get; } = new(); + + public DurationIntervalMapping() : base("interval", typeof(System.TimeSpan)) { } + private DurationIntervalMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new DurationIntervalMapping(parameters); + public override System.Reflection.MethodInfo GetDataReaderMethod() => DurationInterval.GetFieldValue.MakeGenericMethod(DurationInterval.IntervalType); + public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => + System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(DurationInterval.FromInterval))!, + System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => DurationInterval.Literal((System.TimeSpan)value); +} - private sealed class ListMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping - { - private static readonly Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer> ListComparer = new( - (a, b) => a == null ? b == null : b != null && System.Linq.Enumerable.SequenceEqual(a, b), - v => System.Linq.Enumerable.Aggregate(v, 0, (h, e) => System.HashCode.Combine(h, e)), - v => System.Linq.Enumerable.ToList(v)); - - public ListMapping() : base(new RelationalTypeMappingParameters( - new CoreTypeMappingParameters(typeof(System.Collections.Generic.IList), comparer: ListComparer, keyComparer: ListComparer), "interval[]")) { } - private ListMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } - protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new ListMapping(parameters); - public override System.Reflection.MethodInfo GetDataReaderMethod() => GetFieldValue.MakeGenericMethod(IntervalType.MakeArrayType()); - public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => - System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(FromIntervals))!, - System.Linq.Expressions.Expression.Convert(expression, typeof(object))); - protected override string GenerateNonNullSqlLiteral(object value) => - "ARRAY[" + string.Join(",", System.Linq.Enumerable.Select((System.Collections.Generic.IEnumerable)value, Literal)) + "]::interval[]"; - } - } +/// The type mapping of an @isArray field.duration column on Npgsql (an interval[]). +public sealed class DurationIntervalArrayMapping : Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping +{ + private static readonly Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer> ListComparer = new( + (a, b) => a == null ? b == null : b != null && System.Linq.Enumerable.SequenceEqual(a, b), + v => System.Linq.Enumerable.Aggregate(v, 0, (h, e) => System.HashCode.Combine(h, e)), + v => System.Linq.Enumerable.ToList(v)); + + // After ListComparer: static initializers run in declaration order. The element mapping is the + // scalar one, which is what lets EF query the column as a primitive collection (Contains, Count, + // Any): a compiled model carries only what the mapping itself names. + public static DurationIntervalArrayMapping Default { get; } = new(); + + public DurationIntervalArrayMapping() : base(new RelationalTypeMappingParameters( + new CoreTypeMappingParameters(typeof(System.Collections.Generic.IList), comparer: ListComparer, keyComparer: ListComparer, + elementMapping: DurationIntervalMapping.Default), "interval[]")) { } + private DurationIntervalArrayMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } + protected override Microsoft.EntityFrameworkCore.Storage.RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new DurationIntervalArrayMapping(parameters); + public override System.Reflection.MethodInfo GetDataReaderMethod() => DurationInterval.GetFieldValue.MakeGenericMethod(DurationInterval.IntervalType.MakeArrayType()); + public override System.Linq.Expressions.Expression CustomizeDataReaderExpression(System.Linq.Expressions.Expression expression) => + System.Linq.Expressions.Expression.Call(typeof(DurationInterval).GetMethod(nameof(DurationInterval.FromIntervals))!, + System.Linq.Expressions.Expression.Convert(expression, typeof(object))); + protected override string GenerateNonNullSqlLiteral(object value) => + "ARRAY[" + string.Join(",", System.Linq.Enumerable.Select((System.Collections.Generic.IEnumerable)value, DurationInterval.Literal)) + "]::interval[]"; +} """; // The EF Core provider name Npgsql registers (DbContext.Database.ProviderName). @@ -1372,7 +1387,7 @@ private static bool HoldsMap(MetaObject vo, MetaRoot root, HashSet s // else `_`, then the member's own column — the same function // migrate-ts names these columns with, and TS owns the schema (ADR-0015). It is NOT EF's // own owned-type default, `
    __chk` (enum), `_numeric_chk`, `_length_chk`, `_regex_chk`, `_cmp_chk`, `_reqwhen_chk`, `_presentiff_chk`, `_atleastone_chk`; a declared `@constraintName` replaces the name and is kept even where `skipRedundant` would leave the CHECK out; +- `@dbCheck: false` leaves a validator's or an enum's CHECK out, under `skipRedundant` too + (`npi`, `legacyState`, `rank`'s minimum, `legacyWindow`); a sibling validator on the same field + keeps its own (`rank`'s maximum), and `@dbCheck: true` is the default (`floor`); - comparisons, not `BETWEEN`; columns double-quoted; an int-backed enum lists its integers; a duration literal is the interval text on Postgres and microseconds on SQLite; - no CHECK on an array column, and none on a derived (origin-bearing) field — it has no column — diff --git a/fixtures/check-constraint-conformance/expected.d1.json b/fixtures/check-constraint-conformance/expected.d1.json index 6c2f99305e..76c725c34a 100644 --- a/fixtures/check-constraint-conformance/expected.d1.json +++ b/fixtures/check-constraint-conformance/expected.d1.json @@ -36,6 +36,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" diff --git a/fixtures/check-constraint-conformance/expected.postgres.json b/fixtures/check-constraint-conformance/expected.postgres.json index 3c3ff6c9bc..3cd7745287 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.json +++ b/fixtures/check-constraint-conformance/expected.postgres.json @@ -40,6 +40,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" diff --git a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json index f4290aa53e..ac9f084b56 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json @@ -40,6 +40,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" diff --git a/fixtures/check-constraint-conformance/expected.sqlite.json b/fixtures/check-constraint-conformance/expected.sqlite.json index 6c2f99305e..76c725c34a 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.json @@ -36,6 +36,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" diff --git a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json index 07d2386050..27207ec778 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json @@ -36,6 +36,10 @@ "name": "gadgets_ref_fits", "expression": "length(\"ref\") <= 10" }, + { + "name": "gadgets_rank_numeric_chk", + "expression": "\"rank\" <= 99" + }, { "name": "gadgets_starts_at_cmp_chk", "expression": "\"starts_at\" <= \"ends_at\"" diff --git a/fixtures/check-constraint-conformance/input/meta.checks.json b/fixtures/check-constraint-conformance/input/meta.checks.json index 971fd1047e..e48f73e581 100644 --- a/fixtures/check-constraint-conformance/input/meta.checks.json +++ b/fixtures/check-constraint-conformance/input/meta.checks.json @@ -13,7 +13,7 @@ { "field.enum": { "name": "tags", "isArray": true, "@values": ["A", "B"] } }, { "field.string": { "name": "kind", "@required": true } }, { "field.int": { "name": "score", "children": [ { "validator.numeric": { "@min": 1, "@max": 5 } } ] } }, - { "field.int": { "name": "floor", "children": [ { "validator.numeric": { "@min": 0 } } ] } }, + { "field.int": { "name": "floor", "children": [ { "validator.numeric": { "@min": 0, "@dbCheck": true } } ] } }, { "field.string": { "name": "code", "@maxLength": 10, "children": [ { "validator.length": { "@min": 2, "@max": 20 } } ] } }, { "field.string": { "name": "label", "@maxLength": 40, "children": [ { "validator.length": { "@min": 0, "@max": 30 } } ] } }, { "field.string": { "name": "sku", "children": [ { "validator.regex": { "@pattern": "^[A-Z]{3}-'\\d+$", "@constraintName": "gadgets_sku_shape" } } ] } }, @@ -29,6 +29,13 @@ { "field.string": { "name": "fax" } }, { "field.enum": { "name": "channel", "@values": ["EMAIL", "SMS"], "children": [ { "validator.length": { "@min": 1, "@max": 5 } } ] } }, { "field.string": { "name": "ref", "@maxLength": 10, "children": [ { "validator.length": { "@max": 10, "@constraintName": "gadgets_ref_fits" } } ] } }, + { "field.string": { "name": "npi", "children": [ + { "validator.regex": { "name": "tenDigits", "@pattern": "^\\d{10}$", "@dbCheck": false } }, + { "validator.length": { "name": "npiLength", "@max": 12, "@dbCheck": false } } ] } }, + { "field.enum": { "name": "legacyState", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, + { "field.int": { "name": "rank", "children": [ + { "validator.numeric": { "name": "rankFloor", "@min": 1, "@dbCheck": false } }, + { "validator.numeric": { "name": "rankCeiling", "@max": 99 } } ] } }, { "field.string": { "name": "band", "children": [ { "validator.length": { "@max": 4 } }, { "origin.computed": { "@expr": { "case": [ { "when": { "op": "gte", "left": { "field": "score" }, "right": { "value": 4 } }, "then": { "value": "HIGH" } } ], @@ -45,7 +52,8 @@ { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@max": 1 } }, { "validator.atLeastOne": { "name": "anyContact", "@fields": ["phone", "fax"], "@condition": { "op": "eq", "left": { "field": "level" }, "right": { "value": "HIGH" } } } }, - { "validator.requiredWhen": { "name": "bandFax", "@field": "fax", "@when": "band", "@equals": "HIGH" } } + { "validator.requiredWhen": { "name": "bandFax", "@field": "fax", "@when": "band", "@equals": "HIGH" } }, + { "validator.comparison": { "name": "legacyWindow", "@left": "startsAt", "@op": "lt", "@right": "endsAt", "@dbCheck": false } } ] } }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index f7ce951729..de13830e7b 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -55,6 +55,7 @@ "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", + "ERR_CONSTRAINT_NAME_WITHOUT_CHECK": "A CHECK-generating validator (numeric, length, regex, comparison, requiredWhen, presentIff, atLeastOne) or a field.enum sets @dbCheck: false, which generates no database CHECK, and @constraintName, which names that CHECK. With no CHECK there is nothing to name, so the node is refused rather than one of the two silently ignored.", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", diff --git a/fixtures/conformance/error-db-check-constraint-name/expected-errors.json b/fixtures/conformance/error-db-check-constraint-name/expected-errors.json new file mode 100644 index 0000000000..57beb78b35 --- /dev/null +++ b/fixtures/conformance/error-db-check-constraint-name/expected-errors.json @@ -0,0 +1,25 @@ +{ + "errors": [ + { + "code": "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['field.enum']" + } + }, + { + "code": "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[3]['field.string'].children[0]['validator.regex']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-db-check-constraint-name/input/meta.checks.json b/fixtures/conformance/error-db-check-constraint-name/input/meta.checks.json new file mode 100644 index 0000000000..da1ac33e40 --- /dev/null +++ b/fixtures/conformance/error-db-check-constraint-name/input/meta.checks.json @@ -0,0 +1,21 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Provider", + "children": [ + { "source.rdb": { "@table": "providers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false, "@constraintName": "providers_state_ok" } }, + { "field.string": { "name": "npi", "children": [ + { "validator.regex": { "name": "tenDigits", "@pattern": "^\\d{10}$", "@dbCheck": false, "@constraintName": "providers_npi_shape" } } + ] } }, + { "identity.primary": { "name": "pk", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/validator-db-check/expected.json b/fixtures/conformance/validator-db-check/expected.json new file mode 100644 index 0000000000..b4fb1458fc --- /dev/null +++ b/fixtures/conformance/validator-db-check/expected.json @@ -0,0 +1,141 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Provider", + "children": [ + { + "source.rdb": { + "@table": "providers" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "state", + "@dbCheck": false, + "@values": [ + "OPEN", + "SHUT" + ] + } + }, + { + "field.string": { + "name": "npi", + "children": [ + { + "validator.regex": { + "name": "tenDigits", + "@dbCheck": false, + "@pattern": "^\\d{10}$" + } + }, + { + "validator.length": { + "name": "npiLength", + "@constraintName": "providers_npi_fits", + "@dbCheck": true, + "@max": 12 + } + } + ] + } + }, + { + "field.int": { + "name": "rank", + "children": [ + { + "validator.numeric": { + "name": "rankRange", + "@dbCheck": false, + "@max": 99, + "@min": 1 + } + } + ] + } + }, + { + "field.string": { + "name": "kind" + } + }, + { + "field.string": { + "name": "email" + } + }, + { + "field.string": { + "name": "phone" + } + }, + { + "field.timestamp": { + "name": "startsAt" + } + }, + { + "field.timestamp": { + "name": "endsAt" + } + }, + { + "identity.primary": { + "name": "pk", + "@fields": [ + "id" + ] + } + }, + { + "validator.comparison": { + "name": "window", + "@dbCheck": false, + "@left": "startsAt", + "@op": "lte", + "@right": "endsAt" + } + }, + { + "validator.requiredWhen": { + "name": "clinicEmail", + "@dbCheck": false, + "@equals": "clinic", + "@field": "email", + "@when": "kind" + } + }, + { + "validator.presentIff": { + "name": "clinicStart", + "@dbCheck": false, + "@equals": "clinic", + "@field": "startsAt", + "@when": "kind" + } + }, + { + "validator.atLeastOne": { + "name": "contact", + "@dbCheck": false, + "@fields": [ + "email", + "phone" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/validator-db-check/input/meta.checks.json b/fixtures/conformance/validator-db-check/input/meta.checks.json new file mode 100644 index 0000000000..6736ec95f0 --- /dev/null +++ b/fixtures/conformance/validator-db-check/input/meta.checks.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Provider", + "children": [ + { "source.rdb": { "@table": "providers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, + { "field.string": { "name": "npi", "children": [ + { "validator.regex": { "name": "tenDigits", "@pattern": "^\\d{10}$", "@dbCheck": false } }, + { "validator.length": { "name": "npiLength", "@max": 12, "@dbCheck": true, "@constraintName": "providers_npi_fits" } } + ] } }, + { "field.int": { "name": "rank", "children": [ { "validator.numeric": { "name": "rankRange", "@min": 1, "@max": 99, "@dbCheck": false } } ] } }, + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "email" } }, + { "field.string": { "name": "phone" } }, + { "field.timestamp": { "name": "startsAt" } }, + { "field.timestamp": { "name": "endsAt" } }, + { "identity.primary": { "name": "pk", "@fields": "id" } }, + { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": false } }, + { "validator.requiredWhen": { "name": "clinicEmail", "@field": "email", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, + { "validator.presentIff": { "name": "clinicStart", "@field": "startsAt", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, + { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": false } } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index fd6e81c625..2fa1e8467c 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -67,7 +67,7 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `field.decimal`: `@column`, `@db.indexed`, `@dbColumnType` - `field.double`: `@column`, `@db.indexed`, `@dbColumnType` - `field.duration`: `@column`, `@db.indexed`, `@dbColumnType` -- `field.enum`: `@column`, `@constraintName`, `@db.indexed`, `@dbColumnType` +- `field.enum`: `@column`, `@constraintName`, `@db.indexed`, `@dbCheck`, `@dbColumnType` - `field.float`: `@column`, `@db.indexed`, `@dbColumnType` - `field.inet`: `@column`, `@db.indexed`, `@dbColumnType` - `field.int`: `@column`, `@db.indexed`, `@dbColumnType` @@ -84,13 +84,13 @@ DB-domain attributes — @column / @db.indexed / @dbColumnType on every field, @ - `identity.secondary`: `@expr`, `@orders`, `@using`, `@where` - `index.lookup`: `@expr`, `@orders`, `@using`, `@where` - `source.rdb`: `@function`, `@kind`, `@materializedView`, `@parameterRef`, `@proc`, `@role`, `@schema`, `@sql`, `@table`, `@unmanaged`, `@view` -- `validator.atLeastOne`: `@constraintName` -- `validator.comparison`: `@constraintName` -- `validator.length`: `@constraintName` -- `validator.numeric`: `@constraintName` -- `validator.presentIff`: `@constraintName` -- `validator.regex`: `@constraintName` -- `validator.requiredWhen`: `@constraintName` +- `validator.atLeastOne`: `@constraintName`, `@dbCheck` +- `validator.comparison`: `@constraintName`, `@dbCheck` +- `validator.length`: `@constraintName`, `@dbCheck` +- `validator.numeric`: `@constraintName`, `@dbCheck` +- `validator.presentIff`: `@constraintName`, `@dbCheck` +- `validator.regex`: `@constraintName`, `@dbCheck` +- `validator.requiredWhen`: `@constraintName`, `@dbCheck` ## metaobjects-documentation diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index d26330c317..eafe7abc08 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -265,6 +265,7 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@enumAlias` | properties | no | | | metaobjects-prompt | Map of alternate/off-vocabulary tokens to canonical enum members; feeds the FR-010 tolerant extract alias-fold. | diff --git a/fixtures/metamodel-docs/expected/types/validator.md b/fixtures/metamodel-docs/expected/types/validator.md index 3a2e9ce293..9e147b28af 100644 --- a/fixtures/metamodel-docs/expected/types/validator.md +++ b/fixtures/metamodel-docs/expected/types/validator.md @@ -45,6 +45,7 @@ Cardinality of presence: at least one of the named fields (@fields) must be pres | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@fields` | string[] | yes | | | metaobjects-core-types | Names of the candidate fields; at least one must be present. | | `@max` | int | no | | | metaobjects-core-types | The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE). | @@ -85,6 +86,7 @@ Cross-field ordering: requires two sibling fields of the owning entity stand in | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@left` | string | yes | | | metaobjects-core-types | Name of the left-hand field of the owning entity. | | `@op` | string | yes | | `gt`, `gte`, `lt`, `lte`, `ne`, `eq` | metaobjects-core-types | Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=). | | `@right` | string | yes | | | metaobjects-core-types | Name of the right-hand field of the owning entity. | @@ -106,6 +108,7 @@ Bounds string length / collection size via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -126,6 +129,7 @@ Bounds a numeric value's magnitude via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -149,6 +153,7 @@ Biconditional presence: the target field (@field) is present (NOT NULL) if and o | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; @field is present exactly when @when equals this. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field whose presence is governed by the condition. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field. | @@ -170,6 +175,7 @@ Requires the value match a regular expression (@pattern). | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@pattern` | string | no | | | metaobjects-core-types | Regular expression the value must match. | @@ -210,6 +216,7 @@ One-directional conditional presence: when the gating field (@when) equals @equa | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; when @when equals this, @field must be present. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field that becomes required when the condition holds. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field whose value triggers the requirement. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 5a8a5011b9..8890375c42 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1201,6 +1201,13 @@ "required": false, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "dbColumnType", "valueType": "string", @@ -5024,6 +5031,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "fields", "valueType": "string", @@ -5084,6 +5098,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "left", "valueType": "string", @@ -5129,6 +5150,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -5159,6 +5187,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -5197,6 +5232,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "equals", "valueType": "string", @@ -5234,6 +5276,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "max", "valueType": "int", @@ -5287,6 +5336,13 @@ "required": false, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { + "name": "dbCheck", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + }, { "name": "equals", "valueType": "string", diff --git a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs index 4845583adb..4e3580b90a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs @@ -78,6 +78,12 @@ public void The_context_declares_each_check_on_its_table() Assert.Contains("modelBuilder.Entity().ToTable(t => t.HasCheckConstraint(\"gadgets_status_chk\", \"\\\"status\\\" IN ('DRAFT', 'LIVE')\"));", context); Assert.Contains("t.HasCheckConstraint(\"gadgets_sku_shape\", ", context); Assert.Contains("t.HasCheckConstraint(\"gadgets_email_atleastone_chk\", \"num_nonnulls(\\\"email\\\", \\\"phone\\\") = 1\")", context); + // rc.20 @dbCheck: false — the opted-out validators and enum declare no CHECK; a sibling + // validator on the same field keeps its own. + Assert.DoesNotContain("gadgets_npi_", context); + Assert.DoesNotContain("gadgets_legacy_state_chk", context); + Assert.DoesNotContain("\\\"rank\\\" >= 1", context); + Assert.Contains("t.HasCheckConstraint(\"gadgets_rank_numeric_chk\", \"\\\"rank\\\" <= 99\")", context); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index f530ab264e..7c27152db5 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -54,7 +54,8 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co if (field.IsDerived()) continue; var col = CSharpNaming.Column(field, strategy); var qcol = Quote(col); - if (field.SubType == FIELD_SUBTYPE_ENUM && field.EffectiveEnumValues is { Count: > 0 } values) + // @dbCheck: false (resolving) asks for no CHECK: the rule is enforced app-side only. + if (field.SubType == FIELD_SUBTYPE_ENUM && !OptedOut(field) && field.EffectiveEnumValues is { Count: > 0 } values) { var ints = field.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; var members = ints is null @@ -70,6 +71,7 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co var enforcedMax = config.SkipRedundantChecks && !IsSqlite(dialect) ? VarcharLength(field) : null; foreach (var v in field.Validators()) { + if (OptedOut(v)) continue; // A declared @constraintName asks for the CHECK by name, so it is kept even where // skipRedundant would leave it out: a declaration beats a default. var declared = DeclaredName(v) is not null; @@ -80,12 +82,17 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co } foreach (var v in entity.Validators()) { + if (OptedOut(v)) continue; if (CrossFieldCheck(v, entity, table, strategy, dialect) is { } check) checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); } return checks; } + /// Whether a validator or field.enum opts out of its CHECK (@dbCheck: false, resolving). + /// SkipRedundantChecks is independent of it: it only ever leaves more out. + private static bool OptedOut(MetaData node) => node.Attr(VALIDATOR_ATTR_DB_CHECK) is false; + /// The length a string column's VARCHAR(n) enforces: a string's @maxLength, a string-stored enum's resolved length. private static long? VarcharLength(MetaField field) => field.SubType switch { diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs index f957d03cfd..5e5763dc81 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs @@ -53,6 +53,8 @@ public static class ValidatorConstants public const string VALIDATOR_ATTR_CONDITION = "condition"; /// A CHECK-generating validator (db provider): the database name of that CHECK. public const string VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName"; + /// A CHECK-generating validator or field.enum (db provider): false generates no database CHECK. Absent: true. + public const string VALIDATOR_ATTR_DB_CHECK = "dbCheck"; /// The validators meta migrate renders as a CHECK (and so may carry @constraintName): /// numeric, length, regex and the cross-field ones. required is NOT NULL; array and base have none. diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 67758cb3c4..2eb5871eb4 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -308,6 +308,8 @@ public enum ErrorCode ERR_SEQUENCE_WITHOUT_INCREMENT, // identity.primary @sequenceStart below 1, or past what its key field can hold. ERR_SEQUENCE_START_OUT_OF_RANGE, + // A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. + ERR_CONSTRAINT_NAME_WITHOUT_CHECK, } /// diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 2694cfc92f..847b4ce27c 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -540,6 +540,7 @@ public LoadResult Load(IReadOnlyList sources) errors.AddRange(ValidationPasses.ValidateEnumMaxLength(root)); errors.AddRange(ValidationPasses.ValidateIdentitySequence(root)); errors.AddRange(ValidationPasses.ValidateCrossFieldValidators(root)); + errors.AddRange(ValidationPasses.ValidateDbCheck(root)); // Pass 9: template @payloadRef / @requiredSlots resolution errors.AddRange(ValidationPasses.ValidateTemplatePayloadRefs(root)); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 8b7d8f8220..af76acfceb 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2539,6 +2539,38 @@ public static IReadOnlyList ValidateIdentitySequence(MetaData root) return errors; } + // --------------------------------------------------------------------------- + // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no + // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the + // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). Read RESOLVING (ADR-0039), reported on + // each node that declares either of the two itself. Mirrors TS validateDbCheck. + // --------------------------------------------------------------------------- + public static IReadOnlyList ValidateDbCheck(MetaData root) + { + var errors = new List(); + const string dbCheck = MetaObjects.Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK; + const string constraintName = MetaObjects.Core.Validator.ValidatorConstants.VALIDATOR_ATTR_CONSTRAINT_NAME; + void Visit(MetaData node, string? owner) + { + var checkedNode = (node.Type == TYPE_VALIDATOR && MetaObjects.Core.Validator.ValidatorConstants.CHECK_VALIDATOR_SUBTYPES.Contains(node.SubType)) + || (node.Type == TYPE_FIELD && node.SubType == FIELD_SUBTYPE_ENUM); + if (checkedNode && (node.OwnAttr(dbCheck) is not null || node.OwnAttr(constraintName) is not null) + && node.Attr(dbCheck) is false && node.Attr(constraintName) is string { Length: > 0 } name) + { + var label = $"{node.Type}.{node.SubType} \"{(owner is null ? "" : owner + ".")}{node.Name}\""; + errors.Add(new MetaError( + $"{label} sets @dbCheck: false and @constraintName \"{name}\"; with no CHECK there is nothing for the name to name. " + + "Remove @constraintName, or remove @dbCheck: false.", + ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + Envelope: node.Source)); + } + var next = node.Type == TYPE_OBJECT || node.Type == TYPE_FIELD ? node.Name : owner; + foreach (var child in node.OwnChildren()) Visit(child, next); + } + foreach (var child in root.OwnChildren()) Visit(child, null); + return errors; + } + // --------------------------------------------------------------------------- // field.enum @maxLength — the column length of a string-stored enum: // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the diff --git a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs index 300a7dc76c..e5c9b960e7 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbProvider.cs @@ -57,13 +57,13 @@ public void RegisterTypes(TypeRegistry registry) registry.Extend( MetaObjects.Shared.BaseTypes.TYPE_FIELD, FieldConstants.FIELD_SUBTYPE_ENUM, - attributes: [DbSchema.EnumConstraintNameSchema]); + attributes: [DbSchema.EnumConstraintNameSchema, DbSchema.EnumDbCheckSchema]); foreach (string subType in Core.Validator.ValidatorConstants.CHECK_VALIDATOR_SUBTYPES) { registry.Extend( MetaObjects.Shared.BaseTypes.TYPE_VALIDATOR, subType, - attributes: [DbSchema.ValidatorConstraintNameSchema]); + attributes: [DbSchema.ValidatorConstraintNameSchema, DbSchema.ValidatorDbCheckSchema]); } // @flattenedColumnPrefix is field.object-ONLY (the flattened-member column prefix), mirroring diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index 7a13df2191..8a4cb9df0f 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -111,6 +111,20 @@ public static class DbSchema Required: false, Description: "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider."); + /// @dbCheck on a validator — false generates no database CHECK for it. + public static readonly AttrSchema ValidatorDbCheckSchema = new AttrSchema( + Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK, + ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, + Required: false, + Description: "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider."); + + /// @dbCheck on a field.enum — false generates no membership CHECK. + public static readonly AttrSchema EnumDbCheckSchema = new AttrSchema( + Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK, + ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, + Required: false, + Description: "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider."); + /// @constraintName on a field.enum — the database name of its membership CHECK. public static readonly AttrSchema EnumConstraintNameSchema = new AttrSchema( Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_CONSTRAINT_NAME, diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index e1d1cb0327..47ab036326 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -63,14 +63,16 @@ "type": "field", "subType": "enum", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { "type": "validator", "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 6ada0df2e9..0c97e6542c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -299,6 +299,8 @@ public enum ErrorCode { ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP, ERR_SEQUENCE_WITHOUT_INCREMENT, ERR_SEQUENCE_START_OUT_OF_RANGE, + /** A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. */ + ERR_CONSTRAINT_NAME_WITHOUT_CHECK, /** @storage was set on a field that has no @objectRef. */ ERR_STORAGE_WITHOUT_OBJECT_REF, diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java index f16630f29c..1fc244795c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java @@ -164,6 +164,10 @@ public void registerTypes(MetaDataRegistry registry) { registry.extendType(c, def -> def .optionalAttributeWithConstraints(com.metaobjects.validator.MetaValidator.ATTR_CONSTRAINT_NAME) .ofType(StringAttribute.SUBTYPE_STRING).asSingle()); + // @dbCheck: false asks the same node for no CHECK at all (rc.20). + registry.extendType(c, def -> def + .optionalAttributeWithConstraints(com.metaobjects.validator.MetaValidator.ATTR_DB_CHECK) + .ofType(com.metaobjects.attr.BooleanAttribute.SUBTYPE_BOOLEAN).asSingle()); } // --- index.lookup RDB-physical attrs --- diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index f510a1909c..b0f2f6ed2b 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -265,6 +265,7 @@ public static void run(MetaRoot root, MetaDataLoader loader) { validateEnumMaxLength(root, collected); validateIdentitySequence(root, collected); validateCrossFieldValidators(root, collected); + validateDbCheck(root, collected); pass(collected, () -> validateFieldMap(root)); pass(collected, () -> validateIdentityFieldsAndGeneration(root)); // FR-024 B3/B4a — subtype rules (identity-name, value purity, projection licensing). @@ -2566,6 +2567,44 @@ static void validateIdentitySequence(MetaRoot root, List out) } } + // ========================================================================= + // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no + // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the + // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). Read RESOLVING (ADR-0039), reported on + // each node that declares either of the two itself. Mirrors TS validateDbCheck. + // ========================================================================= + + private static final java.util.Set DB_CHECK_VALIDATOR_SUBTYPES = java.util.Set.of( + "numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"); + + static void validateDbCheck(MetaRoot root, List out) { + for (MetaData child : root.getChildren(MetaData.class, false)) visitDbCheck(child, null, out); + } + + private static void visitDbCheck(MetaData node, String owner, List out) { + if (node instanceof com.metaobjects.attr.MetaAttribute) return; + String dbCheck = com.metaobjects.validator.MetaValidator.ATTR_DB_CHECK; + String constraintName = com.metaobjects.validator.MetaValidator.ATTR_CONSTRAINT_NAME; + boolean checked = ("validator".equals(node.getType()) && DB_CHECK_VALIDATOR_SUBTYPES.contains(node.getSubType())) + || ("field".equals(node.getType()) && "enum".equals(node.getSubType())); + if (checked && (node.hasMetaAttr(dbCheck, false) || node.hasMetaAttr(constraintName, false)) + && node.hasMetaAttr(dbCheck) && node.hasMetaAttr(constraintName)) { + boolean off = "false".equalsIgnoreCase(String.valueOf(node.getMetaAttr(dbCheck).getValue())); + String name = node.getMetaAttr(constraintName).getValueAsString(); + if (off && name != null && !name.isEmpty()) { + String label = node.getType() + "." + node.getSubType() + " \"" + (owner == null ? "" : owner + ".") + + node.getShortName() + "\""; + out.add(new MetaDataException( + ErrorMessageConstants.ERR_CONSTRAINT_NAME_WITHOUT_CHECK + + ": " + label + " sets @dbCheck: false and @constraintName \"" + name + "\"; with no CHECK" + + " there is nothing for the name to name. Remove @constraintName, or remove @dbCheck: false.", + ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, node.getSource())); + } + } + String next = ("object".equals(node.getType()) || "field".equals(node.getType())) ? node.getShortName() : owner; + for (MetaData child : node.getChildren(MetaData.class, false)) visitDbCheck(child, next, out); + } + /** Every offending enum is reported, as the other ports do, not only the first. */ static void validateEnumMaxLength(MetaData node, List out) { for (MetaData child : node.getChildren(MetaData.class, false)) { diff --git a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java index 2771809b23..3b1bdc90bb 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java +++ b/server/java/metadata/src/main/java/com/metaobjects/util/ErrorMessageConstants.java @@ -204,6 +204,13 @@ private ErrorMessageConstants() { */ public static final String ERR_SEQUENCE_START_OUT_OF_RANGE = "ERR_SEQUENCE_START_OUT_OF_RANGE"; + /** + * A CHECK-generating validator or {@code field.enum} sets {@code @dbCheck: false} (no CHECK) and + * {@code @constraintName} (the CHECK's name). Cross-language contract: + * {@code ERR_CONSTRAINT_NAME_WITHOUT_CHECK}. + */ + public static final String ERR_CONSTRAINT_NAME_WITHOUT_CHECK = "ERR_CONSTRAINT_NAME_WITHOUT_CHECK"; + /** * Error code emitted when {@code field.object @storage} is set on a field that * has no {@code @objectRef} — storage shape only applies to referenced objects. diff --git a/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java b/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java index c0ba1630c3..58aa9ee45e 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java +++ b/server/java/metadata/src/main/java/com/metaobjects/validator/MetaValidator.java @@ -48,6 +48,8 @@ public abstract class MetaValidator extends MetaData { /** The database name of the CHECK a CHECK-generating validator (or a field.enum's membership) generates. */ public final static String ATTR_CONSTRAINT_NAME = "constraintName"; + /** A CHECK-generating validator or field.enum (db provider): {@code false} generates no database CHECK. Absent: true. */ + public final static String ATTR_DB_CHECK = "dbCheck"; /** * Register this type with the MetaDataRegistry (called by provider) diff --git a/server/python/src/metaobjects/errors.py b/server/python/src/metaobjects/errors.py index 2bb2e75755..df90e50d58 100644 --- a/server/python/src/metaobjects/errors.py +++ b/server/python/src/metaobjects/errors.py @@ -209,6 +209,8 @@ class ErrorCode(str, Enum): ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP = "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP" ERR_SEQUENCE_WITHOUT_INCREMENT = "ERR_SEQUENCE_WITHOUT_INCREMENT" ERR_SEQUENCE_START_OUT_OF_RANGE = "ERR_SEQUENCE_START_OUT_OF_RANGE" + # A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. + ERR_CONSTRAINT_NAME_WITHOUT_CHECK = "ERR_CONSTRAINT_NAME_WITHOUT_CHECK" ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE = ( "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE" ) diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 6ccb221652..7eb5567a13 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -258,6 +258,8 @@ def run_validations( _validate_identity_sequence(root, errors) # cross-field validators — atLeastOne @max in range; @condition names entity fields. _validate_cross_field_validators(root, errors) + # @dbCheck: false with @constraintName names a CHECK that is never created. + _validate_db_check(root, errors) # field.map — exactly one of @valueType (scalar) or @objectRef (VO), and # @valueType (when set) must name a known scalar subtype. _validate_field_map(root, errors) @@ -3761,6 +3763,48 @@ def _validate_identity_sequence(root: MetaData, errors: list[MetaError]) -> None )) +# @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no +# database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the +# node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). Read RESOLVING (ADR-0039), reported on +# each node that declares either of the two itself. Mirrors TS validateDbCheck. +def _validate_db_check(root: MetaData, errors: list[MetaError]) -> None: + from ..meta.core.field import field_constants as fc + from ..meta.core.validator import validator_constants as vc + + checked_validators = ( + vc.VALIDATOR_SUBTYPE_NUMERIC, + vc.VALIDATOR_SUBTYPE_LENGTH, + vc.VALIDATOR_SUBTYPE_REGEX, + *vc.CROSS_FIELD_VALIDATOR_SUBTYPES, + ) + + def visit(node: MetaData, owner: str | None) -> None: + checked = (node.type == TYPE_VALIDATOR and node.sub_type in checked_validators) or ( + node.type == TYPE_FIELD and node.sub_type == fc.FIELD_SUBTYPE_ENUM + ) + # ADR-0039 sanctioned own: reported where the node declares either attr itself. + declares = node.attr(vc.VALIDATOR_ATTR_DB_CHECK) is not None or node.attr(vc.VALIDATOR_ATTR_CONSTRAINT_NAME) is not None + if checked and declares: + name = node.get_meta_attr(vc.VALIDATOR_ATTR_CONSTRAINT_NAME) + if node.get_meta_attr(vc.VALIDATOR_ATTR_DB_CHECK) is False and isinstance(name, str) and name: + prefix = f"{owner}." if owner is not None else "" + errors.append(MetaError( + code=ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + message=( + f'{node.type}.{node.sub_type} "{prefix}{node.name}" sets @dbCheck: false and ' + f'@constraintName "{name}"; with no CHECK there is nothing for the name to name. ' + "Remove @constraintName, or remove @dbCheck: false." + ), + envelope=node.source, + )) + nxt = node.name if node.type in (TYPE_OBJECT, TYPE_FIELD) else owner + for child in node.own_children(): + visit(child, nxt) + + for child in root.own_children(): + visit(child, None) + + # Cross-field validators (comparison / requiredWhen / presentIff / atLeastOne), which the # database enforces as CHECKs: atLeastOne @max between 1 and the number of its @fields, # every field a @condition names a field of the owning entity, and a @condition that can diff --git a/server/python/src/metaobjects/meta/core/validator/validator_constants.py b/server/python/src/metaobjects/meta/core/validator/validator_constants.py index 7509c4eef9..9825c13ed7 100644 --- a/server/python/src/metaobjects/meta/core/validator/validator_constants.py +++ b/server/python/src/metaobjects/meta/core/validator/validator_constants.py @@ -33,6 +33,8 @@ VALIDATOR_ATTR_CONDITION = "condition" # The database name of the CHECK a CHECK-generating validator generates (db provider). VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName" +# A CHECK-generating validator or field.enum (db provider): false generates no database CHECK. Absent: true. +VALIDATOR_ATTR_DB_CHECK = "dbCheck" # The cross-field validators (entity-scoped; the database enforces them as CHECKs). CROSS_FIELD_VALIDATOR_SUBTYPES = ( VALIDATOR_SUBTYPE_COMPARISON, diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index 17e1308f21..761b1f24ce 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -208,6 +208,18 @@ "were named by hand. RDB-physical — contributed by the db provider." ), ) +_ENUM_DB_CHECK_SCHEMA = AttrSchema( + name=vc.VALIDATOR_ATTR_DB_CHECK, + value_type=ATTR_SUBTYPE_BOOLEAN, + required=False, + description="false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", +) +_VALIDATOR_DB_CHECK_SCHEMA = AttrSchema( + name=vc.VALIDATOR_ATTR_DB_CHECK, + value_type=ATTR_SUBTYPE_BOOLEAN, + required=False, + description="false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", +) # The validators meta migrate renders as a CHECK: required is NOT NULL; array and base have none. _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME = ( vc.VALIDATOR_SUBTYPE_NUMERIC, @@ -257,9 +269,10 @@ def _register(registry: TypeRegistry) -> None: ], ) # @constraintName names the CHECK a validator / a field.enum's membership generates. - registry.extend(TYPE_FIELD, fc.FIELD_SUBTYPE_ENUM, attributes=[_ENUM_CONSTRAINT_NAME_SCHEMA]) + # @dbCheck: false asks either of them for no CHECK at all. + registry.extend(TYPE_FIELD, fc.FIELD_SUBTYPE_ENUM, attributes=[_ENUM_CONSTRAINT_NAME_SCHEMA, _ENUM_DB_CHECK_SCHEMA]) for sub_type in _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME: - registry.extend(TYPE_VALIDATOR, sub_type, attributes=[_VALIDATOR_CONSTRAINT_NAME_SCHEMA]) + registry.extend(TYPE_VALIDATOR, sub_type, attributes=[_VALIDATOR_CONSTRAINT_NAME_SCHEMA, _VALIDATOR_DB_CHECK_SCHEMA]) # index.lookup: same RDB physical attrs as identity.secondary (@orders/@where/@expr/@using). registry.extend( TYPE_INDEX, diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index e1d1cb0327..47ab036326 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -63,14 +63,16 @@ "type": "field", "subType": "enum", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { "type": "validator", "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { diff --git a/server/typescript/packages/metadata/src/core/validator/validator-constants.ts b/server/typescript/packages/metadata/src/core/validator/validator-constants.ts index 22524989bf..b1d8d0bd7c 100644 --- a/server/typescript/packages/metadata/src/core/validator/validator-constants.ts +++ b/server/typescript/packages/metadata/src/core/validator/validator-constants.ts @@ -55,6 +55,8 @@ export type ComparisonOp = (typeof VALIDATOR_COMPARISON_OPS)[number]; export const VALIDATOR_ATTR_CONDITION = "condition"; /** Every validator (db provider): the database name of the CHECK it generates. */ export const VALIDATOR_ATTR_CONSTRAINT_NAME = "constraintName"; +/** A CHECK-generating validator or field.enum (db provider): `false` generates no database CHECK. Absent: true. */ +export const VALIDATOR_ATTR_DB_CHECK = "dbCheck"; /** The cross-field validators: the database enforces them, nothing else evaluates them. */ export const CROSS_FIELD_VALIDATOR_SUBTYPES: readonly string[] = [ VALIDATOR_SUBTYPE_COMPARISON, diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index ceacde2468..13f358a147 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -158,6 +158,8 @@ export const ERROR_CODES = [ "ERR_SEQUENCE_WITHOUT_INCREMENT", // identity.primary @sequenceStart below 1, or past what its key field can hold. "ERR_SEQUENCE_START_OUT_OF_RANGE", + // A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. + "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", "ERR_STORAGE_WITHOUT_OBJECT_REF", // ADR-0013 — a field.object REQUIRES @objectRef (open/untyped JSON uses // the physical @dbColumnType: jsonb escape hatch on field.string instead). diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index 52f80c922d..7d8d4b84f5 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -26,7 +26,7 @@ import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, - validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; + validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -735,6 +735,9 @@ export class MetaDataLoader { // Cross-field validators: atLeastOne @max in range; @condition names real fields. errors.push(...validateCrossFieldValidators(root)); + // @dbCheck: false with @constraintName names a CHECK that is never created. + errors.push(...validateDbCheck(root)); + // Tenth pass: one-primary multi-source rule — if an object has ≥1 source, // exactly one must carry role "primary" (ERR_SOURCE_NO_PRIMARY / // ERR_SOURCE_MULTIPLE_PRIMARY). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index c75083bf36..c7c408ddd7 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -17,6 +17,11 @@ import { VALIDATOR_ATTR_FIELDS, VALIDATOR_ATTR_MAX, VALIDATOR_SUBTYPE_AT_LEAST_ONE, + VALIDATOR_ATTR_CONSTRAINT_NAME, + VALIDATOR_ATTR_DB_CHECK, + VALIDATOR_SUBTYPE_LENGTH, + VALIDATOR_SUBTYPE_NUMERIC, + VALIDATOR_SUBTYPE_REGEX, } from "../core/validator/validator-constants.js"; import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; @@ -2053,6 +2058,40 @@ export function validateIdentitySequence(root: MetaData): ParseError[] { return errors; } +// --------------------------------------------------------------------------- +// @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no +// database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the +// node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK) rather than one of them silently ignored. +// Read RESOLVING (ADR-0039), reported on each node that declares either of the two itself. +// --------------------------------------------------------------------------- + +const DB_CHECK_VALIDATOR_SUBTYPES: readonly string[] = [ + VALIDATOR_SUBTYPE_NUMERIC, VALIDATOR_SUBTYPE_LENGTH, VALIDATOR_SUBTYPE_REGEX, ...CROSS_FIELD_VALIDATOR_SUBTYPES, +]; + +export function validateDbCheck(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + const visit = (node: MetaData, owner: string | undefined): void => { + const checked = (node.type === TYPE_VALIDATOR && DB_CHECK_VALIDATOR_SUBTYPES.includes(node.subType)) + || (node.type === TYPE_FIELD && node.subType === FIELD_SUBTYPE_ENUM); + if (checked && (node.ownAttr(VALIDATOR_ATTR_DB_CHECK) !== undefined || node.ownAttr(VALIDATOR_ATTR_CONSTRAINT_NAME) !== undefined)) { + const name = node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (node.attr(VALIDATOR_ATTR_DB_CHECK) === false && typeof name === "string" && name.length > 0) { + const label = `${node.type}.${node.subType} "${owner !== undefined ? `${owner}.` : ""}${node.name}"`; + errors.push(new ParseError( + `${label} sets @dbCheck: false and @constraintName "${name}"; with no CHECK there is nothing for the name to name. ` + + `Remove @constraintName, or remove @dbCheck: false.`, + { code: "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", source: node.source }, + )); + } + } + const next = node.type === TYPE_OBJECT || node.type === TYPE_FIELD ? node.name : owner; + for (const child of node.ownChildren()) visit(child, next); + }; + for (const child of root.ownChildren()) visit(child, undefined); + return errors; +} + // --------------------------------------------------------------------------- // field.enum @maxLength — the column length of a string-stored enum: // 1. every member of @values fits in it (ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH), the diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index 0a7072f3e2..e56d546178 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -265,6 +265,14 @@ export const DB_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, + { + "type": "attr", + "subType": "boolean", + "name": "dbCheck", + "min": 0, + "max": 1, + "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, @@ -287,6 +295,14 @@ export const DB_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." + }, + { + "type": "attr", + "subType": "boolean", + "name": "dbCheck", + "min": 0, + "max": 1, + "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, diff --git a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts index 7d95baeaaf..f15eeeddb0 100644 --- a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts @@ -111,6 +111,7 @@ const ENUM_CORE_EXTRA: Record = { // db provider: the name of the CHECK an enum's member list generates. const ENUM_DB_EXTRA: Record = { constraintName: { valueType: "string", required: false }, + dbCheck: { valueType: "boolean", required: false }, }; /** Scoped concern attrs (db / prompt). */ diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 552b50b436..87a5ea2588 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -75,6 +75,7 @@ import { VALIDATOR_ATTR_CONDITION, VALIDATOR_ATTR_MAX, VALIDATOR_ATTR_CONSTRAINT_NAME, + VALIDATOR_ATTR_DB_CHECK, type ExprNode, } from "@metaobjectsdev/metadata"; import type { SqlType } from "./sql-type.js"; @@ -911,7 +912,9 @@ function buildChecks( // the member strings — `IN (0, 5, 9)`, not `IN ('DRAFT', …)`. The members are // still the SSOT: the integers are read THROUGH the map, keyed by member, so a // member with no mapping cannot silently vanish from the constraint. - if (field.subType === FIELD_SUBTYPE_ENUM) { + // @dbCheck: false (ADR-0039 resolving) asks for no CHECK; the enum's membership and each + // validator's rule are enforced app-side only. + if (field.subType === FIELD_SUBTYPE_ENUM && !checkOptedOut(field)) { const raw = field.attr(FIELD_ATTR_VALUES); if (Array.isArray(raw) && raw.length > 0) { const values = raw.map((v) => String(v)); @@ -946,6 +949,7 @@ function buildChecks( const enforcesLength = dialect !== "sqlite" && dialect !== "d1"; const enforcedMax = skipRedundant && enforcesLength && columnType.kind === "text" ? columnType.maxLength : undefined; for (const v of field.validators()) { + if (checkOptedOut(v)) continue; // A declared @constraintName asks for the CHECK by name, so it is kept even where the // project's `migrate.checks.skipRedundant` would leave it out: a declaration beats a default. const keep = declaredCheckName(v) !== undefined; @@ -957,6 +961,7 @@ function buildChecks( } // Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne). for (const v of entity.validators()) { + if (checkOptedOut(v)) continue; const check = crossFieldCheck(v, entity, tableName, strategy, dialect); if (check) checks.push(withDeclaredName(withCondition(check, v, entity, strategy, dialect), v)); } @@ -1035,6 +1040,12 @@ function renderEquals( return `'${s.replace(/'/g, "''")}'`; } +/** Whether a validator or field.enum opts out of its CHECK (`@dbCheck: false`; ADR-0039 resolving). + * `migrate.checks.skipRedundant` is independent of it: it only ever leaves more out. */ +function checkOptedOut(node: MetaData): boolean { + return node.attr(VALIDATOR_ATTR_DB_CHECK) === false; +} + /** A validator's or field.enum's declared CHECK name (`@constraintName`; ADR-0039 resolving), if any. */ function declaredCheckName(node: MetaData): string | undefined { const name = node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); diff --git a/site-reference/providers.html b/site-reference/providers.html index 3bf4e9bf8b..ad88f7763b 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -102,7 +102,7 @@

    metaobjects-db

  • field.decimal: @column, @db.indexed, @dbColumnType
  • field.double: @column, @db.indexed, @dbColumnType
  • field.duration: @column, @db.indexed, @dbColumnType
  • -
  • field.enum: @column, @constraintName, @db.indexed, @dbColumnType
  • +
  • field.enum: @column, @constraintName, @db.indexed, @dbCheck, @dbColumnType
  • field.float: @column, @db.indexed, @dbColumnType
  • field.inet: @column, @db.indexed, @dbColumnType
  • field.int: @column, @db.indexed, @dbColumnType
  • @@ -119,13 +119,13 @@

    metaobjects-db

  • identity.secondary: @expr, @orders, @using, @where
  • index.lookup: @expr, @orders, @using, @where
  • source.rdb: @function, @kind, @materializedView, @parameterRef, @proc, @role, @schema, @sql, @table, @unmanaged, @view
  • -
  • validator.atLeastOne: @constraintName
  • -
  • validator.comparison: @constraintName
  • -
  • validator.length: @constraintName
  • -
  • validator.numeric: @constraintName
  • -
  • validator.presentIff: @constraintName
  • -
  • validator.regex: @constraintName
  • -
  • validator.requiredWhen: @constraintName
  • +
  • validator.atLeastOne: @constraintName, @dbCheck
  • +
  • validator.comparison: @constraintName, @dbCheck
  • +
  • validator.length: @constraintName, @dbCheck
  • +
  • validator.numeric: @constraintName, @dbCheck
  • +
  • validator.presentIff: @constraintName, @dbCheck
  • +
  • validator.regex: @constraintName, @dbCheck
  • +
  • validator.requiredWhen: @constraintName, @dbCheck
  • metaobjects-documentation

    Universal documentation common attrs (description / title / notes / deprecated / replacedBy / seeAlso / aliases) accepted on every metatype.

    diff --git a/site-reference/types/field.html b/site-reference/types/field.html index b8f9cf4497..7f9289c351 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -1192,6 +1192,15 @@

    field.enum

    + + + + + + + + + diff --git a/site-reference/types/validator.html b/site-reference/types/validator.html index 6a1f483852..db6bff86ea 100644 --- a/site-reference/types/validator.html +++ b/site-reference/types/validator.html @@ -125,6 +125,15 @@

    validator.atLeastOne

    When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means).
    @dbCheckbooleannometaobjects-dbfalse: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @dbColumnType string noThe database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + @@ -219,6 +228,15 @@

    validator.comparison

    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @fields string[] yes The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + @@ -275,6 +293,15 @@

    validator.length

    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @left string yes The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + @@ -322,6 +349,15 @@

    validator.numeric

    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max int no The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + @@ -379,6 +415,15 @@

    validator.presentIff

    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max int no The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + @@ -435,6 +480,15 @@

    validator.regex

    - + diff --git a/site-reference/types/attr.html b/site-reference/types/attr.html index 2495d90ecf..5fca197e1f 100644 --- a/site-reference/types/attr.html +++ b/site-reference/types/attr.html @@ -79,7 +79,7 @@

    attr.double

    Allowed children

    No structural children.

    attr.expression

    -

    A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.

    +

    A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.

    Owning provider: metaobjects-core-types

    Attributes

    No subtype-specific attributes.

    diff --git a/spec/metamodel/attr.json b/spec/metamodel/attr.json index c05dab28b7..ec55a95947 100644 --- a/spec/metamodel/attr.json +++ b/spec/metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } From 94b8f391a2e4638b477590afbe5be39aed2905d4 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:44:02 -0500 Subject: [PATCH 200/267] fix(views): a partial or expression unique index never makes a reverse hop to-one Co-Authored-By: Claude Opus 5.5 --- .../ViewVocabularyRc21LoaderTests.cs | 12 ++++++++---- server/csharp/MetaObjects/Loader/ValidationPasses.cs | 2 ++ .../test/projection/rc21b-view-vocabulary.test.ts | 9 ++++++--- .../metadata/src/loader/validation-passes.ts | 5 ++++- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index 569679a467..38587c0f82 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -165,11 +165,15 @@ public void The_db_column_type_text_spellings_load_and_an_oversize_max_length_is // rc.21 part B: a passthrough walks a reference backwards when its holder declares a unique identity over its fields. [Theory] - [InlineData(true)] - [InlineData(false)] - public void A_passthrough_over_a_reverse_hop_needs_a_unique_identity(bool unique) + [InlineData(true, false)] + [InlineData(false, false)] + [InlineData(true, true)] + public void A_passthrough_over_a_reverse_hop_needs_a_unique_identity(bool unique, bool partial) { - var secondary = unique ? """{ "identity.secondary": { "name": "events_order_uq", "@fields": "orderId" } },""" : ""; + // A partial (@where) unique index is unique only over its subset: the hop stays to-many. + var where = partial ? """, "@where": "\"note\" IS NOT NULL" """ : ""; + var secondary = unique ? $$"""{ "identity.secondary": { "name": "events_order_uq", "@fields": "orderId"{{where}} } },""" : ""; + unique = unique && !partial; var json = $$""" { "metadata.root": { "package": "acme", "children": [ { "object.entity": { "name": "Order", "children": [ { "source.rdb": { "@table": "orders" } }, { "field.long": { "name": "id" } }, diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index b7c4bbd89e..cceca59552 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1305,8 +1305,10 @@ private static bool ReverseHopIsUnique(MetaData rel) if (rel.Parent is not { } holder) return false; var fields = IdentityFieldSet(rel); if (fields.Length == 0) return false; + // A partial (@where) or expression (@expr) unique index never makes the hop to-one. return holder.Children().Any(c => c.Type == TYPE_IDENTITY && (c.SubType == IDENTITY_SUBTYPE_PRIMARY || c.SubType == IDENTITY_SUBTYPE_SECONDARY) + && c.Attr(IDENTITY_ATTR_WHERE) is null && c.Attr(IDENTITY_ATTR_EXPR) is null && IdentityFieldSet(c) == fields); } diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts index 37c1406607..aab45ac269 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -251,14 +251,15 @@ describe("a projection over a TPH root reads its subtypes' columns; a unique rev expect(sql).toContain("FROM public.vehicles v"); expect(sql).not.toContain("'TRUCK'"); }); - const viaCard = (unique: boolean) => [ + const viaCard = (unique: boolean | "partial") => [ { "object.entity": { name: "LockerKey", children: [ { "source.rdb": { "@table": "locker_keys" } }, { "field.long": { name: "id" } }, { "field.long": { name: "lockerId" } }, { "field.string": { name: "note" } }, { "identity.primary": { "@fields": "id" } }, - ...(unique ? [{ "identity.secondary": { name: "locker_keys_locker_uq", "@fields": "lockerId" } }] : []), + ...(unique ? [{ "identity.secondary": { name: "locker_keys_locker_uq", "@fields": "lockerId", + ...(unique === "partial" ? { "@where": "\"note\" IS NOT NULL" } : {}) } }] : []), { "identity.reference": { name: "lockerId", "@fields": "lockerId", "@references": "Locker" } } ] } }, ]; test("a passthrough over a reverse hop loads when the holder's reference fields are a unique identity, and only then", async () => { @@ -267,7 +268,7 @@ describe("a projection over a TPH root reads its subtypes' columns; a unique rev { "field.long": { name: "id", extends: "Locker.id" } }, { "field.string": { name: "note", children: [ { "origin.passthrough": { "@from": "LockerKey.note", "@via": "Locker.lockerKeys" } } ] } }, { "identity.primary": { name: "id", extends: "Locker.primary" } } ] } }; - const withUnique = async (unique: boolean) => { + const withUnique = async (unique: boolean | "partial") => { const doc = { "metadata.root": { package: "acme", children: [...tph.slice(0, 3), ...viaCard(unique), projection] } }; const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); return { root, errors: errors.map((e) => e.message) }; @@ -276,5 +277,7 @@ describe("a projection over a TPH root reads its subtypes' columns; a unique rev expect(ok.errors).toEqual([]); expect(buildProjectionViews(ok.root, { dialect: "postgres" })[0]!.sql).toContain("LEFT OUTER JOIN public.locker_keys l0 ON l0.locker_id = l.id"); expect((await withUnique(false)).errors.some((m) => /is to-many/.test(m))).toBe(true); + // A partial unique index is unique only over its subset, so the hop stays to-many. + expect((await withUnique("partial")).errors.some((m) => /is to-many/.test(m))).toBe(true); }); }); diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 3494630275..5c1d0dae71 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -113,7 +113,7 @@ import { FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, } from "../core/field/field-constants.js"; -import { FIELD_ATTR_COLUMN, FIELD_ATTR_FLATTENED_COLUMN_PREFIX, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START } from "../persistence/db/db-constants.js"; +import { FIELD_ATTR_COLUMN, FIELD_ATTR_FLATTENED_COLUMN_PREFIX, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR, IDENTITY_ATTR_WHERE, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START } from "../persistence/db/db-constants.js"; import { IDENTITY_ATTR_FIELDS, IDENTITY_SUBTYPE_REFERENCE, @@ -906,8 +906,11 @@ function _reverseHopIsUnique(rel: MetaData): boolean { const fields = _identityFieldSet(rel).join(","); if (fields === "") return false; // ADR-0039: resolving — a unique identity may be inherited. + // A partial (@where) or expression (@expr) unique index is unique over a subset or a value, not + // over the reference's rows, so it never makes the hop to-one. return holder.children().some((c) => c.type === TYPE_IDENTITY && (c.subType === IDENTITY_SUBTYPE_PRIMARY || c.subType === IDENTITY_SUBTYPE_SECONDARY) + && c.attr(IDENTITY_ATTR_WHERE) === undefined && c.attr(IDENTITY_ATTR_EXPR) === undefined && _identityFieldSet(c).join(",") === fields); } From aa3d8f000d46c39251f8b1f0f8cd72801850e765 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:46:19 -0500 Subject: [PATCH 201/267] feat(views): warn when an extender's view widened over a TPH base; the anchor rule is a behaviour change The load warns (TypeScript and C#, one message) when a projection with no identity of its own, anchored by its super on a TPH base, binds a field to a subtype-only column and has no @filter on the discriminator: the case whose view now returns every base row. The CHANGELOG moves the anchor rule to a behaviour change with the upgrade note (a discriminator @filter, or anchoring on the subtype), notes the partial-index rule for reverse hops, and states the GROUP BY change accurately. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 34 +++++++++---- .../ViewVocabularyRc21LoaderTests.cs | 30 +++++++++++ .../MetaObjects/Loader/MetaDataLoader.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 38 ++++++++++++++ .../metadata/src/loader/meta-data-loader.ts | 4 +- .../metadata/src/loader/validation-passes.ts | 51 +++++++++++++++++++ .../test/rc21b-view-vocabulary.test.ts | 35 +++++++++++++ 7 files changed, 182 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92f48264c9..d11fabb6d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -362,6 +362,20 @@ vocabulary; upgrade every port together. ### Changed +- **Behaviour change, TypeScript and C#: a projection that extends another keeps its super's + identity anchor (rc.21).** An extender that declared no identity of its own took its base from + its own fields' `extends`. So a projection over a TPH root that added a subtype's column moved + its base to that subtype, and its view returned only the subtype's rows. It now keeps the + identity its super anchors with: the base is the TPH base, and the view returns **every** row of + the shared table, the subtype column NULL on the others. A field bound to a TPH relative of the + base reads the shared table's column (it read a column named after the projection field). The + load now warns in exactly the case whose output widened: an extender with no identity of its + own, anchored by its super on a TPH base, that binds a field to a subtype-only column and has no + `@filter` on the discriminator. **Upgrade note:** to get the subtype-scoped view back, either add + `@filter: { : }` to the extender, or anchor it on the subtype: declare + `identity.primary { name: id, extends: .primary }` with a field extending + `.id`. + - **C#: the generated EF context declares the CHECKs `meta migrate` creates** (rc.19 item 13, ruling R55). Every validator that can carry one (`numeric`, `length`, `regex`, and the cross-field `comparison`, `requiredWhen`, `presentIff`, `atLeastOne`, with `@condition`) and @@ -620,23 +634,21 @@ vocabulary; upgrade every port together. ### Fixed -- **Fix, TypeScript and C#: a projection that extends another keeps its super's identity anchor - (rc.21).** An extender that declared no identity of its own took its base from its own fields' - `extends`, so a projection over a TPH root that added a subtype's column moved its base to the - subtype (and its view to that subtype's rows). It now keeps the identity its super anchors with. - And a field bound to a TPH relative of the base reads the shared table's column, where it read a - column named after the projection field. - - **Fix, TypeScript and C#: a passthrough may walk a reference backwards when at most one row references it (rc.21).** A reverse hop was always to-many, so a passthrough over it was refused (`ERR_ORIGIN_CARDINALITY`). When the holder declares an `identity.primary` or `identity.secondary` over exactly the reference's fields, the hop is to-one for a passthrough; - an aggregate over it stays legal. + an aggregate over it stays legal. A partial (`@where`) or expression (`@expr`) unique index is + unique only over a subset or a value, so it never makes the hop to-one. - **Fix, TypeScript: a grouped view groups the joined columns its expressions read (rc.21).** A - computed column or an `origin.first` correlation that read a joined column outside an - aggregate was not in the GROUP BY; Postgres refused the view. The base row's columns stay out - (its primary key is grouped). + computed column or an `origin.first` correlation that read a joined column outside an aggregate + was not in the GROUP BY. Where the joined row's primary key was not grouped, Postgres refused + the view; it is valid now. The generated view text changes for every grouped view whose + expressions read a joined column, also where the view already worked (SQLite, or a Postgres + view the joined key's grouping made valid), so the next `meta migrate` replaces such a view + once. Every added column is on a to-one join, so the rows are the same. The base row's columns + stay out (its primary key is grouped). - **Fix, C#: a reference over a flattened member configures the owned type's own navigation (rc.21, U6).** `identity.reference { @fields: address.countryId, @references: Country }` emitted diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index 38587c0f82..3c07a640dd 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -191,4 +191,34 @@ public void A_passthrough_over_a_reverse_hop_needs_a_unique_identity(bool unique if (unique) Assert.Empty(errors); else Assert.Contains(errors, e => e.Code.ToString() == "ERR_ORIGIN_CARDINALITY"); } + + // rc.21 part B fix round (I2): an extender whose view widened over a TPH base warns, unless scoped. + [Theory] + [InlineData("", true)] + [InlineData("\"@filter\": { \"kind\": \"TRUCK\" },", false)] + public void An_extender_whose_view_widened_over_a_tph_base_warns(string filter, bool warns) + { + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Truck", "extends": "Vehicle", "@discriminatorValue": "TRUCK", "children": [ { "field.string": { "name": "payloadClass" } } ] } }, + { "object.projection": { "name": "VehicleBase", "abstract": true, "children": [ + { "field.long": { "name": "vehicleId", "extends": "Vehicle.id" } }, { "identity.primary": { "name": "id", "extends": "Vehicle.primary" } } ] } }, + { "object.projection": { "name": "TruckRow", "extends": "VehicleBase", {{filter}} "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { "name": "payload", "extends": "Truck.payloadClass" } } ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var result = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "t.json")]); + Assert.Empty(result.Errors); + var hit = result.Warnings.Where(w => w.Contains("TruckRow", StringComparison.Ordinal)).ToList(); + if (warns) + { + var w = Assert.Single(hit); + Assert.Contains("only the subtype Truck carries, over the TPH base Vehicle with no @filter on its discriminator \"kind\"", w); + } + else Assert.Empty(hit); + } } diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 72faee9228..d4c20781e9 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -491,6 +491,8 @@ public LoadResult Load(IReadOnlyList sources) // Pass 4: filterable-without-index drift warning warnings.AddRange(ValidationPasses.ValidateFilterableHasIndex(root)); + // rc.21 part B (I2): an extender whose view widened with the identity-anchor rule. + warnings.AddRange(ValidationPasses.ValidateExtenderSubtypeScope(root)); // Pass 4b: @filterable on a subtype with no operator band, or an array → error (SP-H Unit9 / #335) errors.AddRange(ValidationPasses.ValidateFilterableHasSupportedOps(root)); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index cceca59552..609809cf79 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1332,6 +1332,44 @@ private static bool ReverseHopIsUnique(MetaData rel) /// Derive the BASE entity a no-`@via` origin path anchors at (spec §5). /// Returns null when no base is derivable (an error has been pushed). + /// + /// rc.21 part B (I2): warn when an extender's view WIDENED with the identity-anchor rule — no identity + /// of its own, a super anchored on a TPH base, a field bound to a column only a subtype carries, and no + /// discriminator filter. TS validateExtenderSubtypeScope, message for message. + /// + public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) + { + var warnings = new List(); + foreach (var obj in root.OwnChildren().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) + { + if (obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY)) continue; + if (obj.SuperData is not { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } sup || !AnchorsByIdentity(sup)) continue; + if (DeriveBaseEntity(obj, root, "@extends", obj.Source, new List()) is not { } baseEntity) continue; + string? discriminator = null; + for (var cur = baseEntity; cur is { Type: TYPE_OBJECT }; cur = cur.SuperData) + if (cur.OwnAttr(OBJECT_ATTR_DISCRIMINATOR) is string d) { discriminator = d; break; } + if (discriminator is null) continue; + if (ProjectionFilters.Effective(obj) is IReadOnlyDictionary filter && FilterKeys(filter).Contains(discriminator)) continue; + var pkg = NamingRefs.EffectivePackage(obj); + foreach (var f in obj.Children().Where(c => c.Type == TYPE_FIELD)) + { + var owner = RefNamedOwner(f, root, pkg); + if (owner is null || ReferenceEquals(owner, baseEntity)) continue; + var descends = false; + for (var cur = owner.SuperData; cur is not null; cur = cur.SuperData) + if (ReferenceEquals(cur, baseEntity)) { descends = true; break; } + if (!descends) continue; + var col = f.SuperRef is { } r ? r.Split('.').Last() : f.Name; + warnings.Add( + $"object.projection {obj.Name}: \"{f.Name}\" reads {owner.Name}.{col}, a column only the " + + $"subtype {owner.Name} carries, over the TPH base {baseEntity.Name} with no @filter on its discriminator \"{discriminator}\", so the " + + $"view returns every {baseEntity.Name} row (rc.21: an extender keeps its super's identity anchor; before, its base was {owner.Name}). " + + $"To keep a subtype-scoped view, add @filter {{ {discriminator}: }} or declare identity.primary {{ extends: {owner.Name}.primary }}."); + } + } + return warnings.AsReadOnly(); + } + /// rc.21 part B: whether a projection (or one it extends) anchors its base with an extended identity. private static bool AnchorsByIdentity(MetaData obj) { diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index 75968a48cd..c952a6358f 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -26,7 +26,7 @@ import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, - validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; + validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateExtenderSubtypeScope, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -636,6 +636,8 @@ export class MetaDataLoader { // Fifth pass: @filterable without index drift warning. warnings.push(...validateFilterableHasIndex(root)); + // rc.21 part B (I2): an extender whose view widened with the identity-anchor rule. + warnings.push(...validateExtenderSubtypeScope(root)); // SP-H Unit9 — @filterable on a subtype with no operator band → error // (would silently generate a filter that rejects every request). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 5c1d0dae71..64836d3590 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -74,6 +74,7 @@ import { OBJECT_PROJECTION_ATTR_UNION_ALL, OBJECT_PROJECTION_ATTR_GRAIN, OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + OBJECT_ATTR_DISCRIMINATOR, } from "../core/object/object-constants.js"; import { MetaSource } from "../persistence/source/meta-source.js"; import { resolveColumnName } from "../naming.js"; @@ -1032,6 +1033,56 @@ function _deriveBaseEntity( return undefined; } +/** + * rc.21 part B (I2): warn when an extender's view WIDENED with the identity-anchor rule — a projection + * with no identity of its own whose base its super anchors on a TPH base, that binds a field to a + * column only a subtype carries, and that scopes no row by the discriminator. Before rc.21 its base + * was that subtype and its view held only the subtype's rows; now it is the TPH base's, every row. + */ +export function validateExtenderSubtypeScope(root: MetaData): string[] { + const warnings: string[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_PROJECTION)) { + // ADR-0039: own — the identity anchor rule applies to an extender that declares none of its own. + if (obj.ownChildren().some((c) => c.type === TYPE_IDENTITY)) continue; + const sup = obj.superResolved; + if (sup === undefined || sup.type !== TYPE_OBJECT || sup.subType !== OBJECT_SUBTYPE_PROJECTION || !_anchorsByIdentity(sup)) continue; + const base = _deriveBaseEntity(obj, root, "@extends", obj.source, []); + if (base === undefined) continue; + // ADR-0039: resolving — the discriminator may be declared on an ancestor of the base. + const discriminator = _tphDiscriminatorOf(base); + if (discriminator === undefined) continue; + if (filterKeys(effectiveProjectionFilter(obj)).includes(discriminator)) continue; + const referrerPkg = obj.package ?? obj.fileDefaultPackage ?? ""; + for (const f of obj.children().filter((c) => c.type === TYPE_FIELD)) { + const owner = _refNamedOwner(f, root, referrerPkg); + if (owner === undefined || owner === base || !_isDescendantOf(owner, base)) continue; + warnings.push( + `object.projection ${obj.name}: "${f.name}" reads ${owner.name}.${f.superRef?.split(".").pop() ?? f.name}, a column only the ` + + `subtype ${owner.name} carries, over the TPH base ${base.name} with no @filter on its discriminator "${discriminator}", so the ` + + `view returns every ${base.name} row (rc.21: an extender keeps its super's identity anchor; before, its base was ${owner.name}). ` + + `To keep a subtype-scoped view, add @filter { ${discriminator}: } or declare identity.primary { extends: ${owner.name}.primary }.`, + ); + } + } + return warnings; +} + +/** The discriminator field of the TPH level `obj` belongs to (its own, or an ancestor's), if any. */ +function _tphDiscriminatorOf(obj: MetaData): string | undefined { + for (let cur: MetaData | undefined = obj; cur !== undefined && cur.type === TYPE_OBJECT; cur = cur.superResolved) { + // ADR-0039: own — the level that declares the discriminator. + const d = cur.ownAttr(OBJECT_ATTR_DISCRIMINATOR); + if (typeof d === "string") return d; + } + return undefined; +} + +/** Whether `obj` extends `ancestor`, directly or through levels. */ +function _isDescendantOf(obj: MetaData, ancestor: MetaData): boolean { + for (let cur = obj.superResolved; cur !== undefined; cur = cur.superResolved) if (cur === ancestor) return true; + return false; +} + /** rc.21 part B: whether a projection (or a projection it extends) anchors its base with an extended identity. */ function _anchorsByIdentity(obj: MetaData): boolean { // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index 10822f607c..a0966e2c8b 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -201,3 +201,38 @@ describe("U15 — @union", () => { await refused("ERR_BAD_ATTR_VALUE", /@unionAll needs @union/, branch("A", "Customer", "id", label("zip")), union({ "@unionAll": true })); }); }); + +// rc.21 part B fix round (I2): an extender keeps its super's identity anchor, so a projection over a +// TPH base that reads a subtype-only column now returns every base row. The load warns, unless a +// discriminator filter (or its own identity) scopes it. +describe("an extender whose view widened over a TPH base", () => { + const tph = [ + { "object.entity": { name: "Vehicle", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { name: "id" } }, { "field.string": { name: "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "Truck", extends: "Vehicle", "@discriminatorValue": "TRUCK", children: [ + { "field.string": { name: "payloadClass" } } ] } }, + { "object.projection": { name: "VehicleBase", abstract: true, children: [ + { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, + { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, + ]; + const row = (extra: Record = {}, children: unknown[] = []) => ({ "object.projection": { name: "TruckRow", extends: "VehicleBase", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { name: "payload", extends: "Truck.payloadClass" } }, ...children ] } }); + async function warningsOf(...extra: unknown[]): Promise { + const { errors, warnings } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [...tph, ...extra] } }))]); + expect(errors).toEqual([]); + return warnings.map((w) => (typeof w === "string" ? w : (w as { message: string }).message)); + } + test("warns, naming the remedy", async () => { + const w = (await warningsOf(row())).filter((m) => m.includes("TruckRow")); + expect(w.length).toBe(1); + expect(w[0]).toMatch(/only the subtype Truck carries, over the TPH base Vehicle with no @filter on its discriminator "kind"/); + expect(w[0]).toMatch(/@filter \{ kind: \} or declare identity.primary \{ extends: Truck.primary \}/); + }); + test("a discriminator filter, or its own identity, scopes it: no warning", async () => { + expect((await warningsOf(row({ "@filter": { kind: "TRUCK" } }))).filter((m) => m.includes("TruckRow"))).toEqual([]); + expect((await warningsOf(row({}, [{ "field.long": { name: "vehicleId", extends: "Truck.id" } }, + { "identity.primary": { name: "id", extends: "Truck.primary" } }]))).filter((m) => m.includes("TruckRow"))).toEqual([]); + }); +}); From 36e46ef1083102bee77f77df5b111fa095ba8470 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:49:55 -0500 Subject: [PATCH 202/267] feat(views): origin.function declares its signature; the call is checked and cast origin.function gains @params (one field subtype per argument) and a required @returns. The loader (TypeScript and C#) refuses an argument whose field type is not its declared parameter type, pointing at an origin.computed cast field, a @returns other than the carrying field's subtype, and a @params of the wrong length; codegen re-checks for a caller that skipped the loader. The view casts the call to the field's column type, so the column has it whatever the function returns. A reached function's derived arguments are reached too. Java and Python register the two attrs. Co-Authored-By: Claude Opus 5.5 --- docs/features/relationships.md | 9 ++-- .../input/meta.views.json | 2 +- .../expected.json | 5 ++ .../input/meta.views.json | 2 +- fixtures/metamodel-docs/expected/INDEX.md | 2 +- fixtures/metamodel-docs/expected/providers.md | 2 +- .../metamodel-docs/expected/types/origin.md | 6 ++- .../expected-registry.json | 18 ++++++- .../ViewVocabularyRc21LoaderTests.cs | 24 +++++++++ .../MetaObjects/Loader/ValidationPasses.cs | 38 +++++++++++++- .../Persistence/Origin/OriginConstants.cs | 2 + .../Persistence/Origin/OriginSchema.cs | 4 ++ .../MetaObjects/SpecMetamodel/origin.json | 6 ++- .../metaobjects/origin/FunctionOrigin.java | 6 +++ server/python/src/metaobjects/core_types.py | 2 + .../metaobjects/spec_metamodel/origin.json | 6 ++- .../test_template_payload_target_210.py | 2 +- .../src/projection/extract-view-spec.ts | 52 ++++++++++++++++--- .../rc21b-view-vocabulary.fixture.ts | 2 +- .../projection/rc21b-view-vocabulary.test.ts | 10 +++- .../test/view-vocabulary-rc21-pg.test.ts | 5 +- .../metadata/src/loader/validation-passes.ts | 50 +++++++++++++++++- .../persistence/origin/origin-constants.ts | 2 + .../origin/origin-definition.embedded.ts | 21 +++++++- .../test/rc21b-view-vocabulary.test.ts | 26 ++++++++-- .../test/template-payload-target-210.test.ts | 2 +- site-reference/index.html | 2 +- site-reference/providers.html | 2 +- site-reference/types/origin.html | 22 +++++++- spec/metamodel/origin.json | 6 ++- 30 files changed, 296 insertions(+), 42 deletions(-) diff --git a/docs/features/relationships.md b/docs/features/relationships.md index 3877221a3b..fb86e17344 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -279,15 +279,18 @@ filterable (it exists only after grouping). A grouped view also groups every joi expressions read. **A database function the project owns** (`origin.function`). `@function` and `@schema` name it -(plain identifiers), `@args` the fields passed to it in order; each argument is typed by its -field and the result by the carrying field's subtype. Declared on an entity, it is +(plain identifiers), `@args` the fields passed to it in order, `@params` their declared types and +`@returns` the result's (field subtypes). Each argument must have its parameter's type — pass an +`origin.computed` field that casts it (`{ cast: { field: x }, as: int }`) otherwise — and +`@returns` must be the carrying field's subtype; the view casts the call to the field's column +type. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. MetaObjects never creates the function (it is owned SQL, created before the view). Postgres only. ```yaml - field.int: name: riskScore - children: [ { origin.function: { "@function": compute_risk_score, "@schema": app, "@args": [id] } } ] + children: [ { origin.function: { "@function": compute_risk_score, "@schema": app, "@args": [id], "@params": [long], "@returns": int } } ] ``` **One row per array element** (`@grain`, `@grainOrdinal`). A projection whose `@grain` names a diff --git a/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json b/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json index 4f9f08c7ac..8ce97fbb47 100644 --- a/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json +++ b/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json @@ -3,7 +3,7 @@ { "source.rdb": { "@table": "customers" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "field.string": { "name": "tier", "children": [ { "origin.function": { "@function": "tier_of(id); drop table customers", "@args": ["id"] } } ] } } + { "field.string": { "name": "tier", "children": [ { "origin.function": { "@function": "tier_of(id); drop table customers", "@args": ["id"], "@params": ["long"], "@returns": "string" } } ] } } ] } }, { "object.projection": { "name": "V", "children": [ { "source.rdb": { "@kind": "view", "@view": "v" } }, diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/expected.json b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json index 74e6c19e96..39387e08fc 100644 --- a/fixtures/conformance/projection-view-vocabulary-rc21/expected.json +++ b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json @@ -78,6 +78,11 @@ "zip" ], "@function": "tier_of", + "@params": [ + "long", + "string" + ], + "@returns": "string", "@schema": "app" } } diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json index 4864b5e411..57c98b15a5 100644 --- a/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json +++ b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json @@ -15,7 +15,7 @@ { "field.object": { "name": "contacts", "@objectRef": "Contact", "isArray": true, "@storage": "jsonb" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, { "field.string": { "name": "tier", "children": [ - { "origin.function": { "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"] } } + { "origin.function": { "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } } ] } }, { "object.entity": { "name": "Order", "children": [ diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 03801c2a58..44c5a4ed19 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -65,7 +65,7 @@ children and the cardinality of that subtype. Documentation attributes | `origin.base` | Abstract base origin — the shared root subtype for field-level provenance. A field carrying any origin.* is derived ⇒ read-only wherever it lives. The base carries no attrs of its own; concrete subtypes add their provenance attrs. Not authored directly: a `origin.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/origin.md#originbase](types/origin.md#originbase) | | `origin.computed` | A row-level value computed from the base entity's own fields via a structured expression tree (@expr). No related rows, no @via. Read-only; the expression's inferred type must equal the field's declared subType. | [types/origin.md#origincomputed](types/origin.md#origincomputed) | | `origin.first` | The single related row selected by @orderBy along @via, projecting its @of column (argmax then project). Latest = @orderBy desc. Read-only; empty related set (after @filter) → null, so the field must not be @required. | [types/origin.md#originfirst](types/origin.md#originfirst) | -| `origin.function` | A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. | [types/origin.md#originfunction](types/origin.md#originfunction) | +| `origin.function` | A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. | [types/origin.md#originfunction](types/origin.md#originfunction) | | `origin.passthrough` | A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). | [types/origin.md#originpassthrough](types/origin.md#originpassthrough) | | `relationship.aggregation` | A shared/independent containment — the parent groups the target but does not own its lifecycle (default @onDelete set-null). | [types/relationship.md#relationshipaggregation](types/relationship.md#relationshipaggregation) | | `relationship.association` | A plain reference to another entity — no ownership; the target has an independent lifecycle (default @onDelete restrict). | [types/relationship.md#relationshipassociation](types/relationship.md#relationshipassociation) | diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index bc53f39ae8..4d52b810d4 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -36,7 +36,7 @@ Core metaobjects metamodel types and subtypes. - `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@segment`, `@via` - `origin.computed`: `@expr` - `origin.first`: `@filter`, `@of`, `@orderBy`, `@segment`, `@via` -- `origin.function`: `@args`, `@function`, `@schema` +- `origin.function`: `@args`, `@function`, `@params`, `@returns`, `@schema` - `origin.passthrough`: `@convert`, `@from`, `@via` - `relationship.aggregation`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` - `relationship.association`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index 61f58f1cca..f1e536e0af 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -94,7 +94,7 @@ _No structural children._ ### origin.function -A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. +A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. **Owning provider:** metaobjects-core-types @@ -104,8 +104,10 @@ A value computed by a database function the project owns (rc.21): @function name | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@args` | string[] | no | | | metaobjects-core-types | The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments. | +| `@args` | string[] | no | | | metaobjects-core-types | The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments. | | `@function` | string | yes | | | metaobjects-core-types | The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase. | +| `@params` | string[] | no | | | metaobjects-core-types | The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN). | +| `@returns` | string | yes | | | metaobjects-core-types | The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns. | | `@schema` | string | no | | | metaobjects-core-types | The schema the function lives in, a plain identifier. Absent: public. | **Allowed children** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 8163d03c83..a64b0adfa2 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -4078,7 +4078,7 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "attrs": [ { @@ -4086,7 +4086,7 @@ "valueType": "string", "isArray": true, "required": false, - "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." + "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, { "name": "function", @@ -4095,6 +4095,20 @@ "required": true, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { + "name": "params", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." + }, + { + "name": "returns", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." + }, { "name": "schema", "valueType": "string", diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index 3c07a640dd..be579a7590 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -221,4 +221,28 @@ public void An_extender_whose_view_widened_over_a_tph_base_warns(string filter, } else Assert.Empty(hit); } + + // rc.21 part B fix round (I4): origin.function's declared signature is checked. + [Theory] + [InlineData("[\"id\"]", "[\"int\"]", "string", "argument 1 \"id\" is a field.long, but parameter 1 is declared int")] + [InlineData("[\"id\"]", "[\"long\"]", "int", "@returns int, but the field is field.string")] + [InlineData("[\"id\", \"zip\"]", "[\"long\"]", "string", "@params declares 1 parameter type(s) for 2 argument(s)")] + [InlineData("[\"id\", \"zip\"]", "[\"long\", \"string\"]", "string", null)] + public void Origin_function_checks_its_declared_signature(string args, string parameters, string returns, string? fragment) + { + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "C2", "children": [ { "source.rdb": { "@table": "c2" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "zip" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.function": { "@function": "tier_of", "@args": {{args}}, "@params": {{parameters}}, "@returns": "{{returns}}" } } ] } } ] } }, + { "object.projection": { "name": "P2", "children": [ { "source.rdb": { "@kind": "view", "@view": "p2" } }, + { "field.long": { "name": "id", "extends": "C2.id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.passthrough": { "@from": "C2.tier" } } ] } }, + { "identity.primary": { "name": "id", "extends": "C2.id" } } ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var errors = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "f.json")]).Errors; + if (fragment is null) Assert.Empty(errors); + else Assert.Contains(errors, e => e.Code.ToString() == "ERR_INVALID_ORIGIN" && e.Message.Contains(fragment, StringComparison.Ordinal)); + } } diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 609809cf79..ebc642efcc 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1736,9 +1736,22 @@ private static HashSet ProjectionReachedEntityFields(MetaData root) if (FilterPaths.Resolve(bo2, name, out _) is { } p) reached.Add(p.Field); } } + // rc.21 part B fix round (I4): a reached origin.function's arguments are reached too. + foreach (var f in reached.ToList()) ReachFunctionArgs(f, reached); return reached; } + private static void ReachFunctionArgs(MetaData f, HashSet reached) + { + var origin = f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_FUNCTION); + if (origin is null || f.Parent is not { } host) return; + var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); + var names = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + foreach (var name in names.OfType()) + if (host.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) is { } arg && reached.Add(arg)) + ReachFunctionArgs(arg, reached); + } + // ========================================================================= // rc.19 origin-segment and correlated-filter, on every origin.first / origin.aggregate: // @segment names a segment of the related entity (ERR_INVALID_ORIGIN); an @filter operand @@ -1799,10 +1812,28 @@ private static void ValidateFunctionOrigin(MetaData origin, MetaData obj, MetaDa } var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); var args = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + // rc.21 part B fix round (I4): the declared signature (TS _validateFunctionOrigin, message for message). + var rawParams = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_PARAMS); + var parameters = rawParams switch { null => new List(), IReadOnlyList pl => pl.ToList(), _ => new List { rawParams } }; + var returns = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + foreach (var t in parameters.Concat(returns is null ? [] : new[] { returns })) + if (t is not string ts || !ExpressionGrammar.CastTargets.Contains(ts)) + errors.Add(new MetaError( + $"{where}: {System.Text.Json.JsonSerializer.Serialize(t?.ToString())} is not a parameter or return type; use one of {string.Join(", ", ExpressionGrammar.CastTargets)}.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + if (returns is string r && r != field.SubType) + errors.Add(new MetaError( + $"{where}: @returns {r}, but the field is field.{field.SubType}; the declared return type must be the field's type.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + if (parameters.Count != args.Count) + errors.Add(new MetaError( + $"{where}: @params declares {parameters.Count} parameter type(s) for {args.Count} argument(s); declare one per @args entry.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); var isProjection = obj.SubType == OBJECT_SUBTYPE_PROJECTION; var baseEntity = isProjection ? DeriveBaseEntity(obj, root, field.Name, src, new List()) : obj; - foreach (var a in args) + for (var index = 0; index < args.Count; index++) { + var a = args[index]; var name = a as string; var own = name is not null && name != field.Name ? obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) : null; @@ -1821,6 +1852,11 @@ private static void ValidateFunctionOrigin(MetaData origin, MetaData obj, MetaDa errors.Add(new MetaError( $"{where}: @args names \"{a}\", a field.{arg.SubType}{(arg is MetaField af2 && af2.ResolvedIsArray() ? " array" : "")}; a function argument is a scalar.", ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + else if (index < parameters.Count && parameters[index] is string p && arg.SubType != p) + errors.Add(new MetaError( + $"{where}: argument {index + 1} \"{a}\" is a field.{arg.SubType}, but parameter {index + 1} is declared {p}; " + + $"pass an origin.computed field that casts it ({{ cast: {{ field: {a} }}, as: {p} }}).", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); } } diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs index 560c08d2a8..7459942421 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs @@ -93,6 +93,8 @@ public static class OriginConstants public const string ORIGIN_FUNCTION_ATTR_FUNCTION = "function"; public const string ORIGIN_FUNCTION_ATTR_SCHEMA = "schema"; public const string ORIGIN_FUNCTION_ATTR_ARGS = "args"; + public const string ORIGIN_FUNCTION_ATTR_PARAMS = "params"; + public const string ORIGIN_FUNCTION_ATTR_RETURNS = "returns"; /// A plain SQL identifier: what @function and @schema may hold (never free SQL). public static readonly System.Text.RegularExpressions.Regex ORIGIN_FUNCTION_IDENTIFIER = new("^[A-Za-z_][A-Za-z0-9_]*$"); diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs index 2269e13a20..f2a9a072a2 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs @@ -138,6 +138,10 @@ public static class OriginSchema Description: "The schema the function lives in, a plain identifier. Absent: public."), new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_ARGS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, Description: "The fields passed to the function, in parameter order."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_PARAMS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, + Description: "The function's declared parameter types, one field subtype per @args entry."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_RETURNS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, + Description: "The function's declared return type, the carrying field's subtype."), ]; /// diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index 08e8584d24..b175e9b4a8 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -45,12 +45,14 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, - { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." } + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } ] }, { diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java index ddc5d7f396..533e68aa68 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java @@ -31,6 +31,8 @@ public class FunctionOrigin extends MetaOrigin { public static final String ATTR_FUNCTION = "function"; public static final String ATTR_SCHEMA = "schema"; public static final String ATTR_ARGS = "args"; + public static final String ATTR_PARAMS = "params"; + public static final String ATTR_RETURNS = "returns"; public FunctionOrigin(String name) { super(SUBTYPE_FUNCTION, name); @@ -48,6 +50,10 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); def.optionalAttributeWithConstraints(ATTR_ARGS) .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints(ATTR_PARAMS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.requiredAttributeWithConstraints(ATTR_RETURNS) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); }); } } diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 020a116211..318115d570 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -1074,6 +1074,8 @@ def _register_subtypes( AttrSchema(name="function", value_type=ATTR_SUBTYPE_STRING, required=True), AttrSchema(name="schema", value_type=ATTR_SUBTYPE_STRING, required=False), AttrSchema(name="args", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + AttrSchema(name="params", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + AttrSchema(name="returns", value_type=ATTR_SUBTYPE_STRING, required=True), ], child_rules=[ChildRule(TYPE_ATTR, "*")], ) diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index 08e8584d24..b175e9b4a8 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -45,12 +45,14 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, - { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." } + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } ] }, { diff --git a/server/python/tests/loader/test_template_payload_target_210.py b/server/python/tests/loader/test_template_payload_target_210.py index e63bf9902d..b039b79668 100644 --- a/server/python/tests/loader/test_template_payload_target_210.py +++ b/server/python/tests/loader/test_template_payload_target_210.py @@ -83,7 +83,7 @@ def test_assembly_origins_rejected_on_value_host() -> None: "@via": "t::ai::Author.posts", "@orderBy": ["name:desc"]}}, # rc.21 part B (U10). - "function": {"origin.function": {"@function": "f"}}, + "function": {"origin.function": {"@function": "f", "@returns": "int"}}, } assert set(origin_by_subtype) == set(ASSEMBLY_ORIGIN_SUBTYPES) for sub, origin in origin_by_subtype.items(): diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index 1aba835078..03ce1b517a 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -32,6 +32,8 @@ import { ORIGIN_FUNCTION_ATTR_FUNCTION, ORIGIN_FUNCTION_ATTR_SCHEMA, ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_ATTR_PARAMS, + ORIGIN_FUNCTION_ATTR_RETURNS, OBJECT_PROJECTION_ATTR_UNION, OBJECT_PROJECTION_ATTR_UNION_ALL, OBJECT_PROJECTION_ATTR_GRAIN, @@ -1043,17 +1045,42 @@ function temporalOfField(f: MetaField): ReportTemporal { return f.subType === FIELD_SUBTYPE_DATE || f.subType === FIELD_SUBTYPE_TIMESTAMP ? temporalOf(f) : "instant"; } -/** rc.21 part B (U10): an origin.function's call, each argument resolved by `arg` (undefined if one does not). */ -function functionCall(origin: MetaData, arg: (name: string) => ViewExprNode | undefined): ViewExprNode | undefined { +/** + * rc.21 part B (U10): an origin.function's call, each argument resolved by `arg` (undefined if one does + * not), cast to the carrying field's column type (fix round I4: the view column has the field's type + * whatever the function returns). The declared signature is checked here too, for a caller that skipped + * the loader: each argument's subtype is its `@params` entry, and `@returns` is the field's subtype. + */ +function functionCall( + origin: MetaData, field: MetaField, arg: (name: string) => { expr: ViewExprNode; subType: string } | undefined, +): ViewExprNode | undefined { // ADR-0039: own — origin.* never inherits (ADR-0029). const name = origin.ownAttr(ORIGIN_FUNCTION_ATTR_FUNCTION); const schema = origin.ownAttr(ORIGIN_FUNCTION_ATTR_SCHEMA); const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + const rawParams = origin.ownAttr(ORIGIN_FUNCTION_ATTR_PARAMS); + const returns = origin.ownAttr(ORIGIN_FUNCTION_ATTR_RETURNS); if (typeof name !== "string") return undefined; const names = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; - const args = names.map((n) => (typeof n === "string" ? arg(n) : undefined)); - if (args.some((a) => a === undefined)) return undefined; - return { kind: "call", name, ...(typeof schema === "string" ? { schema } : {}), args: args as ViewExprNode[] }; + const params = rawParams === undefined ? [] : Array.isArray(rawParams) ? rawParams : [rawParams]; + const where = `origin.function "${name}" on "${field.name}"`; + if (returns !== field.subType) { + throw new Error(`${where}: @returns ${String(returns)}, but the field is field.${field.subType}; the declared return type must be the field's type.`); + } + if (params.length !== names.length) { + throw new Error(`${where}: @params declares ${params.length} parameter type(s) for ${names.length} argument(s).`); + } + const args: ViewExprNode[] = []; + for (const [i, n] of names.entries()) { + const a = typeof n === "string" ? arg(n) : undefined; + if (a === undefined) return undefined; + if (a.subType !== params[i]) { + throw new Error(`${where}: argument ${i + 1} "${String(n)}" is a field.${a.subType}, but parameter ${i + 1} is declared ${String(params[i])}; cast it through an origin.computed field.`); + } + args.push(a.expr); + } + const call: ViewExprNode = { kind: "call", name, ...(typeof schema === "string" ? { schema } : {}), args }; + return { kind: "cast", arg: call, to: { subType: field.subType } }; } /** rc.21 part B (U14): the value object a `@grain` projection's rows are elements of, if it has one. */ @@ -1747,8 +1774,13 @@ function buildSelectSpec( if (c.kind === "aggregate" || c.kind === "predicateAgg") return { expr: { kind: "agg", column: c }, field: f }; throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to "${ref}", a collect; a computed value cannot read an array.`); }; + const argOf = (arg: string): { expr: ViewExprNode; subType: string } | undefined => { + const e = resolveExprNode({ field: arg }, base, joinTree.baseAlias, ctx, lookup); + const f = lookup(arg)?.field ?? base.fields().find((x) => x.name === arg); + return e === undefined || f === undefined ? undefined : { expr: e, subType: f.subType }; + }; const expr = pending.origin.subType === ORIGIN_SUBTYPE_FUNCTION - ? functionCall(pending.origin, (arg) => resolveExprNode({ field: arg }, base, joinTree.baseAlias, ctx, lookup)) + ? functionCall(pending.origin, pending.field, argOf) : resolveExprNode(pending.origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), base, joinTree.baseAlias, ctx, lookup); resolving.delete(name); pendingComputed.delete(name); @@ -2008,7 +2040,13 @@ export function inlineEntityDerived( if (first !== undefined) return { kind: "first", column: { ...first, outerAlias: alias } }; } else if (origin?.subType === ORIGIN_SUBTYPE_FUNCTION) { // rc.21 part B (U10): the call, its arguments read on the reached row. - const call = functionCall(origin, (arg) => resolveExprNode({ field: arg }, entity, alias, ctx)); + const call = functionCall(origin, field, (arg) => { + const f = entity.fields().find((x) => x.name === arg); + if (f === undefined) return undefined; + // An argument that is itself derived (an origin.computed cast, say) inlines on the same row. + const e = f.isDerived() ? inlineEntityDerived(f, entity, alias, root, usedAliases, ctx, where) : resolveExprNode({ field: arg }, entity, alias, ctx); + return e === undefined ? undefined : { expr: e, subType: f.subType }; + }); if (call !== undefined) return call; } throw new Error( diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts index 6a474f2992..952eaf9bd4 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts @@ -24,7 +24,7 @@ export const RC21B_ENTITIES: unknown[] = [ { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, { "field.string": { name: "loyaltyTier", children: [ - { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"] } } ] } }, + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } }, ] } }, { "object.entity": { name: "Address", children: [ { "source.rdb": { "@table": "addresses" } }, diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts index aab45ac269..0f4b12bfa3 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -136,7 +136,15 @@ describe("U10 origin.function", () => { test("postgres: the declared call, its arguments read on the reached row", async () => { const sql = await one("postgres", orderRow([ { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])); - expect(sql).toContain("app.loyalty_tier(c.id, c.zip) AS tier"); + // fix round I4: the call is cast to the field's column type, so the column has it. + expect(sql).toContain("CAST(app.loyalty_tier(c.id, c.zip) AS TEXT) AS tier"); + }); + test("codegen refuses a signature the loader would refuse (a caller that skipped it)", async () => { + const bad = JSON.parse(JSON.stringify(RC21B_ENTITIES).replace('"@params":["long","string"]', '"@params":["int","string"]')); + const doc = { "metadata.root": { package: "acme", children: [...bad, orderRow([ + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])] } }; + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(() => buildProjectionViews(root, { dialect: "postgres" })).toThrow(/argument 1 "id" is a field.long, but parameter 1 is declared int/); }); test("a SQLite view refuses it: SQLite has no stored functions", async () => { const doc = { "metadata.root": { package: "acme", children: [...RC21B_ENTITIES, orderRow([ diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts index ca48c4dd99..c80244f39f 100644 --- a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -34,7 +34,7 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, { "field.string": { name: "loyaltyTier", children: [ - { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"] } } ] } } ] } }, + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } } ] } }, { "object.entity": { name: "Address", children: [ { "source.rdb": { "@table": "addresses" } }, { "field.long": { name: "id" } }, @@ -144,6 +144,9 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { ]); const nothingType = await rows(`SELECT data_type FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name = 'nothing'`); expect(nothingType).toEqual([{ data_type: "character varying" }]); + // I4: the function's call is cast to the carrying field's column type. + expect(await rows(`SELECT data_type FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name = 'tier'`)) + .toEqual([{ data_type: "text" }]); await sql.raw(` INSERT INTO regions (id, code, label, note) VALUES (1, 'NE', 'north east', 'n'); diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 64836d3590..aba822a255 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -129,6 +129,8 @@ import { ORIGIN_FUNCTION_ATTR_FUNCTION, ORIGIN_FUNCTION_ATTR_SCHEMA, ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_ATTR_PARAMS, + ORIGIN_FUNCTION_ATTR_RETURNS, ORIGIN_FUNCTION_IDENTIFIER, ORIGIN_PASSTHROUGH_ATTR_FROM, ORIGIN_PASSTHROUGH_ATTR_VIA, @@ -157,6 +159,7 @@ import { inferExprType, validateExprNode, exprViewOnlyNode, + EXPR_CAST_TARGETS, type ExprNode, } from "../core/attr/meta-attr-expression.js"; import { SORT_ORDER_VALUES } from "../core/query/query-constants.js"; @@ -1863,9 +1866,31 @@ function _validateFunctionOrigin(origin: MetaData, obj: MetaData, field: MetaDat } const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); const args = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; + // rc.21 part B fix round (I4): the declared signature. Each parameter and the result is a field + // subtype (the cast targets); the result is the carrying field's, each argument its parameter's. + const rawParams = origin.ownAttr(ORIGIN_FUNCTION_ATTR_PARAMS); + const params = rawParams === undefined ? [] : Array.isArray(rawParams) ? rawParams : [rawParams]; + const returns = origin.ownAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + for (const t of [...params, ...(returns === undefined ? [] : [returns])]) { + if (typeof t !== "string" || !EXPR_CAST_TARGETS.includes(t)) { + errors.push(new ParseError( + `${where}: ${JSON.stringify(t)} is not a parameter or return type; use one of ${EXPR_CAST_TARGETS.join(", ")}.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + } + if (typeof returns === "string" && returns !== field.subType) { + errors.push(new ParseError( + `${where}: @returns ${returns}, but the field is field.${field.subType}; the declared return type must be the field's type.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + if (params.length !== args.length) { + errors.push(new ParseError( + `${where}: @params declares ${params.length} parameter type(s) for ${args.length} argument(s); declare one per @args entry.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } const isProjection = obj.subType === OBJECT_SUBTYPE_PROJECTION; const base = isProjection ? _deriveBaseEntity(obj, root, field.name, src, []) : obj; - for (const name of args) { + for (const [index, name] of args.entries()) { const own = typeof name === "string" && name !== field.name ? obj.children().find((c) => c.type === TYPE_FIELD && c.name === name) : undefined; const ownOrigin = own?.ownChildren().find((c) => c.type === TYPE_ORIGIN); @@ -1883,6 +1908,11 @@ function _validateFunctionOrigin(origin: MetaData, obj: MetaData, field: MetaDat errors.push(new ParseError( `${where}: @args names "${String(name)}", a field.${arg.subType}${(arg as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() ? " array" : ""}; a function argument is a scalar.`, { code: "ERR_INVALID_ORIGIN", source: src })); + } else if (typeof params[index] === "string" && arg.subType !== params[index]) { + errors.push(new ParseError( + `${where}: argument ${index + 1} "${String(name)}" is a field.${arg.subType}, but parameter ${index + 1} is declared ${String(params[index])}; ` + + `pass an origin.computed field that casts it ({ cast: { field: ${String(name)} }, as: ${String(params[index])} }).`, + { code: "ERR_INVALID_ORIGIN", source: src })); } } } @@ -1993,9 +2023,27 @@ export function projectionReachedEntityFields(root: MetaData): Set { } } } + // rc.21 part B fix round (I4): a reached origin.function inlines its arguments on the same row, so a + // derived argument (an origin.computed cast, say) is reached too. + for (const f of [...reached]) _reachFunctionArgs(f, reached); return reached; } +function _reachFunctionArgs(f: MetaData, reached: Set): void { + // ADR-0039: own — origin.* never inherits (ADR-0029). + const origin = f.ownChildren().find((c) => c.type === TYPE_ORIGIN && c.subType === ORIGIN_SUBTYPE_FUNCTION); + const host = f.parent; + if (origin === undefined || host === undefined) return; + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + for (const name of raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]) { + const arg = host.children().find((c) => c.type === TYPE_FIELD && c.name === name); + if (arg !== undefined && !reached.has(arg)) { + reached.add(arg); + _reachFunctionArgs(arg, reached); + } + } +} + /** * rc.19 origin-segment and correlated-filter, on every origin.first / origin.aggregate: * - `@segment` names a segment.filter declared on the related entity (the @of entity, else diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts index 58fca964bd..815f37dd41 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts @@ -89,6 +89,8 @@ export const ORIGIN_FIRST_ATTR_FILTER = "filter"; export const ORIGIN_FUNCTION_ATTR_FUNCTION = "function"; export const ORIGIN_FUNCTION_ATTR_SCHEMA = "schema"; export const ORIGIN_FUNCTION_ATTR_ARGS = "args"; +export const ORIGIN_FUNCTION_ATTR_PARAMS = "params"; +export const ORIGIN_FUNCTION_ATTR_RETURNS = "returns"; /** A plain SQL identifier: what @function and @schema may hold (never free SQL). */ export const ORIGIN_FUNCTION_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/; diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index ab1561f855..606d9c3a99 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -141,7 +141,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { @@ -167,7 +167,24 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "isArray": true, "min": 0, "max": 1, - "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." + "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." + }, + { + "type": "attr", + "subType": "string", + "name": "params", + "isArray": true, + "min": 0, + "max": 1, + "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." + }, + { + "type": "attr", + "subType": "string", + "name": "returns", + "min": 1, + "max": 1, + "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } ] }, diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index a0966e2c8b..6c641d4c78 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -151,15 +151,31 @@ describe("U10 — origin.function", () => { { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer2.tier" } } ] } }, { "identity.primary": { name: "id", extends: "Customer2.id" } } ] } }; test("a declared call on an entity, reached by a projection, loads", async () => { - await ok(withFn({ "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"] }), reach); + await ok(withFn({ "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" }), reach); }); test("free SQL, an unknown argument and a non-scalar argument are refused", async () => { - await refused("ERR_INVALID_ORIGIN", /is not a plain identifier/, withFn({ "@function": "tier_of(1); drop table x", "@args": [] }), reach); - await refused("ERR_INVALID_ORIGIN", /@args names "nope"/, withFn({ "@function": "tier_of", "@args": ["nope"] }), reach); - await refused("ERR_INVALID_ORIGIN", /a field.object array; a function argument is a scalar/, withFn({ "@function": "tier_of", "@args": ["contacts"] }), reach); + await refused("ERR_INVALID_ORIGIN", /is not a plain identifier/, withFn({ "@function": "tier_of(1); drop table x", "@args": [], "@returns": "string" }), reach); + await refused("ERR_INVALID_ORIGIN", /@args names "nope"/, withFn({ "@function": "tier_of", "@args": ["nope"], "@params": ["long"], "@returns": "string" }), reach); + await refused("ERR_INVALID_ORIGIN", /a field.object array; a function argument is a scalar/, withFn({ "@function": "tier_of", "@args": ["contacts"], "@params": ["string"], "@returns": "string" }), reach); + }); + // rc.21 part B fix round (I4): the declared signature is checked. + test("an argument of another type than its parameter, a return type other than the field's, and a short @params are refused", async () => { + await refused("ERR_INVALID_ORIGIN", /argument 1 "id" is a field.long, but parameter 1 is declared int; pass an origin.computed field that casts it/, + withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["int"], "@returns": "string" }), reach); + await refused("ERR_INVALID_ORIGIN", /@returns int, but the field is field.string/, withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["long"], "@returns": "int" }), reach); + await refused("ERR_INVALID_ORIGIN", /@params declares 1 parameter type\(s\) for 2 argument\(s\)/, + withFn({ "@function": "tier_of", "@args": ["id", "zip"], "@params": ["long"], "@returns": "string" }), reach); + await refused("ERR_MISSING_REQUIRED_ATTR", /returns/, withFn({ "@function": "tier_of", "@args": [] }), reach); + }); + test("an argument cast through an origin.computed field loads", async () => { + await ok({ "object.entity": { name: "Customer2", children: [ + { "source.rdb": { "@table": "customers2" } }, { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "field.int": { name: "idAsInt", children: [ { "origin.computed": { "@expr": { cast: { field: "id" }, as: "int" } } } ] } }, + { "field.string": { name: "tier", children: [ { "origin.function": { "@function": "tier_of", "@args": ["idAsInt"], "@params": ["int"], "@returns": "string" } } ] } } ] } }, reach); }); test("an unreached function field on an entity with no read source is refused", async () => { - await refused("ERR_DERIVED_FIELD_NO_READ_SOURCE", /tier/, withFn({ "@function": "tier_of", "@args": ["id"] })); + await refused("ERR_DERIVED_FIELD_NO_READ_SOURCE", /tier/, withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["long"], "@returns": "string" })); }); }); diff --git a/server/typescript/packages/metadata/test/template-payload-target-210.test.ts b/server/typescript/packages/metadata/test/template-payload-target-210.test.ts index 195a410524..86714d5216 100644 --- a/server/typescript/packages/metadata/test/template-payload-target-210.test.ts +++ b/server/typescript/packages/metadata/test/template-payload-target-210.test.ts @@ -81,7 +81,7 @@ describe("#210 — assembly origins are illegal on an object.value host", () => computed: { "origin.computed": { "@expr": { op: "isNotNull", arg: { field: "name" } } } }, first: { "origin.first": { "@of": "t::ai::Author.name", "@via": "t::ai::Author.posts", "@orderBy": ["name:desc"] } }, // rc.21 part B (U10). - function: { "origin.function": { "@function": "f" } }, + function: { "origin.function": { "@function": "f", "@returns": "int" } }, }; test("the originNode table covers exactly the ASSEMBLY_ORIGIN_SUBTYPES set (drift guard)", () => { diff --git a/site-reference/index.html b/site-reference/index.html index 03aaa12a52..69b27d60f1 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -312,7 +312,7 @@ - + diff --git a/site-reference/providers.html b/site-reference/providers.html index 673e8f1f11..e6eb5152ff 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -73,7 +73,7 @@

    metaobjects-core-types

  • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @segment, @via
  • origin.computed: @expr
  • origin.first: @filter, @of, @orderBy, @segment, @via
  • -
  • origin.function: @args, @function, @schema
  • +
  • origin.function: @args, @function, @params, @returns, @schema
  • origin.passthrough: @convert, @from, @via
  • relationship.aggregation: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • relationship.association: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
  • diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index cbc8087926..a8ac236d15 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -237,7 +237,7 @@

    origin.first

    Allowed children

    No structural children.

    origin.function

    -

    A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.

    +

    A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.

    Owning provider: metaobjects-core-types

    When to use: A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.

    Attributes

    @@ -260,7 +260,7 @@

    origin.function

    - + @@ -272,6 +272,24 @@

    origin.function

    + + + + + + + + + + + + + + + + + + diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index 08e8584d24..b175e9b4a8 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -45,12 +45,14 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, - { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." } + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, + { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } ] }, { From e5eac5c83aac126b11fdaf7da48dedc81956ff00 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:52:21 -0500 Subject: [PATCH 203/267] fix(views): casts Postgres has, guarded grains, value-mapped grain members, union value maps, SQLite string counts - A boolean casts only to and from int, and a count parameter (left, right, substring, splitPart) takes only an int: Postgres has no other boolean cast, and resolves those functions over int4 only (TS, C#). - A @grain over a value that is not a JSON array (null, an object, a scalar) yields no element instead of failing the query (jsonb_typeof / json_type guards). - A @grain member that is a value-mapped enum is refused: the element holds the symbol (TS, C#). - A @union compares enum members and value maps, and refuses a member that declares its own @union (TS, C#). - SQLite's left, right and substring give Postgres's meaning for a non-positive count or start. Co-Authored-By: Claude Opus 5.5 --- .../ViewVocabularyRc21LoaderTests.cs | 20 +++++++++++ .../Core/Attr/ExpressionGrammar.cs | 11 +++++-- .../MetaObjects/Loader/ValidationPasses.cs | 13 +++++++- .../src/projection/view-ddl-emit.ts | 28 +++++++++++++--- .../projection/rc21b-view-vocabulary.test.ts | 33 +++++++++++++++++-- .../test/view-vocabulary-rc21-pg.test.ts | 6 ++-- .../src/core/attr/meta-attr-expression.ts | 13 +++++--- .../metadata/src/loader/validation-passes.ts | 18 +++++++++- .../test/rc21b-view-vocabulary.test.ts | 31 +++++++++++++++++ 9 files changed, 154 insertions(+), 19 deletions(-) diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index be579a7590..250b1eed01 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -245,4 +245,24 @@ public void Origin_function_checks_its_declared_signature(string args, string pa if (fragment is null) Assert.Empty(errors); else Assert.Contains(errors, e => e.Code.ToString() == "ERR_INVALID_ORIGIN" && e.Message.Contains(fragment, StringComparison.Ordinal)); } + + // rc.21 part B fix round (M1, M4): casts Postgres has; a union member's own @union is refused. + [Fact] + public void A_boolean_casts_only_with_int_and_a_count_parameter_takes_only_an_int() + { + Refused("ERR_INVALID_ORIGIN", "a long cannot be cast to boolean; only an int can", View(Computed("a", "boolean", Cast(F("id"), "boolean")))); + Refused("ERR_INVALID_ORIGIN", "'left' argument 2 must be an int, got long", View(Computed("a", "string", Fn("left", F("ref"), F("id"))))); + Assert.Empty(Load(View(Computed("a", "boolean", Cast(F("n"), "boolean"))))); + } + + [Fact] + public void A_union_member_with_its_own_union_is_refused() + { + Refused("ERR_BAD_ATTR_VALUE", "member \"B\" declares its own @union", """ + { "object.projection": { "name": "A", "abstract": true, "children": [ { "field.long": { "name": "personId", "extends": "Customer.id" } } ] } }, + { "object.projection": { "name": "B", "abstract": true, "@union": ["C"], "children": [ { "field.long": { "name": "personId", "extends": "Order.customerId" } } ] } }, + { "object.projection": { "name": "C", "abstract": true, "children": [ { "field.long": { "name": "personId", "extends": "Order.id" } } ] } }, + { "object.projection": { "name": "U", "extends": "A", "@union": ["B"], "children": [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } } + """); + } } diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index dd01e70ee8..0f761e0a31 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -99,8 +99,13 @@ private sealed record FnSignature(int Min, int Max, ParamKind[] Params, string R } if (to == FIELD_SUBTYPE_STRING) return null; if (from == FIELD_SUBTYPE_STRING) return null; - if (NumericSubtypes.Contains(to)) return NumericSubtypes.Contains(from) || from == FIELD_SUBTYPE_BOOLEAN ? null : $"a {from} cannot be cast to {to}"; - if (to == FIELD_SUBTYPE_BOOLEAN) return IntegerSubtypes.Contains(from) ? null : $"a {from} cannot be cast to boolean"; + // Postgres casts a boolean only to and from integer (int4), so those are the only number casts. + if (NumericSubtypes.Contains(to)) + { + if (from == FIELD_SUBTYPE_BOOLEAN) return to == FIELD_SUBTYPE_INT ? null : $"a boolean casts only to int, not {to}"; + return NumericSubtypes.Contains(from) ? null : $"a {from} cannot be cast to {to}"; + } + if (to == FIELD_SUBTYPE_BOOLEAN) return from == FIELD_SUBTYPE_INT ? null : $"a {from} cannot be cast to boolean; only an int can"; if (to is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIMESTAMP) return from is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIMESTAMP ? null : $"a {from} cannot be cast to {to}"; return $"a {from} cannot be cast to {to}"; @@ -383,7 +388,7 @@ public static InferResult InferExprType(object? node, Func reso var kind = sig.Params[Math.Min(i, sig.Params.Length - 1)]; if (kind == ParamKind.Same) same.Add(t); else if (kind == ParamKind.String && t != FIELD_SUBTYPE_STRING) errors.Add($"'{name}' argument {i + 1} must be a string, got {t}"); - else if (kind == ParamKind.Int && !IntegerSubtypes.Contains(t)) errors.Add($"'{name}' argument {i + 1} must be an integer, got {t}"); + else if (kind == ParamKind.Int && t != FIELD_SUBTYPE_INT) errors.Add($"'{name}' argument {i + 1} must be an int, got {t}{(t == FIELD_SUBTYPE_LONG ? "; cast it ({ cast: , as: int })" : "")}"); else if (kind == ParamKind.Scalar && NonScalarSubtypes.Contains(t)) errors.Add($"'{name}' argument {i + 1} must be a scalar, got {t}"); } string? unified = same.Count > 0 ? same[0] : null; diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index ebc642efcc..ac90f2aa23 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -528,6 +528,12 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) errors.Add(new MetaError( $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" reads the @grain element, which takes no @via.", ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); + // fix round M2: a value-mapped enum member is held in the document as its symbol. + if (gt.Field.SubType == FIELD_SUBTYPE_ENUM && (gt.Field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null || gt.Field.Attr(FIELD_ATTR_STRING_VALUE_MAP) is not null)) + errors.Add(new MetaError( + $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" is an enum with a value map, but a @grain element holds the member's symbol; " + + "read it as a field.string, or drop the map on the value object's member.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); continue; } // FR-024 B6 — extends/origin agreement (host-agnostic; runs @@ -1892,7 +1898,10 @@ static string Describe(MetaData f) { var arr = f is MetaField mf && mf.ResolvedIsArray() ? "[]" : ""; var col = f.Attr(FIELD_ATTR_COLUMN) is string c ? $" @column {c}" : ""; - return $"{f.Name}: field.{f.SubType}{arr}{col}"; + // fix round M4: an enum's members and value maps are part of the column's meaning. + var enumShape = f.SubType != FIELD_SUBTYPE_ENUM ? "" + : " " + System.Text.Json.JsonSerializer.Serialize(new object?[] { f.Attr(FIELD_ATTR_VALUES), f.Attr(FIELD_ATTR_INT_VALUE_MAP), f.Attr(FIELD_ATTR_STRING_VALUE_MAP) }); + return $"{f.Name}: field.{f.SubType}{arr}{col}{enumShape}"; } foreach (var nameObj in names) { @@ -1907,6 +1916,8 @@ static string Describe(MetaData f) Bad($"@{OBJECT_PROJECTION_ATTR_UNION} names the projection itself."); continue; } + if (member.OwnAttr(OBJECT_PROJECTION_ATTR_UNION) is not null) + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} member \"{member.Name}\" declares its own @{OBJECT_PROJECTION_ATTR_UNION}; name its members here instead."); var a = mine.Select(Describe).ToList(); var b = member.Children().Where(c => c.Type == TYPE_FIELD).Select(Describe).ToList(); if (!a.SequenceEqual(b)) diff --git a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts index d05e951a2a..b62965ab63 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts @@ -184,9 +184,20 @@ function renderFn(name: string, args: readonly string[], nodes: readonly ViewExp case "replace": return `REPLACE(${list})`; case "nullif": return `NULLIF(${list})`; case "length": return pg ? `CHAR_LENGTH(${list})` : `LENGTH(${list})`; - case "substring": return `SUBSTR(${list})`; - case "left": return pg ? `LEFT(${list})` : `SUBSTR(${args[0]}, 1, ${args[1]})`; - case "right": return pg ? `RIGHT(${list})` : `(CASE WHEN ${args[1]} > 0 THEN SUBSTR(${args[0]}, -(${args[1]})) ELSE '' END)`; + // fix round M9: SQLite's substr counts a non-positive start from the end, and has no left/right; + // these spellings give Postgres's meaning for every count (a negative one included). + case "substring": { + if (pg) return `SUBSTR(${list})`; + const [str, start, len] = args; + const from1 = len === undefined ? `SUBSTR(${str}, 1)` : `SUBSTR(${str}, 1, MAX((${len}) + (${start}) - 1, 0))`; + return `(CASE WHEN ${start} >= 1 THEN SUBSTR(${list}) ELSE ${from1} END)`; + } + case "left": + return pg ? `LEFT(${list})` + : `(CASE WHEN ${args[1]} >= 0 THEN SUBSTR(${args[0]}, 1, ${args[1]}) ELSE SUBSTR(${args[0]}, 1, MAX(LENGTH(${args[0]}) + (${args[1]}), 0)) END)`; + case "right": + return pg ? `RIGHT(${list})` + : `(CASE WHEN ${args[1]} > 0 THEN SUBSTR(${args[0]}, -(${args[1]})) WHEN ${args[1]} = 0 THEN '' ELSE SUBSTR(${args[0]}, 1 - (${args[1]})) END)`; case "concat": return pg ? `CONCAT(${list})` : `(${args.map((a) => `COALESCE(CAST(${a} AS TEXT), '')`).join(" || ")})`; case "concatWs": { @@ -578,6 +589,11 @@ export function emitViewDdl(spec: ViewSpec, options: EmitOptions): string { ${body};`; } +/** A @grain view's array column on its base row. */ +function grainCol(spec: ViewSpec): string { + return `${spec.joinTree.baseAlias}.${quoteIfNeeded(spec.grain!.column)}`; +} + /** One SELECT of a view: its columns, base, grain, joins, WHERE and GROUP BY. */ function emitViewBody(spec: ViewSpec, options: EmitOptions): string { const cols = spec.selectSpec.columns @@ -586,8 +602,10 @@ function emitViewBody(spec: ViewSpec, options: EmitOptions): string { // rc.21 part B (U14): a @grain view reads one row per element of the base row's jsonb array. const grain = spec.grain === undefined ? "" : options.dialect === "postgres" - ? ` CROSS JOIN LATERAL jsonb_array_elements(${spec.joinTree.baseAlias}.${quoteIfNeeded(spec.grain.column)}) WITH ORDINALITY AS ${GRAIN_ALIAS}(value, ordinality)` - : ` CROSS JOIN json_each(${spec.joinTree.baseAlias}.${quoteIfNeeded(spec.grain.column)}) ${GRAIN_ALIAS}`; + // fix round M3: a row whose value is JSON null, an object or a scalar has no element (rather than + // failing the whole query on Postgres, or iterating an object's keys on SQLite). + ? ` CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(${grainCol(spec)}) = 'array' THEN ${grainCol(spec)} END) WITH ORDINALITY AS ${GRAIN_ALIAS}(value, ordinality)` + : ` CROSS JOIN json_each(CASE WHEN json_type(${grainCol(spec)}) = 'array' THEN ${grainCol(spec)} END) ${GRAIN_ALIAS}`; const fromClause = ` FROM ${viewRelation(spec.joinTree.baseEntity, options.baseTableName, options)} ${spec.joinTree.baseAlias}${grain}`; const joinsClause = spec.joinTree.joins .map((j) => renderJoin(j, spec.joinTree.baseAlias, options)) diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts index 0f4b12bfa3..013891e003 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -163,7 +163,8 @@ describe("U14 @grain — one row per array element", () => { { "field.int": { name: "rank", children: [ { "origin.passthrough": { "@from": "Contact.rank" } } ] } } ] } }; test("postgres", async () => { const sql = await one("postgres", p); - expect(sql).toContain("FROM public.customers c CROSS JOIN LATERAL jsonb_array_elements(c.contacts) WITH ORDINALITY AS mo_el(value, ordinality)"); + // fix round M3: a non-array value (JSON null, an object, a scalar) has no element. + expect(sql).toContain("FROM public.customers c CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(c.contacts) = 'array' THEN c.contacts END) WITH ORDINALITY AS mo_el(value, ordinality)"); expect(sql).toContain("CAST(mo_el.ordinality AS INTEGER) AS position"); expect(sql).toContain("(mo_el.value ->> 'kind') AS kind"); expect(sql).toContain("CAST((mo_el.value ->> 'rank') AS INTEGER) AS rank"); @@ -172,7 +173,7 @@ describe("U14 @grain — one row per array element", () => { const sql = await one("sqlite", p); const db = new Database(":memory:"); db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); - db.run(`INSERT INTO customers (id, contacts) VALUES (1, '[{"kind":"email","rank":1},{"kind":"phone","rank":2}]'), (2, '[]'), (3, NULL)`); + db.run(`INSERT INTO customers (id, contacts) VALUES (1, '[{"kind":"email","rank":1},{"kind":"phone","rank":2}]'), (2, '[]'), (3, NULL), (4, '{"kind":"x"}'), (5, 'null'), (6, '7')`); db.run(`CREATE VIEW v AS ${sql}`); expect(db.query("SELECT customer_id, position, kind, rank FROM v ORDER BY customer_id, position").all()).toEqual([ { customer_id: 1, position: 1, kind: "email", rank: 1 }, @@ -289,3 +290,31 @@ describe("a projection over a TPH root reads its subtypes' columns; a unique rev expect((await withUnique("partial")).errors.some((m) => /is to-many/.test(m))).toBe(true); }); }); + +// rc.21 part B fix round (M9): SQLite's left / right / substring give Postgres's meaning for every count. +describe("SQLite left, right and substring over non-positive counts", () => { + test("match Postgres", async () => { + const p = orderRow([ + computed("l2", "string", { fn: "left", args: [{ field: "externalRef" }, { value: 2 }] }), + computed("lm2", "string", { fn: "left", args: [{ field: "externalRef" }, { value: -2 }] }), + computed("lm9", "string", { fn: "left", args: [{ field: "externalRef" }, { value: -9 }] }), + computed("r2", "string", { fn: "right", args: [{ field: "externalRef" }, { value: 2 }] }), + computed("rm2", "string", { fn: "right", args: [{ field: "externalRef" }, { value: -2 }] }), + computed("r0", "string", { fn: "right", args: [{ field: "externalRef" }, { value: 0 }] }), + computed("s23", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: 2 }, { value: 3 }] }), + computed("s03", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: 0 }, { value: 3 }] }), + computed("sm13", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: -1 }, { value: 3 }] }), + computed("sm1", "string", { fn: "substring", args: [{ field: "externalRef" }, { value: -1 }] }), + ]); + const sql = await one("sqlite", p); + const db = new Database(":memory:"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, stage INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("INSERT INTO orders (id, external_ref) VALUES (1, 'abcdef')"); + db.run(`CREATE VIEW v AS ${sql}`); + // Postgres: left('abcdef',2)='ab', left(-2)='abcd', left(-9)='', right(2)='ef', right(-2)='cdef', right(0)='', + // substr(s,2,3)='bcd', substr(s,0,3)='ab', substr(s,-1,3)='a', substr(s,-1)='abcdef'. + expect(db.query("SELECT l2, lm2, lm9, r2, rm2, r0, s23, s03, sm13, sm1 FROM v").get()).toEqual({ + l2: "ab", lm2: "abcd", lm9: "", r2: "ef", rm2: "cdef", r0: "", s23: "bcd", s03: "ab", sm13: "a", sm1: "abcdef", + }); + }); +}); diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts index c80244f39f..bde4236cf5 100644 --- a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -152,8 +152,8 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { INSERT INTO regions (id, code, label, note) VALUES (1, 'NE', 'north east', 'n'); INSERT INTO customers (id, first_name, last_name, zip, region_id, contacts) VALUES (10, 'Ada', 'Lovelace', '02139-4307', 1, '[{"kind":"email","preferred":true,"rank":1},{"kind":"phone","preferred":false,"rank":2}]'), - (11, ' Alan', 'Turing ', '12345', 1, '[]'), - (12, NULL, 'Hopper', NULL, NULL, NULL); + (11, ' Alan', 'Turing ', '12345', 1, '{"kind":"not an array"}'), + (12, NULL, 'Hopper', NULL, NULL, 'null'); INSERT INTO addresses (id, customer_id, street) VALUES (100, 10, 'Lovelace'), (101, 11, 'Main St'); INSERT INTO orders (id, customer_id, status, stage, external_ref, updated_at) VALUES (1, 10, 1, 0, NULL, '2026-01-05T00:00:00Z'), @@ -180,7 +180,7 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { tier: null, last_event: null, first_at_status: null, touched: null, earliest: null, event_by_customer: null }, ]); - // U14: one row per element; a customer with an empty or NULL array has none. + // U14: one row per element; a customer whose value is an object or JSON null has none (fix round M3). expect(await rows(`SELECT customer_id, position, kind, preferred, rank FROM v_customer_contact ORDER BY customer_id, position`)).toEqual([ { customer_id: "10", position: 1, kind: "email", preferred: true, rank: 1 }, { customer_id: "10", position: 2, kind: "phone", preferred: false, rank: 2 }, diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index 4c02468b61..6014549e86 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -132,8 +132,12 @@ export function castProblem(from: string | undefined, to: string, intStoredEnum: } if (to === FIELD_SUBTYPE_STRING) return undefined; if (from === FIELD_SUBTYPE_STRING) return undefined; // the database parses it - if (NUMERIC_SUBTYPES.has(to)) return NUMERIC_SUBTYPES.has(from) || from === FIELD_SUBTYPE_BOOLEAN ? undefined : `a ${from} cannot be cast to ${to}`; - if (to === FIELD_SUBTYPE_BOOLEAN) return INTEGER_SUBTYPES.has(from) ? undefined : `a ${from} cannot be cast to boolean`; + // Postgres casts a boolean only to and from integer (int4), so those are the only number casts. + if (NUMERIC_SUBTYPES.has(to)) { + if (from === FIELD_SUBTYPE_BOOLEAN) return to === FIELD_SUBTYPE_INT ? undefined : `a boolean casts only to int, not ${to}`; + return NUMERIC_SUBTYPES.has(from) ? undefined : `a ${from} cannot be cast to ${to}`; + } + if (to === FIELD_SUBTYPE_BOOLEAN) return from === FIELD_SUBTYPE_INT ? undefined : `a ${from} cannot be cast to boolean; only an int can`; if (to === FIELD_SUBTYPE_DATE || to === FIELD_SUBTYPE_TIMESTAMP) { return from === FIELD_SUBTYPE_DATE || from === FIELD_SUBTYPE_TIMESTAMP ? undefined : `a ${from} cannot be cast to ${to}`; } @@ -357,8 +361,9 @@ export function inferExprType( if (kind === "same") same.push(a.type); else if (kind === "string" && a.type !== FIELD_SUBTYPE_STRING) { errors.push(`'${name}' argument ${i + 1} must be a string, got ${a.type}`); - } else if (kind === "int" && !INTEGER_SUBTYPES.has(a.type)) { - errors.push(`'${name}' argument ${i + 1} must be an integer, got ${a.type}`); + } else if (kind === "int" && a.type !== FIELD_SUBTYPE_INT) { + // Postgres resolves these functions over int4 only (no implicit bigint → int for a call). + errors.push(`'${name}' argument ${i + 1} must be an int, got ${a.type}${a.type === FIELD_SUBTYPE_LONG ? "; cast it ({ cast: , as: int })" : ""}`); } else if (kind === "scalar" && NON_SCALAR_SUBTYPES.has(a.type)) { errors.push(`'${name}' argument ${i + 1} must be a scalar, got ${a.type}`); } diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index aba822a255..e23754ba63 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1497,6 +1497,15 @@ export function validateOriginPaths(root: MetaData): ParseError[] { `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" reads the @grain element, which takes no @via.`, { code: "ERR_INVALID_ORIGIN", source: origin.source })); } + // fix round M2: a value object's enum member is held in the document as its symbol; a value + // map (@intValueMap / @stringValueMap) describes a column the element does not have. + if (fromTarget.field.subType === FIELD_SUBTYPE_ENUM + && (fromTarget.field.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined || fromTarget.field.attr(FIELD_ATTR_STRING_VALUE_MAP) !== undefined)) { + errors.push(new ParseError( + `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" is an enum with a value map, but a @grain element holds the member's symbol; ` + + `read it as a field.string, or drop the map on the value object's member.`, + { code: "ERR_INVALID_ORIGIN", source: origin.source })); + } continue; } // FR-024 B6 — extends/origin agreement (host-agnostic; runs whether @@ -3406,11 +3415,18 @@ export function validateProjectionUnionAndGrain(root: MetaData): ParseError[] { continue; } const theirs = member.children().filter((c) => c.type === TYPE_FIELD); + // fix round M4: an enum's members and value maps are part of the column's meaning. const describe = (f: MetaData): string => { const arr = (f as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() === true ? "[]" : ""; const col = f.attr(FIELD_ATTR_COLUMN); - return `${f.name}: field.${f.subType}${arr}${typeof col === "string" ? ` @column ${col}` : ""}`; + const enumShape = f.subType !== FIELD_SUBTYPE_ENUM ? "" + : ` ${JSON.stringify([f.attr(FIELD_ATTR_VALUES) ?? null, f.attr(FIELD_ATTR_INT_VALUE_MAP) ?? null, f.attr(FIELD_ATTR_STRING_VALUE_MAP) ?? null])}`; + return `${f.name}: field.${f.subType}${arr}${typeof col === "string" ? ` @column ${col}` : ""}${enumShape}`; }; + // fix round M4: a member's own @union would be flattened away, silently. + if (member.ownAttr(OBJECT_PROJECTION_ATTR_UNION) !== undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} member "${member.name}" declares its own @${OBJECT_PROJECTION_ATTR_UNION}; name its members here instead.`); + } const a = mine.map(describe); const b = theirs.map(describe); if (a.length !== b.length || a.some((x, i) => x !== b[i])) { diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index 6c641d4c78..294bb5e086 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -252,3 +252,34 @@ describe("an extender whose view widened over a TPH base", () => { { "identity.primary": { name: "id", extends: "Truck.primary" } }]))).filter((m) => m.includes("TruckRow"))).toEqual([]); }); }); + +// rc.21 part B fix round minors. +describe("fix round: casts Postgres has, value-mapped grain members, union value maps", () => { + test("M1: a boolean casts only to and from int; a count parameter takes only an int", async () => { + await refused("ERR_INVALID_ORIGIN", /a long cannot be cast to boolean; only an int can/, orderView([computed("a", "boolean", { cast: { field: "id" }, as: "boolean" })])); + await refused("ERR_INVALID_ORIGIN", /a boolean casts only to int, not long/, orderView([computed("a", "long", { cast: { value: true }, as: "long" })])); + await ok(orderView([computed("a", "boolean", { cast: { field: "n" }, as: "boolean" })])); + await refused("ERR_INVALID_ORIGIN", /'left' argument 2 must be an int, got long; cast it/, orderView([computed("a", "string", { fn: "left", args: [{ field: "ref" }, { field: "id" }] })])); + await ok(orderView([computed("a", "string", { fn: "left", args: [{ field: "ref" }, { cast: { field: "id" }, as: "int" }] })])); + }); + test("M2: a @grain member that is a value-mapped enum is refused", async () => { + const doc = [ + { "object.value": { name: "Tag", children: [ { "field.enum": { name: "kind", "@values": ["A", "B"], "@intValueMap": { A: 0, B: 1 } } } ] } }, + { "object.entity": { name: "Item", children: [ { "source.rdb": { "@table": "items" } }, { "field.long": { name: "id" } }, + { "field.object": { name: "tags", "@objectRef": "Tag", isArray: true, "@storage": "jsonb" } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "ItemTag", "@grain": "tags", children: [ { "source.rdb": { "@kind": "view", "@view": "v_item_tag" } }, + { "field.long": { name: "itemId", extends: "Item.id" } }, + { "field.enum": { name: "kind", "@values": ["A", "B"], "@intValueMap": { A: 0, B: 1 }, children: [ { "origin.passthrough": { "@from": "Tag.kind" } } ] } } ] } }, + ]; + await refused("ERR_INVALID_ORIGIN", /is an enum with a value map, but a @grain element holds the member's symbol/, ...doc); + }); + test("M4: union members whose enum value maps differ, and a member's own @union, are refused", async () => { + const branch = (name: string, map: Record, extra: Record = {}) => ({ "object.projection": { name, abstract: true, ...extra, children: [ + { "field.long": { name: "rowId", extends: "Order.id" } }, + { "field.enum": { name: "state", "@values": ["X", "Y"], "@intValueMap": map, children: [ { "origin.passthrough": { "@from": "Order.status", "@convert": true } } ] } } ] } }); + const union = { "object.projection": { name: "U", extends: "A", "@union": ["B"], children: [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } }; + await refused("ERR_BAD_ATTR_VALUE", /member "B" has a different shape/, branch("A", { X: 0, Y: 1 }), branch("B", { X: 1, Y: 0 }), union); + await refused("ERR_BAD_ATTR_VALUE", /member "B" declares its own @union/, branch("A", { X: 0, Y: 1 }), branch("B", { X: 0, Y: 1 }, { "@union": ["C"] }), + branch("C", { X: 0, Y: 1 }), union); + }); +}); From 4b8d5b097fb473387c4fd28b445aad8106b1cb00 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:55:10 -0500 Subject: [PATCH 204/267] fix(ports): Kotlin Exposed columns honour the text @dbColumnType spellings; exact sized-spelling match in Python; OMDB's bind message; CHANGELOG accuracy Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 25 ++++++++++++++----- .../generator/kotlin/KotlinTypeMapper.kt | 13 +++++++++- .../generator/kotlin/KotlinTypeMapperTest.kt | 15 +++++++++++ .../manager/db/codec/JdbcCodecs.java | 3 ++- .../meta/persistence/db/db_constants.py | 2 +- 5 files changed, 49 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d11fabb6d9..8e2d00145e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,9 @@ here.** `@unionAll`, `@grain`, `@grainOrdinal`, the text `@dbColumnType` spellings, and the `cast` node and function set of `attr.expression`), `@condition`, `atLeastOne @max`, `@sequenceStart`, `@sequenceName`, `@flattenedColumnPrefix`, the `pascal` column rule, and `@dbSetName`, a C#-only attr) and nothing -that loaded before stops loading. The registry gains two fields on a type or attr entry, carried +that loaded before stops loading, with one exception: a cross-field `@condition` that used `case`, +`now` or another view-only expression node, which no CHECK emitter could render (`meta migrate` +threw on it), is now refused at load. The registry gains two fields on a type or attr entry, carried into the registry manifest: `implementedIn` (kind 1: cross-port vocabulary only the named ports implement so far, e.g. the `view.*` controls, `["typescript"]`) and `ports` (kind 2: vocabulary only the named ports ever act on, e.g. `@dbSetName`, `["csharp"]`, and `@objectAdapter`, @@ -36,15 +38,20 @@ vocabulary; upgrade every port together. `right` and `length` beside `coalesce`, each argument typed; a `{ field }` ref to a scalar `origin.aggregate` (read on the grouped row, not filterable); and, on a projection, a path of to-one hops (`"customerId.regionId"`) in an expression or as a correlated - `@filter` operand, joined but not output. `origin.function` (`@function`, `@schema`, `@args`) - is a value computed by a database function the project owns, typed by its argument fields and - its carrying field; declared on an entity it is entity-derived (Postgres only). On + `@filter` operand, joined but not output. `origin.function` (`@function`, `@schema`, `@args`, `@params`, + `@returns`) is a value computed by a database function the project owns: each argument's field + type must be its declared parameter type (cast it through an `origin.computed` field otherwise), + `@returns` must be the carrying field's subtype, and the view casts the call to the field's column + type; declared on an entity it is entity-derived (Postgres only). On `object.projection`: `@grain` / `@grainOrdinal`, one row per element of a jsonb `field.object` array, its members read through `origin.passthrough @from: .`; and `@union` / `@unionAll`, a view that is the UNION (or UNION ALL) of projections of one shape, - checked at load. `@dbColumnType` takes the text spellings `text`, `varchar`, `character + checked at load (enum members and value maps included; a member's own `@union` is refused). A + `@grain` row whose value is not a JSON array (null, an object, a scalar) has no element. A cast + between a boolean and a number exists only for `int`, and the count of `left`, `right`, + `substring` and `splitPart` is an `int`, as in Postgres. `@dbColumnType` takes the text spellings `text`, `varchar`, `character varying`, `varchar(n)`, `character varying(n)` and `character(n)` on a `field.string` (`meta - migrate`, Drizzle, the C# EF context and the view cast honour them; a `@maxLength` over n is + migrate`, Drizzle, the C# EF context, the Kotlin Exposed table and the view cast honour them; the Java OMDB runtime binds them as text and creates no column from them; a `@maxLength` over n is refused), and the registry drops its `allowedValues`. A cross-field `@condition` takes only the CHECK subset of the grammar (fields, literals, comparisons, null tests, and/or/not, coalesce), refused at load otherwise. Rulings: the cast names a field subtype, the type @@ -362,6 +369,12 @@ vocabulary; upgrade every port together. ### Changed +- **Behaviour change: the registry manifest no longer lists `@dbColumnType`'s `allowedValues` + (rc.21).** The sized text spellings (`varchar(n)`, `character varying(n)`, `character(n)`) are no + closed set, so the value is parsed by each port's loader instead (a misspelling is still + `ERR_BAD_ATTR_VALUE` in every port). Tooling that read the enumeration from the manifest (an + editor schema) now sees a free string; the legal spellings are in the attr's description. + - **Behaviour change, TypeScript and C#: a projection that extends another keeps its super's identity anchor (rc.21).** An extender that declared no identity of its own took its base from its own fields' `extends`. So a projection over a TPH root that added a subtype's column moved diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt index 20f49074f8..b4daa4c7a9 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapper.kt @@ -405,6 +405,14 @@ object KotlinTypeMapper { else -> null } + /** rc.21 part B: the Exposed column for a text `@dbColumnType` spelling, or null for none. */ + private fun textSpellingColumn(value: String?, colExpr: String): String? { + if (value == null) return null + if (value == "text" || value == "varchar" || value == "character varying") return "text($colExpr)" + val m = Regex("^(varchar|character varying|character)\\(([1-9][0-9]{0,8})\\)$").matchEntire(value) ?: return null + return if (m.groupValues[1] == "character") "char($colExpr, ${m.groupValues[2]})" else "varchar($colExpr, ${m.groupValues[2]})" + } + /** * Map a MetaField to the Exposed `Table` column statement (e.g., `varchar("name", 100)`). * @@ -526,7 +534,10 @@ object KotlinTypeMapper { // (the `{ it }` identity codec would have left it `Column`). The table file // imports `kotlinx.serialization.json.Json` (see KotlinExposedTableGenerator). DB_COLUMN_TYPE_JSONB -> "jsonb($colExpr, { it.toString() }, { Json.parseToJsonElement(it) })" - else -> { + // rc.21 part B (fix round M6): the text spellings. `character(n)` is Exposed's + // `char(name, n)`, a sized varchar `varchar(name, n)`; an unbounded varchar or `text` + // is `text(name)` (Exposed has no unbounded varchar; Postgres treats them alike). + else -> textSpellingColumn(dbColumnType(field), colExpr) ?: run { // Dispatch to Exposed `text(name)` when the field is unbounded text: // (1) no `@maxLength` declared — the DEFAULT for `field.string` (Phase 1: // no-maxLength string → `text`, matching the canonical TS Postgres DDL), OR diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt index eebf43d317..97eda85692 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTypeMapperTest.kt @@ -336,6 +336,21 @@ class KotlinTypeMapperTest { assertEquals(STRING, KotlinTypeMapper.payloadTypeName(f)) } + @Test fun `string field with a text dbColumnType spelling emits that column`() { + // rc.21 part B (fix round M6): character(n), varchar(n), and an unbounded varchar or text. + for ((spelling, expected) in listOf( + "character(3)" to "char(\"code\", 3)", + "varchar(20)" to "varchar(\"code\", 20)", + "character varying(20)" to "varchar(\"code\", 20)", + "varchar" to "text(\"code\")", + "text" to "text(\"code\")", + )) { + val f = StringField("code") + f.addMetaAttr(StringAttribute.create("dbColumnType", spelling)) + assertEquals(expected, KotlinTypeMapper.exposedColumnSpec(f), spelling) + } + } + @Test fun `string field with dbColumnType=jsonb is case-insensitive`() { // `@dbColumnType` lookup case-folds (see `KotlinTypeMapper.dbColumnType`); both // `"JSONB"` and `"jsonb"` route to the JSONB branch. diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java index e11b589c0f..85269935b6 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java @@ -504,7 +504,8 @@ static final class EnumCodec implements JdbcFieldCodec { } String stored = storedMap.get(member); if (stored == null) { - throw new SQLException("field.enum '" + f.getName() + "' cannot write " + member + // One bind serves a write and a filter argument alike, so the message says "bind". + throw new SQLException("field.enum '" + f.getName() + "' cannot bind " + member + ": it has no stored string in @" + EnumField.ATTR_STRING_VALUE_MAP + " — the value is not one of the members the model declares."); } diff --git a/server/python/src/metaobjects/meta/persistence/db/db_constants.py b/server/python/src/metaobjects/meta/persistence/db/db_constants.py index bfbb99532a..072521b45f 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_constants.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_constants.py @@ -83,7 +83,7 @@ def parse_db_column_type(value: str) -> tuple[str, int | None] | None: return ("text", None) if value in (DB_COLUMN_TYPE_VARCHAR, DB_COLUMN_TYPE_CHARACTER_VARYING): return ("varchar", None) - m = _SIZED_DB_COLUMN_TYPE.match(value) + m = _SIZED_DB_COLUMN_TYPE.fullmatch(value) if m is None: return None return ("char" if m.group(1) == "character" else "varchar", int(m.group(2))) From 0b7c28e95651777c5d72de346774403820494d01 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:55:20 -0500 Subject: [PATCH 205/267] docs(changelog): what OMDB does with the text @dbColumnType spellings Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e2d00145e..23f9d341b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,7 +51,7 @@ vocabulary; upgrade every port together. between a boolean and a number exists only for `int`, and the count of `left`, `right`, `substring` and `splitPart` is an `int`, as in Postgres. `@dbColumnType` takes the text spellings `text`, `varchar`, `character varying`, `varchar(n)`, `character varying(n)` and `character(n)` on a `field.string` (`meta - migrate`, Drizzle, the C# EF context, the Kotlin Exposed table and the view cast honour them; the Java OMDB runtime binds them as text and creates no column from them; a `@maxLength` over n is + migrate`, Drizzle, the C# EF context, the Kotlin Exposed table and the view cast honour them; the Java OMDB runtime binds them as text, and a table OMDB itself creates keeps its VARCHAR or TEXT column; a `@maxLength` over n is refused), and the registry drops its `allowedValues`. A cross-field `@condition` takes only the CHECK subset of the grammar (fields, literals, comparisons, null tests, and/or/not, coalesce), refused at load otherwise. Rulings: the cast names a field subtype, the type From 3b3178d896f9f2c9927ed5adbe48c48625c92676 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:56:12 -0500 Subject: [PATCH 206/267] fix(views): the widened-extender warning is one per projection, over its own fields Only an extender's own fields chose its base before rc.21, so only they can have widened it; the warning names them in one message. Co-Authored-By: Claude Opus 5.5 --- .../ViewVocabularyRc21LoaderTests.cs | 2 +- .../MetaObjects/Loader/ValidationPasses.cs | 18 ++++++++++++------ .../metadata/src/loader/validation-passes.ts | 18 +++++++++++++----- .../test/rc21b-view-vocabulary.test.ts | 2 +- 4 files changed, 27 insertions(+), 13 deletions(-) diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index 250b1eed01..f02a1ce26a 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -217,7 +217,7 @@ public void An_extender_whose_view_widened_over_a_tph_base_warns(string filter, if (warns) { var w = Assert.Single(hit); - Assert.Contains("only the subtype Truck carries, over the TPH base Vehicle with no @filter on its discriminator \"kind\"", w); + Assert.Contains("\"payload\" (Truck.payloadClass) read columns only a subtype carries, over the TPH base Vehicle with no @filter on its discriminator \"kind\"", w); } else Assert.Empty(hit); } diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index ac90f2aa23..d5b555f89d 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1357,7 +1357,10 @@ public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) if (discriminator is null) continue; if (ProjectionFilters.Effective(obj) is IReadOnlyDictionary filter && FilterKeys(filter).Contains(discriminator)) continue; var pkg = NamingRefs.EffectivePackage(obj); - foreach (var f in obj.Children().Where(c => c.Type == TYPE_FIELD)) + // Only the extender's OWN fields chose its base before rc.21, so only they can have widened it. + var subtypeFields = new List(); + MetaData? subtype = null; + foreach (var f in obj.OwnChildren().Where(c => c.Type == TYPE_FIELD)) { var owner = RefNamedOwner(f, root, pkg); if (owner is null || ReferenceEquals(owner, baseEntity)) continue; @@ -1366,12 +1369,15 @@ public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) if (ReferenceEquals(cur, baseEntity)) { descends = true; break; } if (!descends) continue; var col = f.SuperRef is { } r ? r.Split('.').Last() : f.Name; - warnings.Add( - $"object.projection {obj.Name}: \"{f.Name}\" reads {owner.Name}.{col}, a column only the " + - $"subtype {owner.Name} carries, over the TPH base {baseEntity.Name} with no @filter on its discriminator \"{discriminator}\", so the " + - $"view returns every {baseEntity.Name} row (rc.21: an extender keeps its super's identity anchor; before, its base was {owner.Name}). " + - $"To keep a subtype-scoped view, add @filter {{ {discriminator}: }} or declare identity.primary {{ extends: {owner.Name}.primary }}."); + subtypeFields.Add($"\"{f.Name}\" ({owner.Name}.{col})"); + subtype ??= owner; } + if (subtype is not null) + warnings.Add( + $"object.projection {obj.Name}: {string.Join(", ", subtypeFields)} read columns only a subtype carries, over the TPH base " + + $"{baseEntity.Name} with no @filter on its discriminator \"{discriminator}\", so the view returns every {baseEntity.Name} row " + + "(rc.21: an extender keeps its super's identity anchor; before, its base was the subtype). To keep a subtype-scoped " + + $"view, add @filter {{ {discriminator}: }} or declare identity.primary {{ extends: {subtype.Name}.primary }}."); } return warnings.AsReadOnly(); } diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index e23754ba63..77884fd1d5 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1056,14 +1056,22 @@ export function validateExtenderSubtypeScope(root: MetaData): string[] { if (discriminator === undefined) continue; if (filterKeys(effectiveProjectionFilter(obj)).includes(discriminator)) continue; const referrerPkg = obj.package ?? obj.fileDefaultPackage ?? ""; - for (const f of obj.children().filter((c) => c.type === TYPE_FIELD)) { + // ADR-0039: own — only the extender's OWN fields chose its base before rc.21 (an inherited field + // was anchored by the super's identity then too), so only they can have widened it. + const subtypeFields: string[] = []; + let subtype: MetaData | undefined; + for (const f of obj.ownChildren().filter((c) => c.type === TYPE_FIELD)) { const owner = _refNamedOwner(f, root, referrerPkg); if (owner === undefined || owner === base || !_isDescendantOf(owner, base)) continue; + subtypeFields.push(`"${f.name}" (${owner.name}.${f.superRef?.split(".").pop() ?? f.name})`); + subtype ??= owner; + } + if (subtype !== undefined) { warnings.push( - `object.projection ${obj.name}: "${f.name}" reads ${owner.name}.${f.superRef?.split(".").pop() ?? f.name}, a column only the ` + - `subtype ${owner.name} carries, over the TPH base ${base.name} with no @filter on its discriminator "${discriminator}", so the ` + - `view returns every ${base.name} row (rc.21: an extender keeps its super's identity anchor; before, its base was ${owner.name}). ` + - `To keep a subtype-scoped view, add @filter { ${discriminator}: } or declare identity.primary { extends: ${owner.name}.primary }.`, + `object.projection ${obj.name}: ${subtypeFields.join(", ")} read columns only a subtype carries, over the TPH base ` + + `${base.name} with no @filter on its discriminator "${discriminator}", so the view returns every ${base.name} row ` + + `(rc.21: an extender keeps its super's identity anchor; before, its base was the subtype). To keep a subtype-scoped ` + + `view, add @filter { ${discriminator}: } or declare identity.primary { extends: ${subtype.name}.primary }.`, ); } } diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index 294bb5e086..8873911fde 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -243,7 +243,7 @@ describe("an extender whose view widened over a TPH base", () => { test("warns, naming the remedy", async () => { const w = (await warningsOf(row())).filter((m) => m.includes("TruckRow")); expect(w.length).toBe(1); - expect(w[0]).toMatch(/only the subtype Truck carries, over the TPH base Vehicle with no @filter on its discriminator "kind"/); + expect(w[0]).toMatch(/"payload" \(Truck.payloadClass\) read columns only a subtype carries, over the TPH base Vehicle with no @filter on its discriminator "kind"/); expect(w[0]).toMatch(/@filter \{ kind: \} or declare identity.primary \{ extends: Truck.primary \}/); }); test("a discriminator filter, or its own identity, scopes it: no warning", async () => { From d8b5741a67720a5735c8575edfb1c35fff003ab7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:59:05 -0500 Subject: [PATCH 207/267] test(origin): the completeness table names origin.function's @params and @returns Co-Authored-By: Claude Opus 5.5 --- .../metadata/test/origin-definition-completeness.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts index ba011a3212..bc3038c768 100644 --- a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts @@ -74,6 +74,8 @@ const EXPECTED: Record> = { function: { valueType: "string", required: true }, schema: { valueType: "string", required: false }, args: { valueType: "string", required: false }, + params: { valueType: "string", required: false }, + returns: { valueType: "string", required: true }, }, }; From d9c558cdda66cb9b6b33a2fad7f9ce73f132feb6 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:04:10 -0500 Subject: [PATCH 208/267] test(java): the text @dbColumnType spellings load on a field.string The rc.21 text spellings are legal again; the Phase 1 test that refused a bare text value now pins that each spelling loads. Co-Authored-By: Claude Opus 5.5 --- .../loader/DbColumnTypeValidationTest.java | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java index 2d86686825..ad88ca833b 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/DbColumnTypeValidationTest.java @@ -31,7 +31,8 @@ * Tests for {@link ValidationPhase#validateDbColumnType} (R6 Plan 2b). The * {@code @dbColumnType} physical attribute is validated own-only against: *
      - *
    1. a closed value set ({@code uuid|jsonb} — {@code timestamp_with_tz} was retired + *
    2. a closed value set ({@code uuid|jsonb}, and since rc.21 the text spellings on a + * {@code field.string} — {@code timestamp_with_tz} was retired * in ADR-0036 Wave 2); and
    3. *
    4. the legal (logical-subtype × value) pairing.
    5. *
    @@ -174,17 +175,20 @@ public void textArrayValueIsRejected() { } @Test - public void textValueIsRejected() { - // The vestigial dbColumnType:text value is REMOVED (Phase 1): a no-maxLength - // field.string already defaults to a text column — `text` is not an opt-in. - String canonical = "{ \"metadata.root\": { \"package\": \"acme\", \"children\": [" + - " { \"object.entity\": { \"name\": \"Asset\", \"children\": [" + - " { \"field.long\": { \"name\": \"id\" } }," + - " { \"field.string\": { \"name\": \"body\", \"@dbColumnType\": \"text\" } }," + - " { \"identity.primary\": { \"@fields\": \"id\" } }" + - " ] } }" + - "] } }"; - assertBadAttrValue(canonical, "text-value-removed.json"); + public void textSpellingsOnStringAreLegal() { + // rc.21: the text spellings (text, varchar, varchar(n), character varying(n), + // character(n)) are legal on a field.string again, so a view column can carry + // the database's own type name. + for (String spelling : List.of("text", "varchar", "varchar(40)", "character varying(40)", "character(2)")) { + String canonical = "{ \"metadata.root\": { \"package\": \"acme\", \"children\": [" + + " { \"object.entity\": { \"name\": \"Asset\", \"children\": [" + + " { \"field.long\": { \"name\": \"id\" } }," + + " { \"field.string\": { \"name\": \"body\", \"@dbColumnType\": \"" + spelling + "\" } }," + + " { \"identity.primary\": { \"@fields\": \"id\" } }" + + " ] } }" + + "] } }"; + loadThrough(canonical, "text-spelling-" + spelling + ".json"); + } } @Test From 0d28f5568eeb0fe9c984fa6ddad923616aa11ebe Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:25:39 -0500 Subject: [PATCH 209/267] feat(cli): meta gen prints the widened-extender warning The loader records it on its warning channel, which loadMemory does not return, so neither gen nor verify showed it. gen now runs the pass on the model it loaded and prints each finding, like an unknown attribute. Co-Authored-By: Claude Opus 5.5 --- .../packages/cli/src/commands/gen.ts | 5 +- .../test/gen-extender-scope-warning.test.ts | 92 +++++++++++++++++++ .../typescript/packages/metadata/src/index.ts | 4 + 3 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index cea8ee89e6..934fd0fd9b 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -18,7 +18,7 @@ import { import { loadMemory, resolveCollection } from "@metaobjectsdev/sdk"; import { declaredGeneratorNames, runGen, undeclaredGeneratorsMessage } from "@metaobjectsdev/codegen-ts"; import type { WriteStatus } from "@metaobjectsdev/codegen-ts"; -import { packageOfResolutionKey } from "@metaobjectsdev/metadata"; +import { packageOfResolutionKey, validateExtenderSubtypeScope } from "@metaobjectsdev/metadata"; import type { MetaRoot } from "@metaobjectsdev/metadata"; import type { Collection } from "@metaobjectsdev/sdk"; import { describeLoadError, reportLoadError } from "../lib/load-error.js"; @@ -215,6 +215,9 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat ? [...unknownAttrFindings, UNKNOWN_ATTR_GEN_ADVICE] : []; for (const w of unknownAttrs) { log.warn(`warning: ${w}`); warnings.push(w); } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. The loader + // records it on its warning channel, which `loadMemory` does not return, so it is said here. + for (const w of validateExtenderSubtypeScope(metadata)) { log.warn(`warning: ${w}`); warnings.push(w); } // The schema settings `meta migrate` builds with, for the Prisma schema, the schema page and // the migrate advice. A conventions preset that does not resolve is a config error here as in diff --git a/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts new file mode 100644 index 0000000000..ef45eaa62b --- /dev/null +++ b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts @@ -0,0 +1,92 @@ +// rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields +// read a TPH subtype's columns returns every base row. The loader records that on its warning +// channel, which `loadMemory` does not return; `meta gen` prints it so the change is visible. +import { describe, test, expect, beforeEach, afterEach } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { run } from "../src/index.js"; + +const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures", "__tmp__"); + +function model(scoped: boolean): string { + return JSON.stringify({ + "metadata.root": { + package: "app", + children: [ + { "object.entity": { name: "Vehicle", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { name: "id" } }, + { "field.string": { name: "kind", "@maxLength": 10 } }, { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "Truck", extends: "Vehicle", "@discriminatorValue": "TRUCK", children: [ + { "field.string": { name: "payloadClass" } } ] } }, + { "object.projection": { name: "VehicleBase", abstract: true, children: [ + { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, + { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, + { "object.projection": { name: "TruckRow", extends: "VehicleBase", ...(scoped ? { "@filter": { kind: "TRUCK" } } : {}), children: [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { name: "payload", extends: "Truck.payloadClass" } } ] } }, + ], + }, + }); +} + +function setupRepo(scoped: boolean): string { + mkdirSync(WORKSPACE_TMP, { recursive: true }); + const root = mkdtempSync(join(WORKSPACE_TMP, "gen-extender-scope-")); + mkdirSync(join(root, "metaobjects"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.app.json"), model(scoped), "utf8"); + mkdirSync(join(root, ".metaobjects"), { recursive: true }); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }), "utf8"); + writeFileSync(join(root, "metaobjects.config.ts"), ` +import { defineConfig } from "@metaobjectsdev/codegen-ts"; +export default defineConfig({ + outDir: ${JSON.stringify(join(root, "generated"))}, + dialect: "postgres", + dbImport: "~/db", + extStyle: "none", + generators: [], +}); +`); + return root; +} + +let out: string[]; +let err: string[]; +let origLog: typeof console.log; +let origErr: typeof console.error; +beforeEach(() => { + out = []; + err = []; + origLog = console.log; + origErr = console.error; + console.log = (...a: unknown[]) => { out.push(a.map(String).join(" ")); }; + console.error = (...a: unknown[]) => { err.push(a.map(String).join(" ")); }; +}); +afterEach(() => { + console.log = origLog; + console.error = origErr; +}); + +describe("meta gen — the widened-extender warning is printed", () => { + test("names the projection, the field and the remedy; exit code unchanged", async () => { + const root = setupRepo(false); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + const stderr = err.join("\n"); + expect(stderr).toContain("object.projection TruckRow"); + expect(stderr).toContain(`"payload" (Truck.payloadClass)`); + expect(stderr).toContain("@filter { kind: }"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("a discriminator filter scopes it: no warning", async () => { + const root = setupRepo(true); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + expect(err.join("\n")).not.toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 970c5ea3f2..2a1b119170 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -372,6 +372,10 @@ export type { Scope, CompiledScope } from "./scope.js"; export { validateAttrSchema } from "./attr-schema-validate.js"; export type { AttrSchemaValidationResult } from "./attr-schema-validate.js"; +// rc.21 part B (I2): the widened-extender warning, which `meta gen` prints (the load's own +// warning channel is not printed by the CLI). +export { validateExtenderSubtypeScope } from "./loader/validation-passes.js"; + // Guide URLs pinned to the running release's tag (prerelease → main). export { DOCS_REPO_URL, DOCS_DEFAULT_REF, docsRefForVersion, docsBlobUrl, pinDocsRefs, From 819eed4e9d73e25dd8ed4bfb00203fe1e0af0904 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:25:43 -0500 Subject: [PATCH 210/267] fix(tests): the engine surface stays sorted; a shared CHECK name is not refused on SQLite The pg-identifier entry went in out of order, and the verify test still expected the shared-name refusal SQLite no longer gets (SQLite and D1 accept and enforce both CHECKs). Co-Authored-By: Claude Opus 5.5 --- .../packages/cli/test/verify-schema-refusals.test.ts | 9 ++++++--- .../typescript/packages/codegen-ts/src/engine-surface.ts | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts index 58c8375dda..07dd52fa8c 100644 --- a/server/typescript/packages/cli/test/verify-schema-refusals.test.ts +++ b/server/typescript/packages/cli/test/verify-schema-refusals.test.ts @@ -107,7 +107,10 @@ describe("meta verify — schema refusals", () => { expect(scoped.out).toContain('field.enum "Ticket.status" has the member "IN_PROGRESS"'); }); - test("--db: a declared CHECK name two validators share is refused by name, not as an introspection failure", async () => { + // rc.21 (N1): SQLite and D1 accept and enforce two CHECKs under one name, so the shared name is + // not refused there (Postgres refuses it; migrate-ts check-name-collision.test.ts pins that). The + // run reports the ordinary drift, never an introspection failure. + test("--db: a CHECK name two validators share is not refused on SQLite, and is no introspection failure", async () => { const root = await mkdtemp(join(tmpdir(), "verify-schema-refusals-")); dirs.push(root); await mkdir(join(root, "metaobjects"), { recursive: true }); @@ -127,8 +130,8 @@ describe("meta verify — schema refusals", () => { const { code, out } = await capture(() => verifyCommand(["--db", `file:${join(root, "t.db")}`], root)); expect(code).toBe(1); - expect(out).toContain("ERR_CHECK_NAME"); - expect(out).toContain('CHECK "CK_Slot" on table "slots"'); + expect(out).toContain("+ table slots"); + expect(out).not.toContain("ERR_CHECK_NAME"); expect(out).not.toContain("failed to introspect"); }); }); diff --git a/server/typescript/packages/codegen-ts/src/engine-surface.ts b/server/typescript/packages/codegen-ts/src/engine-surface.ts index 71f959c650..6e7659d354 100644 --- a/server/typescript/packages/codegen-ts/src/engine-surface.ts +++ b/server/typescript/packages/codegen-ts/src/engine-surface.ts @@ -46,6 +46,7 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/naming.ts", "codegen-ts/src/naming/name-claims.ts", "codegen-ts/src/owned-runtime.ts", + "codegen-ts/src/pg-identifier.ts", "codegen-ts/src/pk-resolver.ts", "codegen-ts/src/projection/build-projection-views.ts", "codegen-ts/src/projection/extract-view-spec.ts", @@ -65,6 +66,5 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/templates/find-inbound.ts", "codegen-ts/src/templates/find-templates.ts", "codegen-ts/src/tph.ts", - "codegen-ts/src/pg-identifier.ts", "codegen-ts/src/view-context.ts", ]; From 002b8914e8d0df283e88444d8b2b7c7c3224eae3 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:30:35 -0500 Subject: [PATCH 211/267] feat(csharp): dotnet meta gen prints the widened-extender warning The loader records it on its warning channel, which gen does not print; gen now runs the pass on the model it loaded and prints each finding. Co-Authored-By: Claude Opus 5.5 --- .../GenExtenderScopeWarningTests.cs | 53 +++++++++++++++++++ .../csharp/MetaObjects.Codegen/CodegenCli.cs | 7 +++ 2 files changed, 60 insertions(+) create mode 100644 server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs diff --git a/server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs new file mode 100644 index 0000000000..ef54d4d3aa --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/GenExtenderScopeWarningTests.cs @@ -0,0 +1,53 @@ +using Xunit; + +namespace MetaObjects.Cli.Tests; + +/// +/// rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields +/// read a TPH subtype's columns returns every base row. The loader records that on its warning +/// channel, which `dotnet meta gen` does not print; gen now says it, and keeps its exit code. +/// +[Collection(OwnedRunnerCollection.Name)] +public sealed class GenExtenderScopeWarningTests : IDisposable +{ + private readonly string _tmp = Path.Combine(Path.GetTempPath(), "meta-gen-extender-scope-" + Guid.NewGuid().ToString("N")); + private string MetaDir => Path.Combine(_tmp, "metaobjects"); + private string OutDir => Path.Combine(_tmp, "out"); + + private static string Model(string filter) => $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "kind", "@maxLength": 10 } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Truck", "extends": "Vehicle", "@discriminatorValue": "TRUCK", "children": [ { "field.string": { "name": "payloadClass" } } ] } }, + { "object.projection": { "name": "VehicleBase", "abstract": true, "children": [ + { "field.long": { "name": "vehicleId", "extends": "Vehicle.id" } }, { "identity.primary": { "name": "id", "extends": "Vehicle.primary" } } ] } }, + { "object.projection": { "name": "TruckRow", "extends": "VehicleBase", {{filter}} "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, + { "field.string": { "name": "payload", "extends": "Truck.payloadClass" } } ] } } ] } } + """; + + public GenExtenderScopeWarningTests() => Directory.CreateDirectory(MetaDir); + + public void Dispose() { try { Directory.Delete(_tmp, recursive: true); } catch { } } + + [Fact] + public void Gen_prints_the_widened_extender_warning_and_keeps_its_exit_code() + { + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), Model("")); + var run = OwnedRunner.Run(_tmp, ["entity"], "gen", MetaDir, "--out", OutDir, "--namespace", "Acme"); + Assert.Equal(0, run.ExitCode); + Assert.Contains("object.projection TruckRow", run.Stderr); + Assert.Contains("\"payload\" (Truck.payloadClass)", run.Stderr); + Assert.Contains("@filter { kind: }", run.Stderr); + } + + [Fact] + public void A_discriminator_filter_scopes_it_and_gen_says_nothing() + { + File.WriteAllText(Path.Combine(MetaDir, "meta.acme.json"), Model("\"@filter\": { \"kind\": \"TRUCK\" },")); + var run = OwnedRunner.Run(_tmp, ["entity"], "gen", MetaDir, "--out", OutDir, "--namespace", "Acme"); + Assert.Equal(0, run.ExitCode); + Assert.DoesNotContain("object.projection TruckRow", run.Stderr); + } +} diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 0c8c2bd334..038a550900 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -750,6 +750,13 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) WarnUnknownAttrs(meta); genLoad = meta.Load(); } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. The + // loader records it on its warning channel, which gen does not print, so it is said here. + if (genLoad.Errors.Count == 0) + { + foreach (var w in ValidationPasses.ValidateExtenderSubtypeScope(genLoad.Root)) + Console.Error.WriteLine($" warning: {w}"); + } var outcome = RunGen(genLoad, a.OutDir, a.Namespace ?? meta.Namespace, a.EmitAbstractShapes, suite, projectRoot, a.Baseline, includeNames: declared.Any(g => g.Name == "names"), // Only a run of the whole declared list can tell a stale file from one the From b76012e06a795ed450b941e47ee49b45e6bbc55e Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:30:48 -0500 Subject: [PATCH 212/267] docs(changelog): gen prints the widened-extender warning Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23f9d341b6..4715969260 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -383,8 +383,9 @@ vocabulary; upgrade every port together. the shared table, the subtype column NULL on the others. A field bound to a TPH relative of the base reads the shared table's column (it read a column named after the projection field). The load now warns in exactly the case whose output widened: an extender with no identity of its - own, anchored by its super on a TPH base, that binds a field to a subtype-only column and has no - `@filter` on the discriminator. **Upgrade note:** to get the subtype-scoped view back, either add + own, anchored by its super on a TPH base, whose own fields bind a subtype-only column, and no + `@filter` on the discriminator. `meta gen` and `dotnet meta gen` print that warning (the + loader's warning channel is not otherwise printed). **Upgrade note:** to get the subtype-scoped view back, either add `@filter: { : }` to the extender, or anchor it on the subtype: declare `identity.primary { name: id, extends: .primary }` with a field extending `.id`. From 33478e70fd1af76fe75c90eedc1341a47f82f485 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:41:12 -0500 Subject: [PATCH 213/267] fix(views): an origin.function call is cast to the field's full column type; verify --db checks the signature The cast used the subtype's default type: a local timestamp became TIMESTAMPTZ (read in the session zone), a sized string TEXT, a scaled decimal bare NUMERIC. It now takes the type meta migrate gives the field's table column. Because that cast would hide a wrong @returns, meta verify --db reads each declared function from pg_proc and fails on a missing function or a parameter or return type that differs. Live Postgres tests pin both. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 +- docs/features/relationships.md | 7 +- fixtures/metamodel-docs/expected/INDEX.md | 2 +- .../metamodel-docs/expected/types/origin.md | 4 +- .../expected-registry.json | 4 +- .../MetaObjects/SpecMetamodel/origin.json | 4 +- .../metaobjects/spec_metamodel/origin.json | 4 +- .../packages/cli/src/commands/verify.ts | 15 +- .../test/verify-declared-functions.test.ts | 82 ++++++++++ .../src/projection/extract-view-spec.ts | 4 +- .../src/projection/view-ddl-emit.ts | 2 + .../codegen-ts/src/projection/view-spec.ts | 3 + .../test/view-vocabulary-rc21-pg.test.ts | 80 ++++++++- .../origin/origin-definition.embedded.ts | 4 +- .../packages/migrate-ts/src/index.ts | 2 + .../src/introspect/declared-functions.ts | 154 ++++++++++++++++++ site-reference/index.html | 2 +- site-reference/types/origin.html | 4 +- spec/metamodel/origin.json | 4 +- 19 files changed, 365 insertions(+), 24 deletions(-) create mode 100644 server/typescript/packages/cli/test/verify-declared-functions.test.ts create mode 100644 server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4715969260..e94c1ee7e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,8 +41,12 @@ vocabulary; upgrade every port together. `@filter` operand, joined but not output. `origin.function` (`@function`, `@schema`, `@args`, `@params`, `@returns`) is a value computed by a database function the project owns: each argument's field type must be its declared parameter type (cast it through an `origin.computed` field otherwise), - `@returns` must be the carrying field's subtype, and the view casts the call to the field's column - type; declared on an entity it is entity-derived (Postgres only). On + `@returns` must be the carrying field's subtype, and the view casts the call to the field's full + column type, the one its table column would have (length or `@dbColumnType` spelling, precision and + scale, a local or zoned timestamp). The signature is a declaration: `meta verify --db` reads each + function from `pg_proc` and fails on a missing function or a parameter or return type that + differs, so the cast never hides a wrong `@returns`. Declared on an entity it is entity-derived + (Postgres only). On `object.projection`: `@grain` / `@grainOrdinal`, one row per element of a jsonb `field.object` array, its members read through `origin.passthrough @from: .`; and `@union` / `@unionAll`, a view that is the UNION (or UNION ALL) of projections of one shape, diff --git a/docs/features/relationships.md b/docs/features/relationships.md index fb86e17344..04cecd4a21 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -282,8 +282,11 @@ expressions read. (plain identifiers), `@args` the fields passed to it in order, `@params` their declared types and `@returns` the result's (field subtypes). Each argument must have its parameter's type — pass an `origin.computed` field that casts it (`{ cast: { field: x }, as: int }`) otherwise — and -`@returns` must be the carrying field's subtype; the view casts the call to the field's column -type. Declared on an entity, it is +`@returns` must be the carrying field's subtype; the view casts the call to the field's full +column type, the one its table column would have (length or `@dbColumnType` spelling, precision and +scale, a local or zoned timestamp). The signature is a declaration that `meta verify --db` checks: +it reads the function from `pg_proc` and fails on a missing function, or a parameter or return +type that differs, so the cast never hides a wrong `@returns`. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. MetaObjects never creates the function (it is owned SQL, created before the view). Postgres only. diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 44c5a4ed19..915b7fe4e8 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -65,7 +65,7 @@ children and the cardinality of that subtype. Documentation attributes | `origin.base` | Abstract base origin — the shared root subtype for field-level provenance. A field carrying any origin.* is derived ⇒ read-only wherever it lives. The base carries no attrs of its own; concrete subtypes add their provenance attrs. Not authored directly: a `origin.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/origin.md#originbase](types/origin.md#originbase) | | `origin.computed` | A row-level value computed from the base entity's own fields via a structured expression tree (@expr). No related rows, no @via. Read-only; the expression's inferred type must equal the field's declared subType. | [types/origin.md#origincomputed](types/origin.md#origincomputed) | | `origin.first` | The single related row selected by @orderBy along @via, projecting its @of column (argmax then project). Latest = @orderBy desc. Read-only; empty related set (after @filter) → null, so the field must not be @required. | [types/origin.md#originfirst](types/origin.md#originfirst) | -| `origin.function` | A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. | [types/origin.md#originfunction](types/origin.md#originfunction) | +| `origin.function` | A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. | [types/origin.md#originfunction](types/origin.md#originfunction) | | `origin.passthrough` | A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). | [types/origin.md#originpassthrough](types/origin.md#originpassthrough) | | `relationship.aggregation` | A shared/independent containment — the parent groups the target but does not own its lifecycle (default @onDelete set-null). | [types/relationship.md#relationshipaggregation](types/relationship.md#relationshipaggregation) | | `relationship.association` | A plain reference to another entity — no ownership; the target has an independent lifecycle (default @onDelete restrict). | [types/relationship.md#relationshipassociation](types/relationship.md#relationshipassociation) | diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index f1e536e0af..04485083ae 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -94,7 +94,7 @@ _No structural children._ ### origin.function -A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. +A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. **Owning provider:** metaobjects-core-types @@ -107,7 +107,7 @@ A value computed by a database function the project owns (rc.21): @function name | `@args` | string[] | no | | | metaobjects-core-types | The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments. | | `@function` | string | yes | | | metaobjects-core-types | The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase. | | `@params` | string[] | no | | | metaobjects-core-types | The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN). | -| `@returns` | string | yes | | | metaobjects-core-types | The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns. | +| `@returns` | string | yes | | | metaobjects-core-types | The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc). | | `@schema` | string | no | | | metaobjects-core-types | The schema the function lives in, a plain identifier. Absent: public. | **Allowed children** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index a64b0adfa2..df87c06bb5 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -4078,7 +4078,7 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "attrs": [ { @@ -4107,7 +4107,7 @@ "valueType": "string", "isArray": false, "required": true, - "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." + "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." }, { "name": "schema", diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index b175e9b4a8..e8cfe7e735 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -45,14 +45,14 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, - { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } ] }, { diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index b175e9b4a8..e8cfe7e735 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -45,14 +45,14 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, - { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } ] }, { diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index ca9434465e..c911264787 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -76,6 +76,7 @@ import { type ReplayEngine, verifyReplay, introspect, + checkDeclaredFunctions, diff, withoutViewRecreates, readSnapshot, @@ -1463,7 +1464,19 @@ export async function verifyCommand( return 1; } - return reportSchemaDrift(driftResult, [...ledgerDrift, ...snapshotDrift], kysely.displayUrl); + // rc.21 part B (N2): a declared origin.function's signature is the database's, or a finding. + let functionDrift: string[] = []; + if (kysely.dialect === "postgres") { + try { + functionDrift = await checkDeclaredFunctions(kysely.db, root); + } catch (err) { + schemaRunError = `failed to read the declared functions from ${kysely.displayUrl}: ${describeError(err)}`; + log.error(`verify: ${schemaRunError}`); + return 1; + } + } + + return reportSchemaDrift(driftResult, [...ledgerDrift, ...snapshotDrift, ...functionDrift], kysely.displayUrl); } finally { await shadow?.close(); try { diff --git a/server/typescript/packages/cli/test/verify-declared-functions.test.ts b/server/typescript/packages/cli/test/verify-declared-functions.test.ts new file mode 100644 index 0000000000..1a8b0bd40c --- /dev/null +++ b/server/typescript/packages/cli/test/verify-declared-functions.test.ts @@ -0,0 +1,82 @@ +/** + * rc.21 part B fix round 2 (N2): `meta verify --db` reads every declared `origin.function` from + * pg_proc, so a declaration the database does not have (a `numeric` result declared `int`, which the + * view's cast would round) is a finding and fails the run. Needs a Postgres: set + * METAOBJECTS_TEST_PG_URL; without one the test is skipped (the check itself is covered live in + * integration-tests view-vocabulary-rc21-pg.test.ts). + */ +import { describe, test, expect, afterAll } from "bun:test"; +import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { Pool } from "pg"; +import { verifyCommand } from "../src/commands/verify.js"; + +const PG_URL = process.env.METAOBJECTS_TEST_PG_URL; +const dirs: string[] = []; +afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); + +function model(returns: string, subType: string): string { + return JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Meter", children: [ + { "source.rdb": { "@table": "meters" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.projection": { name: "MeterRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_meter_row" } }, + { "field.long": { name: "id", extends: "Meter.id" } }, + { [`field.${subType}`]: { name: "reading", children: [ + { "origin.function": { "@function": "meter_reading", "@schema": "verify_fn", "@args": ["id"], "@params": ["long"], "@returns": returns } } ] } }, + { "identity.primary": { name: "id", extends: "Meter.id" } }, + ] } }, + ] } }); +} + +async function project(returns: string, subType: string): Promise { + const root = await mkdtemp(join(tmpdir(), "verify-declared-functions-")); + dirs.push(root); + await mkdir(join(root, "metaobjects"), { recursive: true }); + await writeFile(join(root, "metaobjects", "meta.acme.json"), model(returns, subType), "utf8"); + await mkdir(join(root, ".metaobjects"), { recursive: true }); + await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1 }), "utf8"); + return root; +} + +async function capture(fn: () => Promise): Promise<{ code: number; out: string }> { + const lines: string[] = []; + const log = console.log; + const err = console.error; + console.log = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + console.error = (...a: unknown[]) => { lines.push(a.map(String).join(" ")); }; + try { + const code = await fn(); + return { code, out: lines.join("\n") }; + } finally { + console.log = log; + console.error = err; + } +} + +describe("meta verify --db — declared origin.function signatures", () => { + test.skipIf(PG_URL === undefined)("a declared return type the database does not have fails the run, named; a matching one is no finding", async () => { + const k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: PG_URL }) }) }); + try { + await sql.raw("DROP SCHEMA IF EXISTS verify_fn CASCADE").execute(k); + await sql.raw("CREATE SCHEMA verify_fn").execute(k); + await sql.raw("CREATE FUNCTION verify_fn.meter_reading(bigint) RETURNS numeric LANGUAGE sql IMMUTABLE AS $$ SELECT $1 * 1.5 $$").execute(k); + + const bad = await capture(async () => verifyCommand(["--db", PG_URL!], await project("int", "int"))); + expect(bad.code).toBe(1); + expect(bad.out).toContain("origin.function verify_fn.meter_reading on MeterRow.reading: declared (long) → int, which needs " + + "verify_fn.meter_reading(bigint) → integer; the database has verify_fn.meter_reading(bigint) → numeric."); + + const good = await capture(async () => verifyCommand(["--db", PG_URL!], await project("decimal", "decimal"))); + expect(good.out).not.toContain("origin.function verify_fn.meter_reading"); + } finally { + await sql.raw("DROP SCHEMA IF EXISTS verify_fn CASCADE").execute(k); + await k.destroy(); + } + }, 60_000); +}); diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index 03ce1b517a..a59e352a6e 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -1080,7 +1080,9 @@ function functionCall( args.push(a.expr); } const call: ViewExprNode = { kind: "call", name, ...(typeof schema === "string" ? { schema } : {}), args }; - return { kind: "cast", arg: call, to: { subType: field.subType } }; + // N1: the call is cast to the field's full column type — length, @dbColumnType spelling, + // precision and scale, local or zoned timestamp — the type `meta migrate` gives its column. + return { kind: "cast", arg: call, to: { subType: field.subType, column: fieldSqlType(field) } }; } /** rc.21 part B (U14): the value object a `@grain` projection's rows are elements of, if it has one. */ diff --git a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts index b62965ab63..d82d662d7f 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts @@ -234,6 +234,8 @@ function renderFn(name: string, args: readonly string[], nodes: readonly ViewExp /** rc.21 part B (U12): the column type a cast names, in the dialect's spelling. */ function castTypeSql(to: CastTarget, dialect: EmitOptions["dialect"]): string { const pg = dialect === "postgres"; + // N1: a field's own column type is spelled by the table DDL's own function. + if (pg && to.column !== undefined) return pgType(to.column); switch (to.subType) { case "string": { if (!pg) return "TEXT"; diff --git a/server/typescript/packages/codegen-ts/src/projection/view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/view-spec.ts index 098a9b4ef8..c3927ced93 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-spec.ts @@ -106,6 +106,9 @@ export type ViewExprNode = export interface CastTarget { readonly subType: string; readonly spelling?: { readonly kind: "text" | "varchar" | "char"; readonly length?: number }; + /** rc.21 part B (N1): the full column type, when the cast is to a field's own column (an + * `origin.function` call): the SqlType `meta migrate` gives that field's table column. */ + readonly column?: SqlType; } /** An aggregate column a computed expression may read (U13): a scalar reduce or an any/all. */ diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts index bde4236cf5..75c3e47047 100644 --- a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -4,7 +4,7 @@ // production pipeline (build → diff → emit → apply), queried, and a second migrate is a no-op. import { describe, test, expect, beforeAll, afterAll } from "bun:test"; -import { buildExpectedSchema, diff, emit, introspectPostgres, postgresViewReplaceProbe, splitSqlStatements } from "@metaobjectsdev/migrate-ts"; +import { buildExpectedSchema, checkDeclaredFunctions, diff, emit, introspectPostgres, postgresViewReplaceProbe, splitSqlStatements } from "@metaobjectsdev/migrate-ts"; import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { Kysely, PostgresDialect, sql } from "kysely"; @@ -34,7 +34,14 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, { "field.string": { name: "loyaltyTier", children: [ - { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } } ] } }, + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"], "@params": ["long", "string"], "@returns": "string" } } ] } }, + // Fix round 2 (N1): the call is cast to the field's full column type. + { "field.timestamp": { name: "memberSince", "@localTime": true, children: [ + { "origin.function": { "@function": "member_since", "@schema": "app", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" } } ] } }, + { "field.string": { name: "regionCode", "@maxLength": 8, children: [ + { "origin.function": { "@function": "region_code", "@schema": "app", "@args": ["id"], "@params": ["long"], "@returns": "string" } } ] } }, + { "field.decimal": { name: "creditLimit", "@precision": 10, "@scale": 2, children: [ + { "origin.function": { "@function": "credit_limit", "@schema": "app", "@args": ["id"], "@params": ["long"], "@returns": "decimal" } } ] } } ] } }, { "object.entity": { name: "Address", children: [ { "source.rdb": { "@table": "addresses" } }, { "field.long": { name: "id" } }, @@ -73,6 +80,9 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "field.int": { name: "refLength", children: [ { "origin.computed": { "@expr": { fn: "length", args: [ { fn: "replace", args: [ { fn: "substring", args: [ { field: "externalRef" }, { value: 2 }, { value: 3 } ] }, { value: "X" }, { value: "" } ] } ] } } } ] } }, { "field.string": { name: "noRef", children: [ { "origin.computed": { "@expr": { fn: "nullif", args: [ { field: "externalRef" }, { value: "NONE" } ] } } } ] } }, { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }, + { "field.timestamp": { name: "memberSince", "@localTime": true, children: [ { "origin.passthrough": { "@from": "Customer.memberSince", "@via": "Order.customerId" } } ] } }, + { "field.string": { name: "regionCode", "@maxLength": 8, children: [ { "origin.passthrough": { "@from": "Customer.regionCode", "@via": "Order.customerId" } } ] } }, + { "field.decimal": { name: "creditLimit", "@precision": 10, "@scale": 2, children: [ { "origin.passthrough": { "@from": "Customer.creditLimit", "@via": "Order.customerId" } } ] } }, { "field.timestamp": { name: "lastEvent", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, { "field.timestamp": { name: "firstAtStatus", children: [ { "origin.aggregate": { "@agg": "min", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents", "@filter": { stage: { eq: { field: "stage" } } } } } ] } }, { "field.timestamp": { name: "touched", children: [ { "origin.computed": { "@expr": { fn: "greatest", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, @@ -132,6 +142,10 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { // The function the project owns: owned SQL, created before the view that calls it. await sql.raw(`CREATE FUNCTION app.loyalty_tier(bigint, text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN $1 % 2 = 0 THEN 'gold' ELSE 'silver' END || ':' || left($2, 2) $$`).execute(k); + await sql.raw(`CREATE FUNCTION app.member_since(bigint) RETURNS timestamp LANGUAGE sql IMMUTABLE + AS $$ SELECT timestamp '2026-01-01 08:30:00' + ($1 || ' days')::interval $$`).execute(k); + await sql.raw(`CREATE FUNCTION app.region_code(bigint) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT 'R-' || $1 $$`).execute(k); + await sql.raw(`CREATE FUNCTION app.credit_limit(bigint) RETURNS numeric LANGUAGE sql IMMUTABLE AS $$ SELECT $1 * 100.5 $$`).execute(k); const again = await migrate(); // U2: the text spellings are the column types. @@ -147,6 +161,14 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { // I4: the function's call is cast to the carrying field's column type. expect(await rows(`SELECT data_type FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name = 'tier'`)) .toEqual([{ data_type: "text" }]); + // N1: a local timestamp stays without a zone, a sized string keeps its length, a decimal its precision and scale. + expect(await rows(`SELECT column_name, data_type, character_maximum_length, numeric_precision, numeric_scale + FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name IN ('member_since', 'region_code', 'credit_limit') + ORDER BY column_name`)).toEqual([ + { column_name: "credit_limit", data_type: "numeric", character_maximum_length: null, numeric_precision: 10, numeric_scale: 2 }, + { column_name: "member_since", data_type: "timestamp without time zone", character_maximum_length: null, numeric_precision: null, numeric_scale: null }, + { column_name: "region_code", data_type: "character varying", character_maximum_length: 8, numeric_precision: null, numeric_scale: null }, + ]); await sql.raw(` INSERT INTO regions (id, code, label, note) VALUES (1, 'NE', 'north east', 'n'); @@ -180,6 +202,19 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { tier: null, last_event: null, first_at_status: null, touched: null, earliest: null, event_by_customer: null }, ]); + // N1: the local timestamp reads the same in any session zone (a TIMESTAMPTZ cast would have moved it). + // One connection: SET LOCAL holds for the transaction only. + const zoned = await k.transaction().execute(async (trx) => { + await sql.raw(`SET LOCAL TIME ZONE 'America/New_York'`).execute(trx); + return (await sql.raw(`SELECT current_setting('TimeZone') AS tz, id, member_since::text AS member_since, region_code, + credit_limit::text AS credit_limit FROM v_order_row ORDER BY id`).execute(trx)).rows; + }); + expect(zoned).toEqual([ + { tz: "America/New_York", id: "1", member_since: "2026-01-11 08:30:00", region_code: "R-10", credit_limit: "1005.00" }, + { tz: "America/New_York", id: "2", member_since: "2026-01-12 08:30:00", region_code: "R-11", credit_limit: "1105.50" }, + { tz: "America/New_York", id: "3", member_since: "2026-01-13 08:30:00", region_code: "R-12", credit_limit: "1206.00" }, + ]); + // U14: one row per element; a customer whose value is an object or JSON null has none (fix round M3). expect(await rows(`SELECT customer_id, position, kind, preferred, rank FROM v_customer_contact ORDER BY customer_id, position`)).toEqual([ { customer_id: "10", position: 1, kind: "email", preferred: true, rank: 1 }, @@ -195,5 +230,46 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { const followup = await again(); expect(followup.changes).toEqual([]); + + // N2: every declared function is the database's, with the declared types. + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(await checkDeclaredFunctions(k, root)).toEqual([]); }, 120_000); + + // N2: `meta verify --db` reads each declared function from pg_proc; a declaration the database + // does not have is a finding, never hidden by the view's cast. Runs after the test above, which + // created the functions. + test("a declared function signature the database does not have is a finding", async () => { + const fn = (field: Record, origin: Record) => ({ ...field, children: [ { "origin.function": { "@schema": "app", ...origin } } ] }); + const findings = async (...fields: { [k: string]: Record }[]) => { + const model = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Account", children: [ + { "source.rdb": { "@table": "accounts" } }, { "field.long": { name: "id" } }, { "field.int": { name: "pin" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "AccountRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_account_row" } }, + { "field.long": { name: "id", extends: "Account.id" } }, { "field.int": { name: "pin", extends: "Account.pin" } }, + { "identity.primary": { name: "id", extends: "Account.id" } }, ...fields ] } } ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); + expect(errors).toEqual([]); + return checkDeclaredFunctions(k, root); + }; + // Matching declarations: none. + expect(await findings( + { "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["id"], "@params": ["long"], "@returns": "decimal" }) }, + { "field.timestamp": fn({ name: "since", "@localTime": true }, { "@function": "member_since", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" }) }, + )).toEqual([]); + // A numeric result declared int: the cast would round it. + const [rounded] = await findings({ "field.int": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["id"], "@params": ["long"], "@returns": "int" }) }); + expect(rounded).toBe("origin.function app.credit_limit on AccountRow.limit: declared (long) → int, which needs app.credit_limit(bigint) → integer; " + + "the database has app.credit_limit(bigint) → numeric."); + // A local timestamp result on a zoned field: the cast would read it in the session's zone. + const [zoned] = await findings({ "field.timestamp": fn({ name: "since" }, { "@function": "member_since", "@args": ["id"], "@params": ["long"], "@returns": "timestamp" }) }); + expect(zoned).toMatch(/needs app\.member_since\(bigint\) → timestamp with time zone; the database has app\.member_since\(bigint\) → timestamp without time zone\.$/); + // A parameter of another type, and a function that does not exist. + const [param] = await findings({ "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["pin"], "@params": ["int"], "@returns": "decimal" }) }); + expect(param).toMatch(/needs app\.credit_limit\(integer\) → numeric; the database has app\.credit_limit\(bigint\) → numeric\.$/); + const [missing] = await findings({ "field.int": fn({ name: "score" }, { "@function": "no_such_fn", "@args": [], "@params": [], "@returns": "int" }) }); + expect(missing).toBe("origin.function app.no_such_fn on AccountRow.score: no such function in the database (declared () → int)."); + }, 60_000); }); diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index 606d9c3a99..6541892303 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -141,7 +141,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { @@ -184,7 +184,7 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { "name": "returns", "min": 1, "max": 1, - "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." + "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } ] }, diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 48d65853fc..0598f081ba 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -16,6 +16,8 @@ export { } from "./referential-actions.js"; export type { ExpectedSchemaWithProvenance, SchemaProvenance, SchemaBuildSettings } from "./expected-schema.js"; export { introspect, introspectPostgres, introspectSqlite } from "./introspect/index.js"; +// rc.21 part B (N2): each declared origin.function, checked against pg_proc by `meta verify --db`. +export { checkDeclaredFunctions } from "./introspect/declared-functions.js"; export { diff } from "./diff/index.js"; export { defaultConventions, efcoreConventions, resolveSchemaConventions, SCHEMA_CONVENTION_PRESETS, diff --git a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts new file mode 100644 index 0000000000..1598717a6d --- /dev/null +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -0,0 +1,154 @@ +// rc.21 part B fix round 2 (N2): `origin.function` declares its signature (`@params`, `@returns`) +// and the view casts the call to the carrying field's column type. The declaration is trusted at +// load and codegen, so a wrong one would be hidden by that cast (a `numeric` result declared `int` +// rounds). `meta verify --db` reads each declared function from `pg_proc` and refuses any whose +// parameter or return types are not the declared ones. + +import type { Kysely } from "kysely"; +import { sql } from "kysely"; +import { + isMetaObject, + TYPE_OBJECT, + TYPE_ORIGIN, + ORIGIN_SUBTYPE_FUNCTION, + ORIGIN_FUNCTION_ATTR_FUNCTION, + ORIGIN_FUNCTION_ATTR_SCHEMA, + ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_ATTR_PARAMS, + ORIGIN_FUNCTION_ATTR_RETURNS, + type MetaData, +} from "@metaobjectsdev/metadata"; +import { fieldSqlType } from "../expected-schema.js"; +import type { SqlType } from "../sql-type.js"; + +/** One declared function call, with the database type names each position accepts. */ +interface DeclaredFunction { + readonly where: string; + readonly schema: string; + readonly name: string; + readonly declared: string; + readonly params: readonly (readonly string[])[]; + readonly returns: readonly string[]; +} + +/** One overload as `pg_proc` has it, its types spelled by `format_type(oid, NULL)`. */ +interface PgFunction { + readonly args: readonly string[]; + readonly returns: string; + readonly retset: boolean; +} + +const TEXT_TYPES = ["text", "character varying", "character"] as const; + +/** The `format_type` names (no modifier) a column of this type has. Empty: not checkable. */ +function pgTypeNames(t: SqlType): readonly string[] { + switch (t.kind) { + case "text": return TEXT_TYPES; + case "integer": return [t.bits === 64 ? "bigint" : "integer"]; + case "real": return ["double precision"]; + case "real4": return ["real"]; + case "numeric": return ["numeric"]; + case "boolean": return ["boolean"]; + case "date": return ["date"]; + case "uuid": return ["uuid"]; + case "timestamp": return [t.withTimezone ? "timestamp with time zone" : "timestamp without time zone"]; + default: return []; + } +} + +/** A declared parameter subtype's names, when the argument's field cannot be read. */ +function subtypeTypeNames(subType: string): readonly string[] { + switch (subType) { + case "string": return TEXT_TYPES; + case "int": return ["integer"]; + case "long": return ["bigint"]; + case "double": return ["double precision"]; + case "float": return ["real"]; + case "decimal": return ["numeric"]; + case "boolean": return ["boolean"]; + case "date": return ["date"]; + case "uuid": return ["uuid"]; + case "timestamp": return ["timestamp with time zone", "timestamp without time zone"]; + default: return []; + } +} + +function asList(raw: unknown): string[] { + if (raw === undefined) return []; + return (Array.isArray(raw) ? raw : [raw]).filter((v): v is string => typeof v === "string"); +} + +/** Every `origin.function` the model declares, once each. */ +export function declaredFunctions(root: MetaData): DeclaredFunction[] { + const out: DeclaredFunction[] = []; + const seen = new Set(); + // ADR-0039: effective children — resolve rather than rely on root being unextended. + for (const obj of root.children()) { + if (obj.type !== TYPE_OBJECT || !isMetaObject(obj)) continue; + for (const field of obj.fields()) { + // ADR-0039: own — origin.* never inherits (ADR-0029); an inherited field is visited + // through the object that declares it, and `seen` keeps each origin once. + for (const origin of field.ownChildren()) { + if (origin.type !== TYPE_ORIGIN || origin.subType !== ORIGIN_SUBTYPE_FUNCTION || seen.has(origin)) continue; + seen.add(origin); + const name = origin.ownAttr(ORIGIN_FUNCTION_ATTR_FUNCTION); + if (typeof name !== "string") continue; + const schemaAttr = origin.ownAttr(ORIGIN_FUNCTION_ATTR_SCHEMA); + const schema = typeof schemaAttr === "string" ? schemaAttr : "public"; + const args = asList(origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS)); + const params = asList(origin.ownAttr(ORIGIN_FUNCTION_ATTR_PARAMS)); + const returns = origin.ownAttr(ORIGIN_FUNCTION_ATTR_RETURNS); + const fields = obj.fields(); + out.push({ + where: `${obj.name}.${field.name}`, + schema, + name, + declared: `(${params.join(", ")}) → ${String(returns)}`, + params: params.map((p, i) => { + // The argument's own column type when it is a field of this object (a local or a + // zoned timestamp, say); the declared subtype's otherwise. + const argField = fields.find((f) => f.name === args[i]); + const names = argField !== undefined && argField.subType === p ? pgTypeNames(fieldSqlType(argField)) : []; + return names.length > 0 ? names : subtypeTypeNames(p); + }), + returns: pgTypeNames(fieldSqlType(field)), + }); + } + } + } + return out; +} + +async function overloads(db: Kysely, schema: string, name: string): Promise { + const result = await sql<{ args: string[]; returns: string; retset: boolean }>` + SELECT ARRAY(SELECT format_type(a.t, NULL) FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS a(t, i) ORDER BY a.i) AS args, + format_type(p.prorettype, NULL) AS returns, p.proretset AS retset + FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace + WHERE n.nspname = ${schema} AND p.proname = ${name} AND p.prokind = 'f'`.execute(db); + return result.rows.map((r) => ({ args: r.args, returns: r.returns, retset: r.retset })); +} + +function matches(declared: DeclaredFunction, fn: PgFunction): boolean { + if (fn.retset || fn.args.length !== declared.params.length) return false; + if (declared.returns.length > 0 && !declared.returns.includes(fn.returns)) return false; + return declared.params.every((accepted, i) => accepted.length === 0 || accepted.includes(fn.args[i]!)); +} + +/** + * The findings for every declared `origin.function` the Postgres database does not have with + * the declared parameter and return types: one line each, empty when all match. + */ +export async function checkDeclaredFunctions(db: Kysely, root: MetaData): Promise { + const findings: string[] = []; + for (const declared of declaredFunctions(root)) { + const found = await overloads(db, declared.schema, declared.name); + if (found.some((fn) => matches(declared, fn))) continue; + const qualified = `${declared.schema}.${declared.name}`; + const expected = `(${declared.params.map((p) => p.join(" | ") || "any").join(", ")}) → ${declared.returns.join(" | ") || "any"}`; + findings.push(found.length === 0 + ? `origin.function ${qualified} on ${declared.where}: no such function in the database (declared ${declared.declared}).` + : `origin.function ${qualified} on ${declared.where}: declared ${declared.declared}, which needs ${qualified}${expected}; ` + + `the database has ${found.map((fn) => `${qualified}(${fn.args.join(", ")}) → ${fn.retset ? "SETOF " : ""}${fn.returns}`).join("; ")}.`); + } + return findings; +} diff --git a/site-reference/index.html b/site-reference/index.html index 69b27d60f1..56fdfa4c2c 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -312,7 +312,7 @@
    - + diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index a8ac236d15..d05225a155 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -237,7 +237,7 @@

    origin.first

    Allowed children

    No structural children.

    origin.function

    -

    A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.

    +

    A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.

    Owning provider: metaobjects-core-types

    When to use: A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.

    Attributes

    @@ -287,7 +287,7 @@

    origin.function

    - + diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index b175e9b4a8..e8cfe7e735 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -45,14 +45,14 @@ { "type": "origin", "subType": "function", - "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments." }, { "type": "attr", "subType": "string", "name": "params", "isArray": true, "min": 0, "max": 1, "description": "The function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN)." }, - { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns." } + { "type": "attr", "subType": "string", "name": "returns", "min": 1, "max": 1, "description": "The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc)." } ] }, { From d085111a19900e22369bc6cef925582484ffb579 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:43:47 -0500 Subject: [PATCH 214/267] fix(views): a derived field that depends on itself is refused at load A view inlines a derived field's dependencies on the same row (a function's @args, a computed expression's field refs), so a cycle has no SQL; codegen recursed until the stack ran out. The loader now refuses each cycle once, naming its path, in TypeScript and C#. Co-Authored-By: Claude Opus 5.5 --- .../ViewVocabularyRc21LoaderTests.cs | 21 +++++++ .../MetaObjects/Loader/MetaDataLoader.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 63 +++++++++++++++++++ .../metadata/src/loader/meta-data-loader.ts | 4 +- .../metadata/src/loader/validation-passes.ts | 49 +++++++++++++++ .../test/rc21b-view-vocabulary.test.ts | 18 ++++++ 6 files changed, 156 insertions(+), 1 deletion(-) diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index f02a1ce26a..e56bafa16f 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -265,4 +265,25 @@ public void A_union_member_with_its_own_union_is_refused() { "object.projection": { "name": "U", "extends": "A", "@union": ["B"], "children": [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } } """); } + // Fix round 2 (N3): a view inlines a derived field's dependencies on the same row; a cycle has no SQL. + private static string Meter(params string[] fields) => $$""" + { "object.entity": { "name": "Meter", "children": [ + { "source.rdb": { "@table": "meters" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "name": "id", "@fields": "id" } }{{string.Concat(fields.Select(f => ",\n" + f))}} ] } }, + { "object.projection": { "name": "MeterRow", "children": [ { "source.rdb": { "@kind": "view", "@view": "v_meter" } }, + { "field.long": { "name": "id", "extends": "Meter.id" } }, + { "field.long": { "name": "a", "children": [ { "origin.passthrough": { "@from": "Meter.a" } } ] } }, + { "identity.primary": { "name": "id", "extends": "Meter.id" } } ] } } + """; + + private static string FnField(string name, string arg) => + $$"""{ "field.long": { "name": "{{name}}", "children": [ { "origin.function": { "@function": "f_{{name}}", "@args": ["{{arg}}"], "@params": ["long"], "@returns": "long" } } ] } }"""; + + [Fact] + public void A_cycle_through_derived_function_arguments_is_refused_naming_the_path() + { + Refused("ERR_INVALID_ORIGIN", "Meter.a: a derived field depends on itself through a → b → a", Meter(FnField("a", "b"), FnField("b", "a"))); + Refused("ERR_INVALID_ORIGIN", "depends on itself through a → c → a", Meter(FnField("a", "c"), + """{ "field.long": { "name": "c", "children": [ { "origin.computed": { "@expr": { "fn": "coalesce", "args": [ { "field": "a" }, { "field": "id" } ] } } } ] } }""")); + Assert.Empty(Load(Meter(FnField("a", "b"), FnField("b", "id")))); + } } diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index d4c20781e9..4ea994447a 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -530,6 +530,8 @@ public LoadResult Load(IReadOnlyList sources) errors.AddRange(ValidationPasses.ValidateOriginSegmentsAndCorrelation(root)); // rc.21 part B — @union shapes and @grain projections. errors.AddRange(ValidationPasses.ValidateProjectionUnionAndGrain(root)); + // rc.21 part B fix round 2 (N3): a derived field that depends on itself has no SQL. + errors.AddRange(ValidationPasses.ValidateDerivedCycles(root)); // Pass 7c (FR-044): reporting vocabulary cross-node rules (dimensions, measures, // segments, reports, relative-date filter values). diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index d5b555f89d..0f86df7da3 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1764,6 +1764,69 @@ private static void ReachFunctionArgs(MetaData f, HashSet reached) ReachFunctionArgs(arg, reached); } + // ========================================================================= + // rc.21 part B fix round 2 (N3): no derived field depends on itself. A view inlines a derived + // field's dependencies on the same row (an origin.function's @args, an origin.computed + // expression's field refs), so a cycle has no SQL and would recurse forever. Refused once per + // cycle, naming the path (ERR_INVALID_ORIGIN). Ported from validation-passes.ts + // validateDerivedCycles. + // ========================================================================= + + public static IReadOnlyList ValidateDerivedCycles(MetaData root) + { + var errors = new List(); + // ADR-0039: effective children, as TS iterates them. + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT)) + { + // ADR-0039: effective — an inherited field's origin is inlined on the extender's row too. + var fields = obj.Children().Where(c => c.Type == TYPE_FIELD).ToList(); + var byName = new Dictionary(); + foreach (var f in fields) byName.TryAdd(f.Name, f); + // ADR-0039: own — origin.* never inherits (ADR-0029). + MetaData? OriginOf(MetaData f) => f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + List Deps(MetaData f) + { + var origin = OriginOf(f); + var names = new List(); + if (origin?.SubType == ORIGIN_SUBTYPE_FUNCTION) + { + var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); + var list = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + names.AddRange(list.OfType()); + } + else if (origin?.SubType == ORIGIN_SUBTYPE_COMPUTED) + { + names.AddRange(ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Select(n => n.Split('.')[0])); + } + return names.Select(n => byName.TryGetValue(n, out var d) ? d : null) + .Where(d => d is not null && !ReferenceEquals(d, f) && OriginOf(d) is not null).Select(d => d!).ToList(); + } + var done = new HashSet(ReferenceEqualityComparer.Instance); + var reported = new HashSet(); + void Visit(MetaData f, List path) + { + var at = path.FindIndex(x => ReferenceEquals(x, f)); + if (at >= 0) + { + var cycle = path.Skip(at).Append(f).Select(x => x.Name).ToList(); + var key = string.Join(",", cycle.Take(cycle.Count - 1).OrderBy(n => n, StringComparer.Ordinal)); + if (reported.Add(key)) + { + errors.Add(new MetaError( + $"{obj.Name}.{f.Name}: a derived field depends on itself through {string.Join(" → ", cycle)}; a view inlines each dependency on the same row, so the cycle has no SQL. Break it.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: (OriginOf(f) ?? f).Source)); + } + return; + } + if (done.Contains(f)) return; + foreach (var d in Deps(f)) Visit(d, [.. path, f]); + done.Add(f); + } + foreach (var f in fields.Where(f => OriginOf(f) is not null)) Visit(f, []); + } + return errors; + } + // ========================================================================= // rc.19 origin-segment and correlated-filter, on every origin.first / origin.aggregate: // @segment names a segment of the related entity (ERR_INVALID_ORIGIN); an @filter operand diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index c952a6358f..8789ce629d 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -26,7 +26,7 @@ import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, - validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateExtenderSubtypeScope, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; + validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateDerivedCycles, validateExtenderSubtypeScope, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -667,6 +667,8 @@ export class MetaDataLoader { errors.push(...validateOriginSegmentsAndCorrelation(root)); // rc.21 part B — @union shapes and @grain projections. errors.push(...validateProjectionUnionAndGrain(root)); + // rc.21 part B fix round 2 (N3): a derived field that depends on itself has no SQL. + errors.push(...validateDerivedCycles(root)); // FR-044 — reporting vocabulary cross-node rules (dimensions, measures, // segments, reports, relative-date filter values). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 77884fd1d5..e6b699d966 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -2061,6 +2061,55 @@ function _reachFunctionArgs(f: MetaData, reached: Set): void { } } +/** + * rc.21 part B fix round 2 (N3): no derived field depends on itself. A view inlines a derived + * field's dependencies on the same row — an origin.function's @args, an origin.computed + * expression's field refs — so a cycle among them (a's argument is b, b's is a) has no SQL and + * would recurse forever. Refused at load, once per cycle, naming the path (ERR_INVALID_ORIGIN). + */ +export function validateDerivedCycles(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT)) { + // ADR-0039: effective — an inherited field's origin is inlined on the extender's row too. + const fields = obj.children().filter((c) => c.type === TYPE_FIELD); + const byName = new Map(fields.map((f) => [f.name, f])); + // ADR-0039: own — origin.* never inherits (ADR-0029); it is the field's own child. + const originOf = (f: MetaData) => f.ownChildren().find((c) => c.type === TYPE_ORIGIN); + const deps = (f: MetaData): MetaData[] => { + const origin = originOf(f); + const names: string[] = []; + if (origin?.subType === ORIGIN_SUBTYPE_FUNCTION) { + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + for (const n of raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]) if (typeof n === "string") names.push(n); + } else if (origin?.subType === ORIGIN_SUBTYPE_COMPUTED) { + for (const n of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) names.push(n.split(".")[0]!); + } + return names.map((n) => byName.get(n)).filter((d): d is MetaData => d !== undefined && d !== f && originOf(d) !== undefined); + }; + const done = new Set(); + const reported = new Set(); + const visit = (f: MetaData, path: MetaData[]): void => { + const at = path.indexOf(f); + if (at >= 0) { + const cycle = [...path.slice(at), f].map((x) => x.name); + const key = [...cycle.slice(0, -1)].sort().join(","); + if (!reported.has(key)) { + reported.add(key); + errors.push(new ParseError( + `${obj.name}.${f.name}: a derived field depends on itself through ${cycle.join(" → ")}; a view inlines each dependency on the same row, so the cycle has no SQL. Break it.`, + { code: "ERR_INVALID_ORIGIN", source: originOf(f)?.source ?? f.source })); + } + return; + } + if (done.has(f)) return; + for (const d of deps(f)) visit(d, [...path, f]); + done.add(f); + }; + for (const f of fields) if (originOf(f) !== undefined) visit(f, []); + } + return errors; +} + /** * rc.19 origin-segment and correlated-filter, on every origin.first / origin.aggregate: * - `@segment` names a segment.filter declared on the related entity (the @of entity, else diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index 8873911fde..b09d58b547 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -174,6 +174,24 @@ describe("U10 — origin.function", () => { { "field.int": { name: "idAsInt", children: [ { "origin.computed": { "@expr": { cast: { field: "id" }, as: "int" } } } ] } }, { "field.string": { name: "tier", children: [ { "origin.function": { "@function": "tier_of", "@args": ["idAsInt"], "@params": ["int"], "@returns": "string" } } ] } } ] } }, reach); }); + // Fix round 2 (N3): a view inlines a derived field's dependencies on the same row; a cycle has no SQL. + test("a cycle through derived function arguments is refused, naming the path", async () => { + const meter = (...fields: unknown[]) => ({ "object.entity": { name: "Meter", children: [ + { "source.rdb": { "@table": "meters" } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ...fields ] } }); + const fnField = (name: string, arg: string) => ({ "field.long": { name, children: [ + { "origin.function": { "@function": `f_${name}`, "@args": [arg], "@params": ["long"], "@returns": "long" } } ] } }); + const meterRow = { "object.projection": { name: "MeterRow", children: [ { "source.rdb": { "@kind": "view", "@table": "v_meter" } }, + { "field.long": { name: "id", extends: "Meter.id" } }, + { "field.long": { name: "a", children: [ { "origin.passthrough": { "@from": "Meter.a" } } ] } }, + { "identity.primary": { name: "id", extends: "Meter.id" } } ] } }; + // function → function + await refused("ERR_INVALID_ORIGIN", /Meter\.a: a derived field depends on itself through a → b → a/, meter(fnField("a", "b"), fnField("b", "a")), meterRow); + // function → computed → function + await refused("ERR_INVALID_ORIGIN", /depends on itself through a → c → a/, + meter(fnField("a", "c"), { "field.long": { name: "c", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "a" }, { field: "id" } ] } } } ] } }), meterRow); + // A chain without a cycle loads. + await ok(meter(fnField("a", "b"), fnField("b", "id")), meterRow); + }); test("an unreached function field on an entity with no read source is refused", async () => { await refused("ERR_DERIVED_FIELD_NO_READ_SOURCE", /tier/, withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["long"], "@returns": "string" })); }); From f00f3f45089a62e3c1a170eb90b9f9df5f8705b6 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:46:23 -0500 Subject: [PATCH 215/267] fix(views): migrate and verify print the widened-extender warning; abstract extenders are not warned about Every command that loads a model to emit or check views now says it, through one helper. An abstract extender emits no view, so the pass skips it, in both ports, and C# iterates the effective root children TypeScript does (here and in the union/grain pass). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- .../ViewVocabularyRc21LoaderTests.cs | 1 + .../MetaObjects/Loader/ValidationPasses.cs | 7 +++- .../packages/cli/src/commands/gen.ts | 8 ++-- .../packages/cli/src/commands/migrate.ts | 7 ++++ .../packages/cli/src/commands/verify.ts | 3 ++ .../packages/cli/src/lib/widened-extenders.ts | 13 +++++++ .../test/gen-extender-scope-warning.test.ts | 37 ++++++++++++++++--- .../metadata/src/loader/validation-passes.ts | 2 + .../test/rc21b-view-vocabulary.test.ts | 3 ++ 10 files changed, 72 insertions(+), 12 deletions(-) create mode 100644 server/typescript/packages/cli/src/lib/widened-extenders.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e94c1ee7e0..2473fd54a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -388,7 +388,8 @@ vocabulary; upgrade every port together. base reads the shared table's column (it read a column named after the projection field). The load now warns in exactly the case whose output widened: an extender with no identity of its own, anchored by its super on a TPH base, whose own fields bind a subtype-only column, and no - `@filter` on the discriminator. `meta gen` and `dotnet meta gen` print that warning (the + `@filter` on the discriminator (an abstract extender emits no view, so it is never warned + about). `meta gen`, `meta migrate`, `meta verify` and `dotnet meta gen` print that warning (the loader's warning channel is not otherwise printed). **Upgrade note:** to get the subtype-scoped view back, either add `@filter: { : }` to the extender, or anchor it on the subtype: declare `identity.primary { name: id, extends: .primary }` with a field extending diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index e56bafa16f..73835cac22 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -196,6 +196,7 @@ public void A_passthrough_over_a_reverse_hop_needs_a_unique_identity(bool unique [Theory] [InlineData("", true)] [InlineData("\"@filter\": { \"kind\": \"TRUCK\" },", false)] + [InlineData("\"abstract\": true,", false)] public void An_extender_whose_view_widened_over_a_tph_base_warns(string filter, bool warns) { var json = $$""" diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 0f86df7da3..33a7c8cdae 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1346,8 +1346,11 @@ private static bool ReverseHopIsUnique(MetaData rel) public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) { var warnings = new List(); - foreach (var obj in root.OwnChildren().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) + // ADR-0039: effective children, the nodes TS iterates (fix round 2, N4). + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) { + // An abstract extender emits no view, so nothing it declares widened one. + if (obj.IsAbstract) continue; if (obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY)) continue; if (obj.SuperData is not { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } sup || !AnchorsByIdentity(sup)) continue; if (DeriveBaseEntity(obj, root, "@extends", obj.Source, new List()) is not { } baseEntity) continue; @@ -1951,7 +1954,7 @@ private static void ValidateFunctionOrigin(MetaData origin, MetaData obj, MetaDa public static IReadOnlyList ValidateProjectionUnionAndGrain(MetaData root) { var errors = new List(); - foreach (var obj in root.OwnChildren().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) + foreach (var obj in root.Children().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) { void Bad(string message) => errors.Add(new MetaError($"object.projection {obj.Name}: {message}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: obj.Source)); // ADR-0039: own — a projection's @union / @grain names ITS view's shape. diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index 934fd0fd9b..a224f3ccee 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -18,7 +18,8 @@ import { import { loadMemory, resolveCollection } from "@metaobjectsdev/sdk"; import { declaredGeneratorNames, runGen, undeclaredGeneratorsMessage } from "@metaobjectsdev/codegen-ts"; import type { WriteStatus } from "@metaobjectsdev/codegen-ts"; -import { packageOfResolutionKey, validateExtenderSubtypeScope } from "@metaobjectsdev/metadata"; +import { packageOfResolutionKey } from "@metaobjectsdev/metadata"; +import { warnWidenedExtenders } from "../lib/widened-extenders.js"; import type { MetaRoot } from "@metaobjectsdev/metadata"; import type { Collection } from "@metaobjectsdev/sdk"; import { describeLoadError, reportLoadError } from "../lib/load-error.js"; @@ -215,9 +216,8 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat ? [...unknownAttrFindings, UNKNOWN_ATTR_GEN_ADVICE] : []; for (const w of unknownAttrs) { log.warn(`warning: ${w}`); warnings.push(w); } - // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. The loader - // records it on its warning channel, which `loadMemory` does not return, so it is said here. - for (const w of validateExtenderSubtypeScope(metadata)) { log.warn(`warning: ${w}`); warnings.push(w); } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnings.push(...warnWidenedExtenders(metadata, (line) => log.warn(line))); // The schema settings `meta migrate` builds with, for the Prisma schema, the schema page and // the migrate advice. A conventions preset that does not resolve is a config error here as in diff --git a/server/typescript/packages/cli/src/commands/migrate.ts b/server/typescript/packages/cli/src/commands/migrate.ts index 91454c84df..726f041b41 100644 --- a/server/typescript/packages/cli/src/commands/migrate.ts +++ b/server/typescript/packages/cli/src/commands/migrate.ts @@ -84,6 +84,7 @@ import { decimalPrecisionWarnings } from "../lib/decimal-precision-advisory.js"; import { schemaAdvisoryLines } from "../lib/schema-advisories.js"; import { scanForReferentialActionConflicts } from "../lib/referential-action-advisory.js"; import type { MetaData, MetaRoot } from "@metaobjectsdev/metadata"; +import { warnWidenedExtenders } from "../lib/widened-extenders.js"; import { describeError } from "../lib/error-text.js"; /** @@ -827,6 +828,8 @@ export async function migrateCommand( reportLoadError(log, "failed to load metadata", err); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(metadata, (line) => log.warn(line)); warnReferentialActionConflicts(metadata, collection, schema); let kysely; @@ -1568,6 +1571,8 @@ export async function runOfflineGenerate( reportLoadError(log, "migrate: failed to load metadata", err); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(metadata, (line) => log.warn(line)); const schema = resolveSchemaBuild(collection, offlineGenConfig, fmt); if (typeof schema === "number") return schema; warnReferentialActionConflicts(metadata, collection, schema); @@ -1882,6 +1887,8 @@ async function runD1Migrate( reportLoadError(log, "migrate: failed to load metadata", err); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(metadata, (line) => log.warn(line)); const schema = resolveSchemaBuild(collection, d1GenConfig, fmt); if (typeof schema === "number") return schema; warnReferentialActionConflicts(metadata, collection, schema); diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index c911264787..a3181125a5 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -60,6 +60,7 @@ import { import type { MetaobjectsGenConfig } from "@metaobjectsdev/codegen-ts"; import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; import { buildKyselyFromUrl, inferDialect, type Dialect } from "../lib/kysely.js"; +import { warnWidenedExtenders } from "../lib/widened-extenders.js"; import { tokensToAllowOptions, describeChange } from "../lib/allow.js"; import { computeDrift, @@ -403,6 +404,8 @@ export async function verifyCommand( }, fmt); return 1; } + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. + warnWidenedExtenders(root, (line) => log.warn(line)); // The project's schema settings, resolved once for every expected-schema build and drift // computation below. A `migrate.conventions` preset this version does not ship is a config diff --git a/server/typescript/packages/cli/src/lib/widened-extenders.ts b/server/typescript/packages/cli/src/lib/widened-extenders.ts new file mode 100644 index 0000000000..ff69bd9367 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/widened-extenders.ts @@ -0,0 +1,13 @@ +// rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields read +// a TPH subtype's columns now returns every base row. The loader records that on its warning +// channel, which `loadMemory` does not return, so every command that loads a model to emit or check +// views — gen, migrate, verify — says it here, the same way. + +import { validateExtenderSubtypeScope, type MetaData } from "@metaobjectsdev/metadata"; + +/** Print each widened-extender finding through `warn` and return the findings. */ +export function warnWidenedExtenders(root: MetaData, warn: (line: string) => void): string[] { + const findings = validateExtenderSubtypeScope(root); + for (const w of findings) warn(`warning: ${w}`); + return findings; +} diff --git a/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts index ef45eaa62b..495accc4eb 100644 --- a/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts +++ b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts @@ -1,6 +1,7 @@ // rc.21 part B (I2): an extender keeps its super's identity anchor, so a view whose own fields // read a TPH subtype's columns returns every base row. The loader records that on its warning -// channel, which `loadMemory` does not return; `meta gen` prints it so the change is visible. +// channel, which `loadMemory` does not return; every command that loads a model to emit or check +// views (gen, migrate, verify) prints it, so the change is visible. import { describe, test, expect, beforeEach, afterEach } from "bun:test"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; @@ -8,7 +9,7 @@ import { run } from "../src/index.js"; const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures", "__tmp__"); -function model(scoped: boolean): string { +function model(scoped: boolean, abstract = false): string { return JSON.stringify({ "metadata.root": { package: "app", @@ -21,7 +22,7 @@ function model(scoped: boolean): string { { "object.projection": { name: "VehicleBase", abstract: true, children: [ { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, - { "object.projection": { name: "TruckRow", extends: "VehicleBase", ...(scoped ? { "@filter": { kind: "TRUCK" } } : {}), children: [ + { "object.projection": { name: "TruckRow", extends: "VehicleBase", ...(abstract ? { abstract: true } : {}), ...(scoped ? { "@filter": { kind: "TRUCK" } } : {}), children: [ { "source.rdb": { "@kind": "view", "@view": "v_trucks" } }, { "field.string": { name: "payload", extends: "Truck.payloadClass" } } ] } }, ], @@ -29,11 +30,11 @@ function model(scoped: boolean): string { }); } -function setupRepo(scoped: boolean): string { +function setupRepo(scoped: boolean, abstract = false): string { mkdirSync(WORKSPACE_TMP, { recursive: true }); const root = mkdtempSync(join(WORKSPACE_TMP, "gen-extender-scope-")); mkdirSync(join(root, "metaobjects"), { recursive: true }); - writeFileSync(join(root, "metaobjects", "meta.app.json"), model(scoped), "utf8"); + writeFileSync(join(root, "metaobjects", "meta.app.json"), model(scoped, abstract), "utf8"); mkdirSync(join(root, ".metaobjects"), { recursive: true }); writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }), "utf8"); writeFileSync(join(root, "metaobjects.config.ts"), ` @@ -80,6 +81,32 @@ describe("meta gen — the widened-extender warning is printed", () => { } }); + test("meta verify and meta migrate print it too (fix round 2, N4)", async () => { + const root = setupRepo(false); + try { + await run(["verify", "--cwd", root]); + expect(err.join("\n")).toContain("object.projection TruckRow"); + err.length = 0; + await run(["migrate", "--cwd", root, "--dialect", "sqlite", "--dry-run"]); + expect(err.join("\n")).toContain("object.projection TruckRow"); + err.length = 0; + await run(["migrate", "--cwd", root, "--from-db", "--db", `file:${join(root, "t.db")}`, "--slug", "init", "--dry-run"]); + expect(err.join("\n")).toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test("an abstract extender emits no view: no warning (fix round 2, N4)", async () => { + const root = setupRepo(false, true); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + expect(err.join("\n")).not.toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + test("a discriminator filter scopes it: no warning", async () => { const root = setupRepo(true); try { diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index e6b699d966..a317779277 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -1045,6 +1045,8 @@ function _deriveBaseEntity( export function validateExtenderSubtypeScope(root: MetaData): string[] { const warnings: string[] = []; for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_PROJECTION)) { + // An abstract extender emits no view, so nothing it declares widened one (fix round 2, N4). + if (obj.isAbstract) continue; // ADR-0039: own — the identity anchor rule applies to an extender that declares none of its own. if (obj.ownChildren().some((c) => c.type === TYPE_IDENTITY)) continue; const sup = obj.superResolved; diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index b09d58b547..e88493df7f 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -264,6 +264,9 @@ describe("an extender whose view widened over a TPH base", () => { expect(w[0]).toMatch(/"payload" \(Truck.payloadClass\) read columns only a subtype carries, over the TPH base Vehicle with no @filter on its discriminator "kind"/); expect(w[0]).toMatch(/@filter \{ kind: \} or declare identity.primary \{ extends: Truck.primary \}/); }); + test("an abstract extender emits no view: no warning (fix round 2)", async () => { + expect((await warningsOf(row({ abstract: true }))).filter((m) => m.includes("TruckRow"))).toEqual([]); + }); test("a discriminator filter, or its own identity, scopes it: no warning", async () => { expect((await warningsOf(row({ "@filter": { kind: "TRUCK" } }))).filter((m) => m.includes("TruckRow"))).toEqual([]); expect((await warningsOf(row({}, [{ "field.long": { name: "vehicleId", extends: "Truck.id" } }, From d03262e826cc4da62dd68204814362304d2d3c83 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:48:18 -0500 Subject: [PATCH 216/267] chore(fixtures): the shared TPH test model is Coupon and Permit, not copay and prior authorization A case-preserving rename across every port's tests, golden fixtures, docs and CHANGELOG (contents and file names): Copay -> Coupon, PriorAuth -> Permit, in each spelling (camel, Pascal, snake, upper). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- .../references/inheritance-tph.md | 2 +- .../metaobjects-codegen/references/csharp.md | 2 +- .../metaobjects-codegen/references/java.md | 2 +- .../references/physical-names.md | 2 +- docs/features/abstracts-and-inheritance.md | 18 +- .../emit-attrs-to-generator-config.md | 2 +- docs/features/relationships.md | 2 +- docs/ports/csharp.md | 10 +- docs/ports/java.md | 14 +- docs/ports/kotlin.md | 6 +- docs/ports/python.md | 10 +- docs/ports/typescript-client.md | 2 +- docs/ports/typescript.md | 8 +- ...1-metamodel-batch-metadata-codegen-plan.md | 8 +- ...6-05-31-metamodel-batch-migrate-ts-plan.md | 6 +- ...3-int-backed-enum-values-ts-persistence.md | 2 +- ...6-07-23-tph-autoset-controller-stamping.md | 6 +- ...6-05-28-fr-014-tph-discriminator-design.md | 12 +- ...2-fr-017-tph-polymorphic-codegen-design.md | 40 ++-- ...ross-port-package-binding-config-design.md | 4 +- .../codegen/generators/routes.ts | 2 +- .../codegen/runtime/drizzle-fastify/index.ts | 2 +- .../runtime/drizzle-fastify/mount-m2m.ts | 2 +- .../showcase/codegen/generators/routes.ts | 2 +- .../codegen/runtime/drizzle-fastify/index.ts | 2 +- .../runtime/drizzle-fastify/mount-m2m.ts | 2 +- .../references/inheritance-tph.md | 2 +- .../metaobjects-codegen/references/java.md | 2 +- .../references/physical-names.md | 2 +- .../references/inheritance-tph.md | 2 +- .../metaobjects-codegen/references/java.md | 2 +- .../references/physical-names.md | 2 +- .../references/inheritance-tph.md | 2 +- .../references/physical-names.md | 2 +- .../references/inheritance-tph.md | 2 +- .../references/physical-names.md | 2 +- .../references/inheritance-tph.md | 2 +- .../references/physical-names.md | 2 +- .../api-contract-conformance/tph/README.md | 14 +- .../api-contract-conformance/tph/meta.json | 12 +- .../tph-base-filter-by-discriminator.yaml | 6 +- .../tph-create-constraint-violation.yaml | 10 +- .../tph/scenarios/tph-cross-subtype-404.yaml | 8 +- .../tph-per-subtype-list-and-create.yaml | 20 +- .../tph-polymorphic-list-and-get.yaml | 4 +- .../tph-update-constraint-violation.yaml | 14 +- .../tph-update-explicit-null-clears.yaml | 12 +- .../api-contract-conformance/tph/seed.json | 6 +- .../input/meta.demo.json | 2 +- .../input/meta.demo.json | 2 +- .../expected.json | 8 +- .../input/meta.demo.json | 8 +- .../tph-shared-marks/expected/openapi.json | 76 +++---- .../schemas/acme/auth/Auth.schema.json | 2 +- ...ema.json => CouponAuth.create.schema.json} | 4 +- ...uth.schema.json => CouponAuth.schema.json} | 6 +- ...ema.json => CouponAuth.strict.schema.json} | 2 +- ...ema.json => CouponAuth.update.schema.json} | 4 +- .../tph-shared-marks/meta.json | 6 +- .../tph/expected/openapi.json | 196 +++++++++--------- .../schemas/acme/auth/Auth.schema.json | 4 +- ...ema.json => CouponAuth.create.schema.json} | 6 +- ...uth.schema.json => CouponAuth.schema.json} | 10 +- ...ema.json => CouponAuth.strict.schema.json} | 6 +- ...ema.json => CouponAuth.update.schema.json} | 6 +- ...ema.json => PermitAuth.create.schema.json} | 4 +- ...uth.schema.json => PermitAuth.schema.json} | 6 +- ...ema.json => PermitAuth.strict.schema.json} | 2 +- ...ema.json => PermitAuth.update.schema.json} | 4 +- .../canonical/expected/model/cubes/Auth.yml | 2 +- .../cubes/{CopayAuth.yml => CouponAuth.yml} | 4 +- .../{PriorAuthAuth.yml => PermitAuth.yml} | 4 +- fixtures/cube-model/canonical/seed.mysql.sql | 4 +- fixtures/cube-model/canonical/seed.sql | 4 +- .../cube-model/entity-tph-subtype/meta.json | 6 +- fixtures/persistence-conformance/README.md | 2 +- .../canonical/meta.fitness.json | 14 +- .../canonical/schema.mysql.sql | 4 +- .../canonical/schema.postgres.sql | 6 +- .../canonical/schema.sqlite.sql | 6 +- .../queries/report-tph-base-filter.yaml | 14 +- .../queries/tph-insert-then-find-by-id.yaml | 10 +- .../tph-insert-three-subtypes-list.yaml | 18 +- .../queries/tph-no-cross-subtype-update.yaml | 14 +- .../NamesExtendsChainTests.cs | 24 +-- .../PackageBindingResolverTests.cs | 2 +- .../TphCodegenTests.cs | 60 +++--- .../TphM2mRoutesTests.cs | 68 +++--- .../Generators/NamesGenerator.cs | 2 +- .../MetaObjects.Codegen/Generators/TphPlan.cs | 2 +- .../Api/ApiContractCorpusPaths.cs | 2 +- .../Api/TphFixture.cs | 14 +- .../Api/TphGeneratedServerFactory.cs | 2 +- .../Api/TphReferenceServer.cs | 38 ++-- .../AppDbContextModelTests.cs | 4 +- .../Generated/AppDbContext.g.cs | 4 +- .../Generated/fitness/Auth.g.cs | 6 +- .../Generated/fitness/AuthsByKind.g.cs | 2 +- .../{CopayAuth.g.cs => CouponAuth.g.cs} | 6 +- ...payAuthNames.g.cs => CouponAuthNames.g.cs} | 12 +- .../{PriorAuthAuth.g.cs => PermitAuth.g.cs} | 4 +- ...uthAuthNames.g.cs => PermitAuthNames.g.cs} | 6 +- .../Exposed1xControllerCompileTest.kt | 2 +- .../generator/kotlin/KotlinM2mSupport.kt | 2 +- .../generator/kotlin/KotlinNamesGenerator.kt | 2 +- .../kotlin/KotlinSpringControllerGenerator.kt | 2 +- ...linM2mSupportAbstractMidLevelTargetTest.kt | 8 +- .../kotlin/KotlinNamesGeneratorTest.kt | 14 +- .../kotlin/KotlinOutputCompilesTest.kt | 16 +- .../kotlin/KotlinTphM2mCodegenTest.kt | 20 +- .../kotlin/KotlinTphM2mShadowedCodegenTest.kt | 56 ++--- .../kotlin/KotlinUuidPrimaryKeyCodegenTest.kt | 12 +- .../KotlinSpringControllerGenerator.kt.txt | 2 +- .../fixtures/entity-with-tph/meta.json | 14 +- .../entity-with-tph/acme/auth/Auth.kt | 20 +- .../acme/auth/AuthController.kt | 162 +++++++-------- .../acme/auth/AuthFilterAllowlist.kt | 8 +- .../entity-with-tph/acme/auth/AuthTable.kt | 4 +- .../entity-with-tph/acme/auth/AuthType.kt | 4 +- ...hValidation.kt => CouponAuthValidation.kt} | 6 +- ...hValidation.kt => PermitAuthValidation.kt} | 6 +- .../spring/SpringNamesGenerator.java | 2 +- .../metaobjects/generator/spring/TphPlan.java | 2 +- ...eneratedTphM2mTraversalCompileRunTest.java | 50 ++--- .../spring/SpringAutoSetStampingTest.java | 2 +- .../spring/SpringCreateDefaultsTest.java | 4 +- .../SpringFilterAllowlistGeneratorTest.java | 10 +- .../spring/SpringM2mTargetTphCodegenTest.java | 10 +- .../spring/SpringTphM2mCodegenTest.java | 48 ++--- ...SpringTphM2mShadowedTargetCodegenTest.java | 20 +- .../SpringUuidPrimaryKeyCodegenTest.java | 12 +- .../TphDiscriminatorEnumConformanceTest.java | 4 +- .../integration/kotlin/QueryScenarioRunner.kt | 2 +- .../api/tph/TphFullSuiteCompilesTest.kt | 28 +-- .../TphGeneratedApiContractConformanceTest.kt | 4 +- .../api/tph/TphM2mFullSuiteCompilesTest.kt | 12 +- .../TphM2mShadowedFullSuiteCompilesTest.kt | 44 ++-- .../GeneratedTphControllerHarness.kt | 6 +- .../integration/kotlin/tables/AuthTable.kt | 8 +- .../integration/QueryScenarioTests.java | 4 +- ...phGeneratedApiContractConformanceTest.java | 4 +- .../GeneratedTphControllerHarness.java | 10 +- .../InMemoryAuthRepositorySource.java | 8 +- .../codegen/generators/tph_plan.py | 2 +- .../tests/codegen/test_names_extends_chain.py | 56 ++--- .../tests/codegen/test_router_generator.py | 6 +- .../test_router_generator_m2m_target_tph.py | 6 +- .../codegen/test_router_generator_tph_m2m.py | 42 ++-- .../test_router_generator_tph_m2m_shadowed.py | 14 +- .../python/tests/codegen/test_tph_codegen.py | 16 +- .../tests/integration/generated_tph_app.py | 2 +- .../test_m2m_target_tph_generated.py | 12 +- .../integration/test_tph_m2m_generated.py | 24 +-- .../test_tph_m2m_shadowed_generated.py | 20 +- .../codegen-ts-react/test/tph-form.test.ts | 8 +- .../codegen-ts-tanstack/test/tph-grid.test.ts | 36 ++-- .../test/tph-hooks.test.ts | 14 +- .../packages/codegen-ts/src/constants.ts | 2 +- .../codegen-ts/src/reference/routes.ts | 2 +- .../codegen-ts/src/templates/routes-file.ts | 2 +- .../codegen-ts/test/api-model.test.ts | 2 +- .../test/contract/contract-behaviours.test.ts | 10 +- .../test/cube/build-cube-model.test.ts | 4 +- .../test/cube/cube-model-canonical.test.ts | 4 +- .../codegen-ts/test/cube/cube-yaml.test.ts | 2 +- .../test/cube/report-rollups.test.ts | 2 +- .../codegen-ts/test/cube/report-spine.test.ts | 4 +- .../test/fixtures/extends-chain.json | 8 +- .../test/golden/api-docs-accuracy.test.ts | 2 +- .../test/names-extends-chain.test.ts | 34 +-- .../packages/codegen-ts/test/names.test.ts | 12 +- .../test/projection/tph-scope.test.ts | 36 ++-- .../test/reference-byte-identical.test.ts | 4 +- .../relation-resolver-m2m-unpairable.test.ts | 2 +- .../codegen-ts/test/routes-expose.test.ts | 2 +- .../test/routes-hono-parity.test.ts | 2 +- .../test/routes-register-all.test.ts | 2 +- .../test/templates/tph-discriminator.test.ts | 30 +-- .../test/templates/tph-tier2-drizzle.test.ts | 12 +- .../test/templates/tph-tier2-queries.test.ts | 8 +- .../templates/tph-tier2-read-schema.test.ts | 10 +- .../test/templates/tph-tier2-routes.test.ts | 16 +- .../templates/tph-tier3-allowlists.test.ts | 8 +- .../test/tph-m2m-credential.test.ts | 6 +- .../codegen-ts/test/tph-m2m-routes.test.ts | 24 +-- .../cube-live/cube-model-shapes.live.ts | 2 +- ...contract-secret-fields-generated-server.ts | 10 +- .../src/api-contract-tph-generated-server.ts | 12 +- .../src/api-contract-tph-server.ts | 50 ++--- .../src/canonical-schema-mysql.ts | 2 +- .../test/api-contract-secret-fields.test.ts | 2 +- .../test/enum-intvaluemap-pg.test.ts | 22 +- .../test/fr014-tph-discriminator.test.ts | 12 +- .../test/expected-schema-tph.test.ts | 18 +- .../runtime-ts/src/drizzle-fastify/index.ts | 2 +- .../src/drizzle-fastify/mount-m2m.ts | 2 +- .../mount-tph-discriminator.test.ts | 10 +- .../test/object-manager-tph.test.ts | 32 +-- .../test-generators/src/generators/routes.ts | 2 +- 200 files changed, 1191 insertions(+), 1191 deletions(-) rename fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/{CopayAuth.create.schema.json => CouponAuth.create.schema.json} (72%) rename fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/{CopayAuth.schema.json => CouponAuth.schema.json} (81%) rename fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/{CopayAuth.strict.schema.json => CouponAuth.strict.schema.json} (90%) rename fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/{CopayAuth.update.schema.json => CouponAuth.update.schema.json} (68%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{CopayAuth.create.schema.json => CouponAuth.create.schema.json} (83%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{CopayAuth.schema.json => CouponAuth.schema.json} (85%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{CopayAuth.strict.schema.json => CouponAuth.strict.schema.json} (90%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{CopayAuth.update.schema.json => CouponAuth.update.schema.json} (80%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{PriorAuthAuth.create.schema.json => PermitAuth.create.schema.json} (79%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{PriorAuthAuth.schema.json => PermitAuth.schema.json} (88%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{PriorAuthAuth.strict.schema.json => PermitAuth.strict.schema.json} (94%) rename fixtures/contract-conformance/tph/expected/schemas/acme/auth/{PriorAuthAuth.update.schema.json => PermitAuth.update.schema.json} (75%) rename fixtures/cube-model/canonical/expected/model/cubes/{CopayAuth.yml => CouponAuth.yml} (83%) rename fixtures/cube-model/canonical/expected/model/cubes/{PriorAuthAuth.yml => PermitAuth.yml} (82%) rename server/csharp/MetaObjects.IntegrationTests/Generated/fitness/{CopayAuth.g.cs => CouponAuth.g.cs} (73%) rename server/csharp/MetaObjects.IntegrationTests/Generated/fitness/{CopayAuthNames.g.cs => CouponAuthNames.g.cs} (60%) rename server/csharp/MetaObjects.IntegrationTests/Generated/fitness/{PriorAuthAuth.g.cs => PermitAuth.g.cs} (82%) rename server/csharp/MetaObjects.IntegrationTests/Generated/fitness/{PriorAuthAuthNames.g.cs => PermitAuthNames.g.cs} (78%) rename server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/{CopayAuthValidation.kt => CouponAuthValidation.kt} (73%) rename server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/{PriorAuthAuthValidation.kt => PermitAuthValidation.kt} (73%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2473fd54a5..2c5d15e6fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1120,7 +1120,7 @@ vocabulary; upgrade every port together. was left for EF to discover as an entity (model validation failed with "requires a primary key"), and a timestamp, enum, decimal precision, array, map, duration or `@readOnly` column lost the mapping the same field gets on the root. Each concrete subtype now configures the - fields it adds, on its own builder. The integration corpus's `CopayAuth.copayAmount` gains its + fields it adds, on its own builder. The integration corpus's `CouponAuth.couponAmount` gains its `HasPrecision(10, 2)`. - **C#: under `EmitAbstractShapes`, a concrete entity extends its abstract shape and keeps the @@ -9188,8 +9188,8 @@ reintroduced one level up. On the persistence corpus's three-subtype TPH hierarc the C# output sheds 30 restated lines. The shape is per-language, the guarantee is not. **C# and Java** use real inheritance — -`class CopayAuthNames : AuthNames` / `extends AuthNames` — since both languages inherit -static members, so `CopayAuthNames.IdColumn` resolves through the base. **TypeScript** +`class CouponAuthNames : AuthNames` / `extends AuthNames` — since both languages inherit +static members, so `CouponAuthNames.IdColumn` resolves through the base. **TypeScript** spreads (`...AuthNames.fields`). **Kotlin and Python** have no static inheritance at all, so they re-export the parent's constants BY REFERENCE. diff --git a/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md b/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/agent-context/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/agent-context/skills/metaobjects-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md index bb96626b61..b2f0238de0 100644 --- a/agent-context/skills/metaobjects-codegen/references/csharp.md +++ b/agent-context/skills/metaobjects-codegen/references/csharp.md @@ -118,7 +118,7 @@ init properties say otherwise — documentation does (below). | `filter-allowlist` | `FilterAllowlistGenerator()` | per-entity `FilterAllowlist` (FR-009 — the server-side field+operator allowlist the routes validate against). | | `callable` | `CallableGenerator()` | `.callable.g.cs` — an FR-015 calling method for a `source.rdb @kind="storedProc"|"tableFunction"`, via EF `FromSqlInterpolated` (args from the `@parameterRef` value object in declaration order). | | `output-parser` / `extractor` / `output-prompt` / `render-helper` | `OutputParserGenerator()`, `ExtractorGenerator()`, `OutputPromptGenerator()`, `RenderHelperGenerator("prompts")` (its constructor argument is the template root its refs resolve from) | the prompt-pillar artifacts for a **responding `template.prompt`** — one carrying `@responseRef` (ADR-0052: these tiers are INBOUND; `template.output` is outbound only and emits no parser). The strict parser, the tolerant `extract`, the **output-format prompt fragment** (`output-prompt`; presentation via `@promptStyle: guide`/`inline`/`exampleOnly`), and the typed render helper. They reference the value objects' POCOs from `entity` and declare no payload type — wire `entity` too (`--list` says so). See the **prompts** reference. | -| `names` | `NamesGenerator()` | `Names.g.cs` — `public abstract class Names` of `const` physical database names, MIRRORING THE METADATA TREE: the object's own `Type`/`SubType`/`Name` (`Name` is the OBJECT's name, never a physical one), then per `source.rdb` keyed by `@role` — `SourcePrimaryType`/`SubType`/`Kind`, `SourcePrimarySchema` when declared, and the physical name under the alias for its `@kind` (`SourcePrimaryTable` / `SourceReplicaView` / `SourcePrimaryProc` / `…Function` / `…MaterializedView`) — then a `Field`/`Column` pair per field, then each identity and index (`IdentityPkName`, and `IdentityUqCustEmailIndex` / `IndexIxCustStatusIndex` — the DATABASE name, carried for `identity.secondary` and `index.lookup` only), then a complete `ColumnsByField`. There is no `ReadOnly`: it is a derivation over `@kind`, so ask `SourcePrimaryKind`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (its own identity + columns, and NO source members — it has no table). A class whose object extends another one **inherits** it (`class CopayAuthNames : AuthNames`) rather than restating its constants — a C# `const` is inherited, so `CopayAuthNames.IdColumn` and `CopayAuthNames.SourcePrimaryTable` resolve through the base (`Type`/`SubType`/`Name` are redeclared with `new`, since every artifact carries its own). `abstract`, not `static`, precisely so it can be inherited; it still cannot be instantiated. In the run, `entity` and `db-context` reference the constants (`[Table(OrderNames.SourcePrimaryTable)]`, `[Column(OrderNames.StatusColumn)]`, `.ToView(OrderNames.SourceReplicaView)`); a run without `names` falls back to literals. | +| `names` | `NamesGenerator()` | `Names.g.cs` — `public abstract class Names` of `const` physical database names, MIRRORING THE METADATA TREE: the object's own `Type`/`SubType`/`Name` (`Name` is the OBJECT's name, never a physical one), then per `source.rdb` keyed by `@role` — `SourcePrimaryType`/`SubType`/`Kind`, `SourcePrimarySchema` when declared, and the physical name under the alias for its `@kind` (`SourcePrimaryTable` / `SourceReplicaView` / `SourcePrimaryProc` / `…Function` / `…MaterializedView`) — then a `Field`/`Column` pair per field, then each identity and index (`IdentityPkName`, and `IdentityUqCustEmailIndex` / `IndexIxCustStatusIndex` — the DATABASE name, carried for `identity.secondary` and `index.lookup` only), then a complete `ColumnsByField`. There is no `ReadOnly`: it is a derivation over `@kind`, so ask `SourcePrimaryKind`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (its own identity + columns, and NO source members — it has no table). A class whose object extends another one **inherits** it (`class CouponAuthNames : AuthNames`) rather than restating its constants — a C# `const` is inherited, so `CouponAuthNames.IdColumn` and `CouponAuthNames.SourcePrimaryTable` resolve through the base (`Type`/`SubType`/`Name` are redeclared with `new`, since every artifact carries its own). `abstract`, not `static`, precisely so it can be inherited; it still cannot be instantiated. In the run, `entity` and `db-context` reference the constants (`[Table(OrderNames.SourcePrimaryTable)]`, `[Column(OrderNames.StatusColumn)]`, `.ToView(OrderNames.SourceReplicaView)`); a run without `names` falls back to literals. | | `template` | `TemplateGenerator.Create(name, template, walk, provider)` (a factory, not `new`) | the generic Mustache `templateGenerator()` primitive. | Metadata lives in the directory the gen run's positional `` argument diff --git a/agent-context/skills/metaobjects-codegen/references/java.md b/agent-context/skills/metaobjects-codegen/references/java.md index 74b7f45183..0b1d5763f3 100644 --- a/agent-context/skills/metaobjects-codegen/references/java.md +++ b/agent-context/skills/metaobjects-codegen/references/java.md @@ -216,7 +216,7 @@ separate `metaobjects-codegen-base` module instead.) | `SpringRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `LlmTraceHelperGenerator` | `TraceHelper.java` per concrete entity — the LLM-trace helper | | `SpringFilterAllowlistGenerator` | per-entity filter allowlist | -| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CopayAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CopayAuthNames.SOURCE_PRIMARY_TABLE` and `CopayAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | +| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CouponAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CouponAuthNames.SOURCE_PRIMARY_TABLE` and `CouponAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | | `JavaObjectCodeGenerator` | module `metaobjects-codegen-base` (`com.metaobjects.generator.direct.object.javacode`), a separate module from the Spring generators above. Flavor-selected via the `flavor` generator arg. `flavor=pojoAware` → `class extends PojoObject` (a concrete `MetaObjectAware` class with a `(MetaObject)` constructor) — its inherited `getMetaData()` back-reference is what breaks a default Jackson/Gson mapper, see "Serializing generated objects" below. `flavor=valueObject` → `class extends ValueObject` (map-backed; less hostile to a default mapper, but still not the sanctioned serialization path). Either concrete flavor also emits a self-registering `ObjectClassBindingProvider`; it writes no extractors. For a plain default-Jackson-friendly type, use the `codegen-spring` record surface instead — never `pojoAware`. | | `ExtractorCodeGenerator` | also in `metaobjects-codegen-base`. One `Extractor` per concrete object, and the only generator that writes them: list it or get none. Give it the same `outputDir`, `pkgPrefix` / `pkgSuffix` / `namePrefix` / `nameSuffix` and `` as the entity generator, which must run a concrete flavor in the same `` (an extractor for an object the entity generator wrote no class for does not compile). A pom with more than one entity generator entry needs one `ExtractorCodeGenerator` entry per entity entry, each with that entry's `outputDir`, naming args and ``. | diff --git a/agent-context/skills/metaobjects-codegen/references/physical-names.md b/agent-context/skills/metaobjects-codegen/references/physical-names.md index 8cb815149b..a14d2efd34 100644 --- a/agent-context/skills/metaobjects-codegen/references/physical-names.md +++ b/agent-context/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/docs/features/abstracts-and-inheritance.md b/docs/features/abstracts-and-inheritance.md index 38c5d8dff3..8397848e99 100644 --- a/docs/features/abstracts-and-inheritance.md +++ b/docs/features/abstracts-and-inheritance.md @@ -190,7 +190,7 @@ metadata: - field.long: { name: id } - field.enum: name: type - "@values": ["Bridge", "Copay", "PriorAuth"] + "@values": ["Bridge", "Coupon", "Permit"] - field.string: { name: reference, "@required": true } - identity.primary: { "@fields": id } @@ -202,16 +202,16 @@ metadata: - field.int: { name: quantity, "@required": true } - object.entity: - name: CopayAuth + name: CouponAuth extends: Auth - "@discriminatorValue": Copay + "@discriminatorValue": Coupon children: - - field.decimal: { name: copayAmount, "@precision": 10, "@scale": 2 } + - field.decimal: { name: couponAmount, "@precision": 10, "@scale": 2 } - object.entity: - name: PriorAuthAuth + name: PermitAuth extends: Auth - "@discriminatorValue": PriorAuth + "@discriminatorValue": Permit children: - field.string: { name: approver } ``` @@ -219,7 +219,7 @@ metadata: ### Single-table persistence Every subtype persists to the base's one table (`auths`). Subtype-only columns -(`quantity`, `copay_amount`, `approver`) are folded into that table **nullable** — +(`quantity`, `coupon_amount`, `approver`) are folded into that table **nullable** — a row of any other subtype stores `NULL` there, **even when the field is `@required`** on its subtype (a required rule can't hold across the shared table, so it is dropped on the folded column; an enum `CHECK` still passes because `NULL IN @@ -265,13 +265,13 @@ The generated polymorphic surface enforces a consistent subtype contract across every port: - **Per-subtype route segment** = the `@discriminatorValue` **lowercased**: - `/auths/bridge`, `/auths/copay`, `/auths/priorauth` (not the subtype entity + `/auths/bridge`, `/auths/coupon`, `/auths/permit` (not the subtype entity name). There is intentionally **no polymorphic `POST /auths`** — you can't create the abstract base. - **Create injects the discriminator** from the URL — `POST /auths/bridge` stamps `type = "Bridge"`; the request body omits it. - **Reads/updates/deletes are scoped to the subtype** — `GET|PATCH|DELETE - /auths/bridge/{id}` on a `Copay` row → **404** (a different-subtype row is + /auths/bridge/{id}` on a `Coupon` row → **404** (a different-subtype row is invisible to a subtype-scoped operation). - **M:N traversal is served inside the hierarchy** — a relationship declared on the base mounts at the base path (`GET /auths/{id}/tags`: every row of the diff --git a/docs/features/migrations/emit-attrs-to-generator-config.md b/docs/features/migrations/emit-attrs-to-generator-config.md index 64cf3dd4f1..056a6a48f9 100644 --- a/docs/features/migrations/emit-attrs-to-generator-config.md +++ b/docs/features/migrations/emit-attrs-to-generator-config.md @@ -72,7 +72,7 @@ Because a `filter` only narrows, it cannot express an opt-*in*. Per-subtype grid TPH subtypes therefore moved to a generator **option**: ```ts -const tphGrids = (e) => e.name === "Copay"; +const tphGrids = (e) => e.name === "Coupon"; export default defineConfig({ generators: [ diff --git a/docs/features/relationships.md b/docs/features/relationships.md index 04cecd4a21..d347aeabb5 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -416,7 +416,7 @@ level between the base and a subtype. Both cases are treated the same way: - field.long: { name: id } - field.enum: name: type - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] - field.long: { name: approverId } # FK to the approver - identity.reference: name: fkApprover diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index d7e15d34a2..75f262fe8b 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -623,15 +623,15 @@ can be inherited — and an object that extends another produces a class that ex other's: ```csharp -public abstract class CopayAuthNames : AuthNames +public abstract class CouponAuthNames : AuthNames { - public const string CopayAmountField = "copayAmount"; - public const string CopayAmountColumn = "copay_cents"; + public const string CouponAmountField = "couponAmount"; + public const string CouponAmountColumn = "coupon_cents"; public new const string Type = "object"; public new const string SubType = "entity"; - public new const string Name = "CopayAuth"; + public new const string Name = "CouponAuth"; // SourcePrimaryTable / IdColumn / … are the base's. A C# const is inherited, so - // CopayAuthNames.SourcePrimaryTable and CopayAuthNames.IdColumn both resolve. + // CouponAuthNames.SourcePrimaryTable and CouponAuthNames.IdColumn both resolve. } ``` diff --git a/docs/ports/java.md b/docs/ports/java.md index 7e867b0bc9..6cd09c5f77 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -634,15 +634,15 @@ implicit `super()` has to reach it), and an object that extends another produces a class that extends the other's: ```java -public abstract class CopayAuthNames extends AuthNames { +public abstract class CouponAuthNames extends AuthNames { public static final String TYPE = "object"; public static final String SUB_TYPE = "entity"; - public static final String NAME = "CopayAuth"; // its OWN name, not the base's + public static final String NAME = "CouponAuth"; // its OWN name, not the base's - public static final String COPAY_AMOUNT_FIELD = "copayAmount"; - public static final String COPAY_AMOUNT_COLUMN = "copay_cents"; + public static final String COUPON_AMOUNT_FIELD = "couponAmount"; + public static final String COUPON_AMOUNT_COLUMN = "coupon_cents"; // SOURCE_PRIMARY_* / ID_COLUMN / … are the base's. Java inherits static members, - // so CopayAuthNames.SOURCE_PRIMARY_TABLE and CopayAuthNames.ID_COLUMN both resolve. + // so CouponAuthNames.SOURCE_PRIMARY_TABLE and CouponAuthNames.ID_COLUMN both resolve. } ``` @@ -650,8 +650,8 @@ Which members a class declares is structural, and follows one rule: it declares what the object DECLARES, and inherits the rest. A TPH subtype sharing its base's single table declares no source of its own, so its whole `SOURCE_PRIMARY_*` block comes from the base. Its `TYPE`/`SUB_TYPE`/`NAME` are -always restated, because they differ — `CopayAuthNames.NAME` has to say -`"CopayAuth"`. An abstract base a persisted entity extends gets a class of its +always restated, because they differ — `CouponAuthNames.NAME` has to say +`"CouponAuth"`. An abstract base a persisted entity extends gets a class of its own carrying the columns and keys it declares and **no `SOURCE_*` block at all** — it has no table, and must never acquire one. `COLUMNS_BY_FIELD` stays complete on every class, inherited entries included. diff --git a/docs/ports/kotlin.md b/docs/ports/kotlin.md index 51ec356254..f1a1645ac3 100644 --- a/docs/ports/kotlin.md +++ b/docs/ports/kotlin.md @@ -755,9 +755,9 @@ Kotlin has no static inheritance — an `object` cannot extend another — so an object extends another re-exports the inherited constants by REFERENCE: ```kotlin -object CopayAuthNames { - const val NAME: String = "CopayAuth" // its OWN name, always restated - const val COPAY_AMOUNT_COLUMN: String = "copay_cents" +object CouponAuthNames { + const val NAME: String = "CouponAuth" // its OWN name, always restated + const val COUPON_AMOUNT_COLUMN: String = "coupon_cents" // A TPH subtype declares no source of its own, so the SHARED table — and every // inherited column — is re-exported by reference and spelled once, on the base. diff --git a/docs/ports/python.md b/docs/ports/python.md index 82ca3af781..35274b22e6 100644 --- a/docs/ports/python.md +++ b/docs/ports/python.md @@ -452,16 +452,16 @@ from its parent's.** Python has no static inheritance, so an artifact whose object extends another re-exports the inherited constants by REFERENCE: ```python -# generated/copay_auth_names.py (excerpt) +# generated/coupon_auth_names.py (excerpt) from .auth_names import ( AUTH_ID_COLUMN, AUTH_ID_FIELD, AUTH_IDENTITY_PK_NAME, AUTH_SOURCE_PRIMARY_KIND, AUTH_SOURCE_PRIMARY_TABLE, ) -COPAYAUTH_NAME: Final[str] = "CopayAuth" # its own name, always -COPAYAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE # SHARED, spelled once -COPAYAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN -COPAYAUTH_COPAY_AMOUNT_COLUMN: Final[str] = "copay_cents" +COUPONAUTH_NAME: Final[str] = "CouponAuth" # its own name, always +COUPONAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE # SHARED, spelled once +COUPONAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN +COUPONAUTH_COUPON_AMOUNT_COLUMN: Final[str] = "coupon_cents" ``` Two forms, and which one you get is structural. An object with its OWN source diff --git a/docs/ports/typescript-client.md b/docs/ports/typescript-client.md index 72dfbeffa5..76c4ffb776 100644 --- a/docs/ports/typescript-client.md +++ b/docs/ports/typescript-client.md @@ -596,7 +596,7 @@ are opt-**IN**. Opting in WIDENS, which a `filter` cannot express — it is a generator option instead, defaulting to `() => false`: ```ts -const perSubtypeGrid = (e: MetaObject) => e.name === "CopayAuth"; +const perSubtypeGrid = (e: MetaObject) => e.name === "CouponAuth"; tanstackGrid({ tphSubtypeGrids: perSubtypeGrid }), tanstackGridHook({ tphSubtypeGrids: perSubtypeGrid }), diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 6838843048..f466be7ec9 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -620,14 +620,14 @@ a log line, an external system's column mapping. object extends another spreads the parent's collections rather than restating them: ```ts -export const CopayAuthNames = { +export const CouponAuthNames = { type: "object", subType: "entity", - name: "CopayAuth", + name: "CouponAuth", sources: { ...AuthNames.sources }, // the SHARED table, named once on the base fields: { ...AuthNames.fields, - copayAmount: { name: "copayAmount", column: "copay_cents" }, + couponAmount: { name: "couponAmount", column: "coupon_cents" }, }, identities: { ...AuthNames.identities }, indexes: { ...AuthNames.indexes }, @@ -642,7 +642,7 @@ which is what a single-table hierarchy legitimately has two of. An abstract base a persisted entity extends gets an artifact of its own, carrying the columns it declares and an **empty `sources`** — it has no table, and must never acquire -one. Reading `CopayAuthNames.sources.primary.table` still works: the spread resolves it, +one. Reading `CouponAuthNames.sources.primary.table` still works: the spread resolves it, with the literal types intact. ## Use diff --git a/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md b/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md index 0390f55989..edbbc09871 100644 --- a/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md +++ b/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md @@ -202,15 +202,15 @@ After TS reference + REST decision, port the attr-registration + repo-emission p FR-014 covers the metamodel + ORM-layer emission. FR-017 covers everything else — the generator surfaces that surround a polymorphic entity. The next session writes FR-017 covering: -- **Discriminated TS union types.** `entityFile` emits `type Auth = BridgeAuth | CopayAuth | PriorAuthAuth | QuickStartAuth | UnknownAuth` as a tagged-union keyed by the discriminator field. -- **Per-subtype Zod schemas.** `entityFile` emits `BridgeAuthSchema`, `CopayAuthSchema`, etc., each `.merge(BaseAuthSchema)`. The TS reference + runtime `parse(json)` dispatch on the discriminator value. +- **Discriminated TS union types.** `entityFile` emits `type Auth = BridgeAuth | CouponAuth | PermitAuth | QuickStartAuth | UnknownAuth` as a tagged-union keyed by the discriminator field. +- **Per-subtype Zod schemas.** `entityFile` emits `BridgeAuthSchema`, `CouponAuthSchema`, etc., each `.merge(BaseAuthSchema)`. The TS reference + runtime `parse(json)` dispatch on the discriminator value. - **Polymorphic queries.** `queriesFile` always projects the discriminator column on `findAll/findById` for a discriminated base; row → subtype constructor dispatch. - **REST contract decisions** (and the design must MAKE these decisions, not punt): - `GET /auths` returns polymorphic rows tagged with the discriminator → `@type` field. - - `POST /auths` — choose: (a) removed in favor of per-subtype `POST /bridge-auths`, `POST /copay-auths`; (b) accepts a discriminated body with `type: "Bridge"` keying the validation branch. + - `POST /auths` — choose: (a) removed in favor of per-subtype `POST /bridge-auths`, `POST /coupon-auths`; (b) accepts a discriminated body with `type: "Bridge"` keying the validation branch. - **TanStack hooks.** `useAuths()` returns the union. Per-subtype hooks `useBridgeAuths()` filter on discriminator. Per-subtype mutations `useCreateBridgeAuth()`, etc. - **TanStack grid.** Decide: single polymorphic grid with mixed rows + a `@type` column, OR per-subtype grids? Specify. -- **React forms.** Per-subtype ``, `` etc. (you can't create an abstract `Auth`). +- **React forms.** Per-subtype ``, `` etc. (you can't create an abstract `Auth`). - **Filter allowlists.** Per-subtype filter allowlist auto-includes the discriminator field, pinned to that subtype's value. - **Spring (Java) generator stack.** `EntityGenerator` (JPA `@Inheritance`), `PayloadGenerator` (per-subtype request DTOs), `ControllerGenerator` (polymorphic GET + per-subtype POST), `RepositoryGenerator` (Spring Data repo on the base; per-subtype repos optional), filter-allowlist generator per subtype. - **Kotlin generator stack.** Sealed class hierarchy in `EntityGenerator`; per-subtype `ControllerGenerator`, `PayloadGenerator`, `FilterAllowlistGenerator`. diff --git a/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md b/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md index 3dd8fdabce..3802baf4f0 100644 --- a/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md +++ b/docs/superpowers/plans/2026-05-31-metamodel-batch-migrate-ts-plan.md @@ -22,7 +22,7 @@ > **What's already shipped (read first):** > - Design + status: [FR-017 spec](../specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md) → see the **Realization status** section (Tier-4 TS foundations + Tier-5 corpora). > - **The oracle (do not modify — make each port match it):** -> - api-contract: `fixtures/api-contract-conformance/tph/` (Auth base + BridgeAuth/CopayAuth/PriorAuthAuth, 4 scenarios, both lanes). +> - api-contract: `fixtures/api-contract-conformance/tph/` (Auth base + BridgeAuth/CouponAuth/PermitAuth, 4 scenarios, both lanes). > - persistence: `fixtures/persistence-conformance/queries/tph-*.yaml` (4 scenarios) + `Auth`/subtypes in `canonical/meta.fitness.json` + the committed `canonical/schema.postgres.sql` (single `auths` table). The query DSL gained `create`/`update` ops + an `expectError` flag — each port's persistence runner must implement these. > - **migrate-ts TPH single-table EMISSION (Task C.1 + C.2 below) is DONE** — `expected-schema.ts` now folds subtype-only columns (nullable) into the single base table and skips subtype tables; the canonical `schema.postgres.sql` is regenerated + drift-checked green. The verify-time **drift rules (C.3/C.4 — `WARN_DISCRIMINATOR_VALUE_UNKNOWN` etc.) remain open** in this plan. Schema is TS-owned per ADR-0015, so **no per-port schema work** — every port executes the committed `schema.postgres.sql`. > - **TS reference to mirror** (per the cross-language-porting skill — mirror, don't re-derive): `server/typescript/packages/codegen-ts/src/templates/{tph-discriminator,drizzle-schema,routes-file}.ts`, `runtime-ts/src/drizzle-fastify/index.ts` (the `discriminator: {column,value}` option), and `runtime-ts/src/{tph.ts,object-manager.ts}` (effective-children resolution + discriminator inject/scope/strip — the runtime-layer reference). @@ -32,7 +32,7 @@ > 2. **Runtime/data-access TPH** so the port passes the `tph-*` persistence scenarios (inherited fields/identity/single-table resolution + discriminator inject/scope/strip + the new `create`/`update`/`expectError` DSL ops in the port's persistence-conformance runner). NB: Java/Kotlin/Python persistence-conformance runs the **generated** controller + a consumer-supplied repo seam per the api-contract README — confirm how each port's query runner executes writes. > 3. **Conformance, both corpora:** make the port green against `api-contract-conformance/tph/` (reference lane + GENERATED artifact over HTTP) and `persistence-conformance/queries/tph-*.yaml`. Until a port's slice lands it **skips** `tph-*` (the m2n-* convention) — do not delete fixtures. > -> **Cross-port invariants (byte-identical):** single `auths` table, subtype cols nullable; `GET /auths` polymorphic union + `GET|POST|PATCH|DELETE /auths/{bridge|copay|priorauth}` per subtype (segment = `@discriminatorValue` lowercased); discriminator injected from the URL on create (never the body); cross-subtype get/delete → 404; response always carries the discriminator field by value. +> **Cross-port invariants (byte-identical):** single `auths` table, subtype cols nullable; `GET /auths` polymorphic union + `GET|POST|PATCH|DELETE /auths/{bridge|coupon|permit}` per subtype (segment = `@discriminatorValue` lowercased); discriminator injected from the URL on create (never the body); cross-subtype get/delete → 404; response always carries the discriminator field by value. > > Use `superpowers:subagent-driven-development` to fan the three ports out. Each is gated by the corpus (the oracle), TDD-first. @@ -173,7 +173,7 @@ Recognize a TPH root by: an `object.entity` carrying `@discriminator` + at least #### C.2 — Single `CREATE TABLE` for the base Emit one `CREATE TABLE` for the discriminated base. Include: - All base fields as columns (nullability per their own `@required`). -- All subtype-only fields as columns, **automatically nullable** (TPH rule — a row that's a `Bridge` won't have `Copay`'s columns populated). +- All subtype-only fields as columns, **automatically nullable** (TPH rule — a row that's a `Bridge` won't have `Coupon`'s columns populated). - The discriminator column with the right type derived from the named field's subtype: - `field.enum` → `varchar` with `CHECK` constraint enumerating all subtype values. - `field.int` → `integer`. diff --git a/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md b/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md index fce0cd804e..0559b83bf3 100644 --- a/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md +++ b/docs/superpowers/plans/2026-07-23-int-backed-enum-values-ts-persistence.md @@ -809,7 +809,7 @@ live): DDL applies + converges; the discriminator column is `integer` with an in CHECK; a generated per-subtype create stores both enums as integers (asserted with raw SQL, bypassing the codec); the per-subtype read schema decodes a raw-SQL-inserted integer row; the per-subtype filter compares the integer; the polymorphic read dispatches on the -decoded value; and find-by-id is discriminator-scoped (a Copay row asked for as a Bridge +decoded value; and find-by-id is discriminator-scoped (a Coupon row asked for as a Bridge must MISS). **Two things the run surfaced, both pre-existing and both identical for a string-backed diff --git a/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md b/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md index 77b75ea781..1dc4e2fa3b 100644 --- a/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md +++ b/docs/superpowers/plans/2026-07-23-tph-autoset-controller-stamping.md @@ -475,9 +475,9 @@ Edit `fixtures/api-contract-conformance/tph/seed.json` — add both columns set ```json "auths": [ - { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "copayAmount": null, "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 2, "type": "Copay", "reference": "REF-2", "quantity": null, "copayAmount": "12.50", "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 3, "type": "PriorAuth", "reference": "REF-3", "quantity": null, "copayAmount": null, "approver": "Dr. Smith","autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } + { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "couponAmount": null, "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 2, "type": "Coupon", "reference": "REF-2", "quantity": null, "couponAmount": "12.50", "approver": null, "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 3, "type": "Permit", "reference": "REF-3", "quantity": null, "couponAmount": null, "approver": "Dr. Smith","autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } ] ``` diff --git a/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md b/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md index e7be6c9e07..5d012a1da5 100644 --- a/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-014-tph-discriminator-design.md @@ -51,7 +51,7 @@ Add two logical attributes on `object.entity`: { "field.enum": { // the discriminator field itself "name": "type", "@column": "Type", // physical column name lives here, not on source.rdb - "@values": ["Unknown", "Bridge", "Copay", "PriorAuth", "QuickStart"] + "@values": ["Unknown", "Bridge", "Coupon", "Permit", "QuickStart"] }}, { "field.string": { "name": "number" } }, { "identity.primary": { "@fields": "id" } } @@ -69,11 +69,11 @@ Add two logical attributes on `object.entity`: }} { "object.entity": { - "name": "CopayAuthorization", + "name": "CouponAuthorization", "extends": "Authorization", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 18, "@scale": 2 } } + { "field.decimal": { "name": "couponAmount", "@precision": 18, "@scale": 2 } } ] }} ``` @@ -133,7 +133,7 @@ Multi-level hierarchies (`Base → Mid → Leaf`) are supported. `@discriminator | Port | Emission | |---|---| -| **TypeScript** | Discriminated union type: `type Auth = Bridge \| Copay \| ...`; per-subtype Zod schemas via `.merge(BaseSchema)`; Drizzle: one `pgTable` for the base + per-subtype TypeScript narrowing. | +| **TypeScript** | Discriminated union type: `type Auth = Bridge \| Coupon \| ...`; per-subtype Zod schemas via `.merge(BaseSchema)`; Drizzle: one `pgTable` for the base + per-subtype TypeScript narrowing. | | **Java** | `@Inheritance(strategy = InheritanceType.SINGLE_TABLE)` + `@DiscriminatorColumn(name="...")` on the base + `@DiscriminatorValue("...")` on each subtype. Spring repo methods on the base; per-subtype query methods optional. | | **Kotlin** | Sealed class hierarchy with KotlinPoet: `sealed class Auth` + per-subtype `data class` with `@DiscriminatorValue`-equivalent. Exposed: single-table query with subtype dispatch. | | **C#** | EF Core: `modelBuilder.Entity().HasDiscriminator(x => x.Type).HasValue(AuthType.Bridge)...`; subtype POCOs inherit from base; `OfType()` polymorphic queries. | @@ -146,7 +146,7 @@ Each port also emits polymorphic query helpers (e.g., `.OfType()` in C#, Per [ADR-0015](../../../spec/decisions/ADR-0015-single-shared-migrate-engine.md), schema migration is TS-only. The TS reference work: - **TPH detection.** `migrate-ts/src/expected-schema.ts` recognizes a TPH root by: an `object.entity` carrying `@discriminator` + the presence of one or more entities `extends:`-ing it with `@discriminatorValue`. -- **DDL emission.** A single `CREATE TABLE` for the base. Every subtype's own fields become columns on the base table, **automatically nullable** if any subtype omits them (the TPH nullability rule — a row that's a `Bridge` won't have `Copay`'s columns populated). +- **DDL emission.** A single `CREATE TABLE` for the base. Every subtype's own fields become columns on the base table, **automatically nullable** if any subtype omits them (the TPH nullability rule — a row that's a `Bridge` won't have `Coupon`'s columns populated). - **Discriminator-column type derivation.** The discriminator column's type follows from the named field's subtype (`field.enum` → `varchar` with CHECK; `field.int` → `integer`; `field.string` → `varchar`). - **Introspection round-trip.** Reading the live DB recovers the column set but **not** the discriminator semantic (which column IS the discriminator). Drift detection compares the metadata-declared expected column set against the actual columns; the discriminator-column identity itself is metadata-declared, not introspected. diff --git a/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md b/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md index b27525955b..ab9193012a 100644 --- a/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md +++ b/docs/superpowers/specs/2026-06-02-fr-017-tph-polymorphic-codegen-design.md @@ -53,10 +53,10 @@ For an entity that carries `@discriminator`, `entityFile` emits one TS union typ ```ts // Generated from object.entity "Auth" with @discriminator: "type" -// and subtypes BridgeAuth / CopayAuth / PriorAuthAuth declaring values -// "Bridge" / "Copay" / "PriorAuth". +// and subtypes BridgeAuth / CouponAuth / PermitAuth declaring values +// "Bridge" / "Coupon" / "Permit". -export type Auth = BridgeAuth | CopayAuth | PriorAuthAuth; +export type Auth = BridgeAuth | CouponAuth | PermitAuth; // Type guard helpers — one per subtype. export function isBridgeAuth(a: Auth): a is BridgeAuth { @@ -77,7 +77,7 @@ For each concrete subtype, `entityFile` emits a Zod schema that is the base enti // Base Zod schema (already emitted today for any entity). export const AuthSchema = z.object({ id: z.number().int(), - type: z.enum(["Bridge", "Copay", "PriorAuth"]), + type: z.enum(["Bridge", "Coupon", "Permit"]), }); // Per-subtype schemas — each merges the base, pins the discriminator value, @@ -88,14 +88,14 @@ export const BridgeAuthSchema = AuthSchema.merge(z.object({ })); export type BridgeAuth = z.infer; -export const CopayAuthSchema = AuthSchema.merge(z.object({ - type: z.literal("Copay"), - copayAmount: z.number(), +export const CouponAuthSchema = AuthSchema.merge(z.object({ + type: z.literal("Coupon"), + couponAmount: z.number(), })); -export type CopayAuth = z.infer; +export type CouponAuth = z.infer; ``` -**Discriminator pin via `z.literal`.** Each subtype schema pins its `type` field to the literal value. So `BridgeAuthSchema.parse({type: "Copay", ...})` throws — typed gatekeeping is enforced by Zod, not just TypeScript. +**Discriminator pin via `z.literal`.** Each subtype schema pins its `type` field to the literal value. So `BridgeAuthSchema.parse({type: "Coupon", ...})` throws — typed gatekeeping is enforced by Zod, not just TypeScript. ### Discriminator dispatch @@ -105,11 +105,11 @@ export type CopayAuth = z.infer; /** Parse a row from the auths table, dispatching by the discriminator value. */ export function parseAuth(row: unknown): Auth { // Read the discriminator without committing the row to any subtype yet. - const head = z.object({ type: z.enum(["Bridge", "Copay", "PriorAuth"]) }).parse(row); + const head = z.object({ type: z.enum(["Bridge", "Coupon", "Permit"]) }).parse(row); switch (head.type) { case "Bridge": return BridgeAuthSchema.parse(row); - case "Copay": return CopayAuthSchema.parse(row); - case "PriorAuth": return PriorAuthAuthSchema.parse(row); + case "Coupon": return CouponAuthSchema.parse(row); + case "Permit": return PermitAuthSchema.parse(row); } } ``` @@ -128,7 +128,7 @@ Concrete shape of `entityFile` output: |---|---| | `Auth.ts` (base) | `AuthSchema` (full union of fields across all subtypes), `Auth` type alias to the discriminated union, type guards, `parseAuth` dispatcher. | | `BridgeAuth.ts` (subtype) | `BridgeAuthSchema` (base merged + own), `BridgeAuth` type, no separate type guard file. | -| `CopayAuth.ts` (subtype) | same as above. | +| `CouponAuth.ts` (subtype) | same as above. | The subtype files each `import { AuthSchema } from "./Auth.js"` — base must be emitted first / locatable. @@ -151,10 +151,10 @@ export const auths = pgTable("auths", { // BridgeAuth-only columns: nullable, since rows of any other subtype have NULL here. quantity: integer("quantity"), - // CopayAuth-only columns: nullable. - copay_amount: numeric("copay_amount", { precision: 10, scale: 2 }), + // CouponAuth-only columns: nullable. + coupon_amount: numeric("coupon_amount", { precision: 10, scale: 2 }), - // PriorAuthAuth-only columns: nullable. + // PermitAuth-only columns: nullable. // ... }); ``` @@ -224,7 +224,7 @@ export async function updateBridgeAuth( } ``` -The discriminator field is **never updatable** — clients can't change a Bridge into a Copay. Generated `updateXxx` strips the discriminator field from any patch. +The discriminator field is **never updatable** — clients can't change a Bridge into a Coupon. Generated `updateXxx` strips the discriminator field from any patch. ### REST contract (TS routes) @@ -342,7 +342,7 @@ New fixtures pinning the polymorphic CRUD shape cross-port: - `tph-polymorphic-list-and-get` — `GET /auths` returns subtype-tagged rows; `GET /auths/:id` returns one row. - `tph-per-subtype-list-and-create` — `GET /auths/bridge` filtered; `POST /auths/bridge` create. - `tph-per-subtype-update-and-delete` — subtype-only mutations. -- `tph-cross-subtype-404` — `GET /auths/bridge/123` for an id that exists but is a Copay returns 404. +- `tph-cross-subtype-404` — `GET /auths/bridge/123` for an id that exists but is a Coupon returns 404. Each fixture asserts request shape (URL + body) and response shape (status + body) cross-port byte-equivalently. @@ -353,7 +353,7 @@ New TPH query scenarios: - `tph-insert-then-find-by-id` — insert a `BridgeAuth`, find by id; the result's subtype-only columns are NULL on other-subtype reads. - `tph-insert-three-subtypes-list` — insert one of each subtype; `findAllAuths()` returns three rows tagged by `@type`. - `tph-update-subtype-only-column` — update a Bridge's `quantity`; verify storage. -- `tph-no-cross-subtype-update` — attempt to update a Bridge with Copay-only fields; verify they're stripped / rejected. +- `tph-no-cross-subtype-update` — attempt to update a Bridge with Coupon-only fields; verify they're stripped / rejected. ## Open questions @@ -421,7 +421,7 @@ New TPH query scenarios: - codegen-ts + codegen-ts-tanstack + codegen-ts-react suites: 652/0. - **Tier 5 (conformance corpora):** **authored + TS-green** (both corpora). - **api-contract** `fixtures/api-contract-conformance/tph/` — Auth base + - BridgeAuth/CopayAuth/PriorAuthAuth over one `auths` table; 4 scenarios + BridgeAuth/CouponAuth/PermitAuth over one `auths` table; 4 scenarios (polymorphic list/get, per-subtype list/create, per-subtype update/delete, cross-subtype 404). TS runs **both lanes** (hand-rolled reference + GENERATED `Auth.routes.ts`) over one Testcontainers Postgres per scenario per diff --git a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md index f2375610bc..7f0b3400f7 100644 --- a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md +++ b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md @@ -198,8 +198,8 @@ csharp: # The 12 @provided enums that live in DataEnums sub-namespaces "acme::authorizations::AuthorizationType": "Acme.Domain.DataEnums.Authorizations" "acme::authorizations::AuthorizationStatus": "Acme.Domain.DataEnums.Authorizations" - "acme::authorizations::CopayCardStatus": "Acme.Domain.DataEnums.CopayCards" - # ... 6 more Copay* enums in acme::authorizations + "acme::authorizations::CouponCardStatus": "Acme.Domain.DataEnums.CouponCards" + # ... 6 more Coupon* enums in acme::authorizations "acme::integrations::DataExportRunStatusEnum": "Acme.Domain.DataEnums.DataExportIntegration" "acme::integrations::SPFileType": "Acme.Domain.DataEnums.SPIntegration" "acme::integrations::SPProcessLogStatus": "Acme.Domain.DataEnums.SPIntegration" diff --git a/examples/advanced-modeling/codegen/generators/routes.ts b/examples/advanced-modeling/codegen/generators/routes.ts index a1c2cf0197..2f10b888e2 100644 --- a/examples/advanced-modeling/codegen/generators/routes.ts +++ b/examples/advanced-modeling/codegen/generators/routes.ts @@ -659,7 +659,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts index 78baf3f97a..8785538f7e 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/index.ts @@ -328,7 +328,7 @@ export function mountUpdateRoute(opts: VerbOptions): void { } const discCond = discriminatorCond(opts); // FR-017 TPH: a row's subtype is immutable — strip the discriminator from - // the patch so a client can't flip a Bridge into a Copay. + // the patch so a client can't flip a Bridge into a Coupon. let data = parsed.data as Record; if (opts.discriminator) { const { [opts.discriminator.column]: _omit, ...rest } = data; diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts index b975e61b63..ffb804776e 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -105,7 +105,7 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { } // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Copay's id}/linkedAuths` return that Copay's relations, because + // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because // the junction FK cannot tell the subtypes apart: it points at the shared base table. const srcDisc = opts.sourceDiscriminator; if (srcDisc !== undefined) { diff --git a/examples/showcase/codegen/generators/routes.ts b/examples/showcase/codegen/generators/routes.ts index a1c2cf0197..2f10b888e2 100644 --- a/examples/showcase/codegen/generators/routes.ts +++ b/examples/showcase/codegen/generators/routes.ts @@ -659,7 +659,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/index.ts b/examples/showcase/codegen/runtime/drizzle-fastify/index.ts index 78baf3f97a..8785538f7e 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/index.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/index.ts @@ -328,7 +328,7 @@ export function mountUpdateRoute(opts: VerbOptions): void { } const discCond = discriminatorCond(opts); // FR-017 TPH: a row's subtype is immutable — strip the discriminator from - // the patch so a client can't flip a Bridge into a Copay. + // the patch so a client can't flip a Bridge into a Coupon. let data = parsed.data as Record; if (opts.discriminator) { const { [opts.discriminator.column]: _omit, ...rest } = data; diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts index b975e61b63..ffb804776e 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -105,7 +105,7 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { } // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Copay's id}/linkedAuths` return that Copay's relations, because + // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because // the junction FK cannot tell the subtypes apart: it points at the shared base table. const srcDisc = opts.sourceDiscriminator; if (srcDisc !== undefined) { diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md index 74b7f45183..0b1d5763f3 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/java.md @@ -216,7 +216,7 @@ separate `metaobjects-codegen-base` module instead.) | `SpringRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `LlmTraceHelperGenerator` | `TraceHelper.java` per concrete entity — the LLM-trace helper | | `SpringFilterAllowlistGenerator` | per-entity filter allowlist | -| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CopayAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CopayAuthNames.SOURCE_PRIMARY_TABLE` and `CopayAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | +| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CouponAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CouponAuthNames.SOURCE_PRIMARY_TABLE` and `CouponAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | | `JavaObjectCodeGenerator` | module `metaobjects-codegen-base` (`com.metaobjects.generator.direct.object.javacode`), a separate module from the Spring generators above. Flavor-selected via the `flavor` generator arg. `flavor=pojoAware` → `class extends PojoObject` (a concrete `MetaObjectAware` class with a `(MetaObject)` constructor) — its inherited `getMetaData()` back-reference is what breaks a default Jackson/Gson mapper, see "Serializing generated objects" below. `flavor=valueObject` → `class extends ValueObject` (map-backed; less hostile to a default mapper, but still not the sanctioned serialization path). Either concrete flavor also emits a self-registering `ObjectClassBindingProvider`; it writes no extractors. For a plain default-Jackson-friendly type, use the `codegen-spring` record surface instead — never `pojoAware`. | | `ExtractorCodeGenerator` | also in `metaobjects-codegen-base`. One `Extractor` per concrete object, and the only generator that writes them: list it or get none. Give it the same `outputDir`, `pkgPrefix` / `pkgSuffix` / `namePrefix` / `nameSuffix` and `` as the entity generator, which must run a concrete flavor in the same `` (an extractor for an object the entity generator wrote no class for does not compile). A pom with more than one entity generator entry needs one `ExtractorCodeGenerator` entry per entity entry, each with that entry's `outputDir`, naming args and ``. | diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 8cb815149b..a14d2efd34 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md index 74b7f45183..0b1d5763f3 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/java.md @@ -216,7 +216,7 @@ separate `metaobjects-codegen-base` module instead.) | `SpringRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `LlmTraceHelperGenerator` | `TraceHelper.java` per concrete entity — the LLM-trace helper | | `SpringFilterAllowlistGenerator` | per-entity filter allowlist | -| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CopayAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CopayAuthNames.SOURCE_PRIMARY_TABLE` and `CopayAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | +| `SpringNamesGenerator` | `Names.java` — `public abstract class` of `static final String` names that MIRRORS THE METADATA TREE. Every node carries its own `TYPE`/`SUB_TYPE`/`NAME`, so `AuthorNames.NAME` is the OBJECT's name (`"Author"`), **not** a table name, and a physical name sits under the member that says what it is: `SOURCE__TABLE` / `_VIEW` / `_MATERIALIZED_VIEW` / `_PROC` / `_FUNCTION`, from the metamodel's own `@kind`-to-alias map, with `` being `PRIMARY` or `REPLICA` (a write-through entity has a member for each). Plus a `_FIELD`/`_COLUMN` pair per field and a complete `COLUMNS_BY_FIELD`; an `identity.secondary` or `index.lookup` also carries `IDENTITY__INDEX` / `INDEX__INDEX`, while `identity.primary` deliberately carries no index member (migrate names a PK by a dialect-conditional formula this artifact must not restate). **There is no `READ_ONLY`** — it was a derivation over `@kind`, never metadata, so ask `SOURCE__KIND`. Emitted for every object with a declared or inherited primary source, PLUS a fragment for any abstract base such an object extends (columns only, no source). A class whose object extends another one **extends** it (`class CouponAuthNames extends AuthNames`) rather than restating its constants — Java inherits static members, so `CouponAuthNames.SOURCE_PRIMARY_TABLE` and `CouponAuthNames.ID_COLUMN` both resolve through the base. **This port generates no SQL** (the repository is an interface you implement), so nothing generated consumes these — they exist for your implementation. | | `JavaObjectCodeGenerator` | module `metaobjects-codegen-base` (`com.metaobjects.generator.direct.object.javacode`), a separate module from the Spring generators above. Flavor-selected via the `flavor` generator arg. `flavor=pojoAware` → `class extends PojoObject` (a concrete `MetaObjectAware` class with a `(MetaObject)` constructor) — its inherited `getMetaData()` back-reference is what breaks a default Jackson/Gson mapper, see "Serializing generated objects" below. `flavor=valueObject` → `class extends ValueObject` (map-backed; less hostile to a default mapper, but still not the sanctioned serialization path). Either concrete flavor also emits a self-registering `ObjectClassBindingProvider`; it writes no extractors. For a plain default-Jackson-friendly type, use the `codegen-spring` record surface instead — never `pojoAware`. | | `ExtractorCodeGenerator` | also in `metaobjects-codegen-base`. One `Extractor` per concrete object, and the only generator that writes them: list it or get none. Give it the same `outputDir`, `pkgPrefix` / `pkgSuffix` / `namePrefix` / `nameSuffix` and `` as the entity generator, which must run a concrete flavor in the same `` (an extractor for an object the entity generator wrote no class for does not compile). A pom with more than one entity generator entry needs one `ExtractorCodeGenerator` entry per entity entry, each with that entry's `outputDir`, naming args and ``. | diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 8cb815149b..a14d2efd34 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 8cb815149b..a14d2efd34 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 8cb815149b..a14d2efd34 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md index 4c9a2fcf1d..9ef1b6273c 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-authoring/references/inheritance-tph.md @@ -27,7 +27,7 @@ mapping). children: - source.rdb: { table: auths } - field.long: { name: id } - - field.enum: { name: type, values: ["Bridge", "Copay"] } + - field.enum: { name: type, values: ["Bridge", "Coupon"] } - identity.primary: { fields: id } - object.entity: diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md index 8cb815149b..a14d2efd34 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/physical-names.md @@ -75,7 +75,7 @@ constants instead of embedding the physical names a second time — so wiring it generated output, and that diff is the point. **It follows `extends`.** An object that extends another does not restate what it -inherits: C# and Java use real class inheritance (`class CopayAuthNames extends +inherits: C# and Java use real class inheritance (`class CouponAuthNames extends AuthNames`), TypeScript spreads (`...AuthNames.fields`), and Kotlin and Python re-export the parent's constants by reference. An abstract base a persisted object extends gets an artifact of its own — columns only, no table name, because it has none. So if you are diff --git a/fixtures/api-contract-conformance/tph/README.md b/fixtures/api-contract-conformance/tph/README.md index 5c45a2231f..bafe0bc5ea 100644 --- a/fixtures/api-contract-conformance/tph/README.md +++ b/fixtures/api-contract-conformance/tph/README.md @@ -17,14 +17,14 @@ DELETE {prefix}/auths//:id → per-subtype delete (404 cross-subtype) ``` The per-subtype URL segment is the **`@discriminatorValue` lowercased** — -`"Bridge"` → `/auths/bridge`, `"PriorAuth"` → `/auths/priorauth` — NOT the subtype +`"Bridge"` → `/auths/bridge`, `"Permit"` → `/auths/permit` — NOT the subtype entity name. There is intentionally **no polymorphic `POST /auths`** (you can't create an abstract base). ## The three cross-port invariants (must hold byte-identically) 1. **Single-table TPH storage.** One physical `auths` table; every subtype-only - column (`quantity` / `copay_amount` / `approver`) is **nullable** (a row of any + column (`quantity` / `coupon_amount` / `approver`) is **nullable** (a row of any other subtype stores NULL there), even when the field is `@required`. 2. **Polymorphic GET / per-subtype POST URLs.** `GET /auths` returns the union; `POST /auths/bridge` etc. create per subtype. The URL paths are identical @@ -37,7 +37,7 @@ create an abstract base). ``` tph/ ├── README.md # this file -├── meta.json # Auth (base, @discriminator "type") + BridgeAuth / CopayAuth / PriorAuthAuth +├── meta.json # Auth (base, @discriminator "type") + BridgeAuth / CouponAuth / PermitAuth ├── seed.json # 3 seed rows (one per subtype) into the single `auths` table └── scenarios/ ├── tph-polymorphic-list-and-get.yaml # polymorphic GET: the /auths union + get-by-id of any subtype @@ -56,10 +56,10 @@ tph/ | Entity | Discriminator | Own fields (a subtype inherits everything on `Auth`) | |---|---|---| -| `Auth` (base) | `@discriminator: "type"`, `@table "auths"` | `id` (long, pk), `type` (enum `Bridge`/`Copay`/`PriorAuth`), `reference` (string, `@required`, `@maxLength` 80), `issuedCurrency` (string, `@maxLength` 3, `@mutability` "writeOnce"), `autoCreatedAt` / `autoUpdatedAt` (timestamp, `@autoSet` onCreate / onUpdate) | +| `Auth` (base) | `@discriminator: "type"`, `@table "auths"` | `id` (long, pk), `type` (enum `Bridge`/`Coupon`/`Permit`), `reference` (string, `@required`, `@maxLength` 80), `issuedCurrency` (string, `@maxLength` 3, `@mutability` "writeOnce"), `autoCreatedAt` / `autoUpdatedAt` (timestamp, `@autoSet` onCreate / onUpdate) | | `BridgeAuth` | `@discriminatorValue: "Bridge"` | `quantity` (int, required → nullable in the single table) | -| `CopayAuth` | `@discriminatorValue: "Copay"` | `copayAmount` (decimal 10,2) | -| `PriorAuthAuth` | `@discriminatorValue: "PriorAuth"` | `approver` (string, `@maxLength` 80) | +| `CouponAuth` | `@discriminatorValue: "Coupon"` | `couponAmount` (decimal 10,2) | +| `PermitAuth` | `@discriminatorValue: "Permit"` | `approver` (string, `@maxLength` 80) | `seed.json` is applied fresh before every scenario (truncate-then-insert into the single `auths` table). Subtype-only columns are `null` for rows of other subtypes. @@ -71,7 +71,7 @@ Identical to the parent `api-contract-conformance` corpus `ids` / `length` / `row` (subset key-match) / `error` / `empty` / `fieldsNotEqual` cover TPH (the last pins the `@autoSet` leg: `autoCreatedAt` preserved vs `autoUpdatedAt` bumped). -A subtype's decimal is asserted over the wire as the canonical string (`copayAmount` `"12.50"` +A subtype's decimal is asserted over the wire as the canonical string (`couponAmount` `"12.50"` is `"12.5"`, ADR-0019 Amendment 1), filters exactly on its subtype segment, and refuses a value with more digits than its `@scale` with `400 validation`. The `row` assertions pin the discriminator value (`type`) and the integer/string subtype-only columns. diff --git a/fixtures/api-contract-conformance/tph/meta.json b/fixtures/api-contract-conformance/tph/meta.json index 99ac47a3ca..20bfe1e7c3 100644 --- a/fixtures/api-contract-conformance/tph/meta.json +++ b/fixtures/api-contract-conformance/tph/meta.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true } }, { "field.string": { "name": "issuedCurrency", "@maxLength": 3, "@mutability": "writeOnce" } }, { "field.timestamp": { "name": "autoCreatedAt", "@autoSet": "onCreate" } }, @@ -25,17 +25,17 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ] }}, { "object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "Auth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80, "@filterable": true, "@sortable": true } } ] diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml index 8e6c8bd563..d2c971bfce 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-base-filter-by-discriminator.yaml @@ -3,7 +3,7 @@ description: > FR-017: the polymorphic base collection filters by its own discriminator. The base allowlist includes the discriminator field (`type` is `@filterable`), so `GET /auths?filter[type][eq]=Bridge` narrows the union to - one subtype and `filter[type][in]=Bridge,Copay` to two — the query a list + one subtype and `filter[type][in]=Bridge,Coupon` to two — the query a list page with a "kind" facet sends on its first render. The JVM generators removed the discriminator from the base allowlist, so both @@ -28,7 +28,7 @@ requests: - id: r2 method: GET - path: /api/auths?filter[type][in]=Bridge,Copay&sort=id:asc + path: /api/auths?filter[type][in]=Bridge,Coupon&sort=id:asc expect: status: 200 body: @@ -38,7 +38,7 @@ requests: # Bare-value sugar for `eq`. - id: r3 method: GET - path: /api/auths?filter[type]=PriorAuth + path: /api/auths?filter[type]=Permit expect: status: 200 body: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml index 8c22016417..2c14be9b16 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-create-constraint-violation.yaml @@ -13,22 +13,22 @@ description: > discriminator is injected from the URL, never the body). A well-formed create still succeeds (201) — the guard rejects only violations, never valid bodies. requests: - # r1 — a valid PriorAuth create still succeeds (positive control: the constraint + # r1 — a valid Permit create still succeeds (positive control: the constraint # guard must not over-reject a well-formed body). - id: r1 method: POST - path: /api/auths/priorauth + path: /api/auths/permit body: reference: "REF-OK" approver: "Dr. Smith" expect: status: 201 body: - row: { type: "PriorAuth", reference: "REF-OK", approver: "Dr. Smith" } - # r2 — an over-@maxLength(80) `reference` on the PriorAuth segment → 400 validation. + row: { type: "Permit", reference: "REF-OK", approver: "Dr. Smith" } + # r2 — an over-@maxLength(80) `reference` on the Permit segment → 400 validation. - id: r2 method: POST - path: /api/auths/priorauth + path: /api/auths/permit body: reference: "RXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" approver: "Dr. Smith" diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml index f3aced914a..8e50b7de6f 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-cross-subtype-404.yaml @@ -12,21 +12,21 @@ requests: status: 404 - id: r2 method: GET - path: /api/auths/copay/1 + path: /api/auths/coupon/1 expect: status: 404 - id: r3 method: DELETE - path: /api/auths/copay/1 + path: /api/auths/coupon/1 expect: status: 404 - id: r4 method: GET - path: /api/auths/copay/2 + path: /api/auths/coupon/2 expect: status: 200 body: - row: { id: 2, type: "Copay", reference: "REF-2" } + row: { id: 2, type: "Coupon", reference: "REF-2" } - id: r5 method: GET path: /api/auths?sort=id:asc diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml index 9a18b245c6..706ba8f523 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-per-subtype-list-and-create.yaml @@ -5,7 +5,7 @@ description: > subtype; POST creates a row of that subtype — the discriminator is injected by the route handler from the URL, NEVER taken from the body (the body omits it). The created row joins the polymorphic collection. A subtype's decimal - (`CopayAuth.copayAmount`, decimal 10,2) is the canonical string on the wire, filters + (`CouponAuth.couponAmount`, decimal 10,2) is the canonical string on the wire, filters exactly on its own segment, and refuses more digits than its declared scale (ADR-0019 Amendment 1). requests: @@ -49,34 +49,34 @@ requests: length: 4 - id: r6 method: POST - path: /api/auths/copay + path: /api/auths/coupon body: - reference: "REF-COPAY" - copayAmount: "8.10" + reference: "REF-COUPON" + couponAmount: "8.10" expect: status: 201 body: - row: { type: "Copay", reference: "REF-COPAY", copayAmount: "8.1" } + row: { type: "Coupon", reference: "REF-COUPON", couponAmount: "8.1" } - id: r7 method: GET - path: /api/auths/copay?filter[copayAmount][gt]=10&sort=id:asc + path: /api/auths/coupon?filter[couponAmount][gt]=10&sort=id:asc expect: status: 200 body: ids: [2] - id: r8 method: GET - path: /api/auths/copay?filter[copayAmount][eq]=8.1 + path: /api/auths/coupon?filter[couponAmount][eq]=8.1 expect: status: 200 body: length: 1 - id: r9 method: POST - path: /api/auths/copay + path: /api/auths/coupon body: - reference: "REF-COPAY-2" - copayAmount: "1.234" + reference: "REF-COUPON-2" + couponAmount: "1.234" expect: status: 400 body: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml index 1e7453b654..72958f7648 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-polymorphic-list-and-get.yaml @@ -25,14 +25,14 @@ requests: expect: status: 200 body: - row: { id: 2, type: "Copay", reference: "REF-2", copayAmount: "12.5" } + row: { id: 2, type: "Coupon", reference: "REF-2", couponAmount: "12.5" } - id: r4 method: GET path: /api/auths/3 expect: status: 200 body: - row: { id: 3, type: "PriorAuth", reference: "REF-3", approver: "Dr. Smith" } + row: { id: 3, type: "Permit", reference: "REF-3", approver: "Dr. Smith" } - id: r5 method: GET path: /api/auths/999 diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml index 7f29926635..2fa3bd9ebf 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-update-constraint-violation.yaml @@ -12,16 +12,16 @@ description: > This gates only PRESENT-VALUE constraints — the FR-035 null semantics (present-null clears / present-null-on-@required → 400 / omitted → untouched) are gated separately - by tph-update-explicit-null-clears. Uses the PriorAuth subtype (id=3): `reference` is + by tph-update-explicit-null-clears. Uses the Permit subtype (id=3): `reference` is the @required @maxLength:80 BASE column shared by every subtype; `approver` is the - @maxLength:80 PriorAuth-only column (folded nullable into the union, hence unannotated + @maxLength:80 Permit-only column (folded nullable into the union, hence unannotated there). A well-formed PATCH still succeeds (200) — the guard rejects only violations. requests: # r1 — positive control: a valid present value on the constrained base `reference` # column still succeeds (the guard must not over-reject a well-formed body). - id: r1 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: "REF-UPDATED" expect: @@ -29,25 +29,25 @@ requests: body: row: id: 3 - type: "PriorAuth" + type: "Permit" reference: "REF-UPDATED" # r2 — an over-@maxLength(80) present value on the @required base `reference` → 400 # validation. The annotation-free union would silently accept it; the subtype's # annotated shape rejects it. - id: r2 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: "RXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" expect: status: 400 body: error: "validation" - # r3 — an over-@maxLength(80) present value on the PriorAuth-only `approver` column → + # r3 — an over-@maxLength(80) present value on the Permit-only `approver` column → # 400 validation (the subtype-own constraint is enforced, not just the base's). - id: r3 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: approver: "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" expect: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml index 459d107d0d..42458658ea 100644 --- a/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-update-explicit-null-clears.yaml @@ -13,7 +13,7 @@ description: > - a cleared column is settable again → 200 - present null on a @required base column → 400 {error:"validation"} - Uses the PriorAuth subtype (id=3): the nullable `approver` is cleared and reset, + Uses the Permit subtype (id=3): the nullable `approver` is cleared and reset, while the @required base `reference` (REF-3) and the discriminator `type` are OMITTED and must survive untouched. Runs on all five ports, BOTH lanes. @@ -22,7 +22,7 @@ requests: # `type` are OMITTED from the patch and must survive (must NOT 400). - id: r1 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: approver: null expect: @@ -30,13 +30,13 @@ requests: body: row: id: 3 - type: "PriorAuth" + type: "Permit" reference: "REF-3" # omitted from the PATCH → untouched (still the seed) approver: null # explicit null → column cleared # r2 — the clear PERSISTED: re-read from the DB, not the mutation's echo. - id: r2 method: GET - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 expect: status: 200 body: @@ -47,7 +47,7 @@ requests: # r3 — the cleared column is settable again. - id: r3 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: approver: "Dr. Jones" expect: @@ -60,7 +60,7 @@ requests: # cross-port validation envelope. - id: r4 method: PATCH - path: /api/auths/priorauth/3 + path: /api/auths/permit/3 body: reference: null expect: diff --git a/fixtures/api-contract-conformance/tph/seed.json b/fixtures/api-contract-conformance/tph/seed.json index 8cfe72e2cb..adf9bdc412 100644 --- a/fixtures/api-contract-conformance/tph/seed.json +++ b/fixtures/api-contract-conformance/tph/seed.json @@ -1,7 +1,7 @@ { "auths": [ - { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "copayAmount": null, "approver": null, "issuedCurrency": "USD", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 2, "type": "Copay", "reference": "REF-2", "quantity": null, "copayAmount": "12.50", "approver": null, "issuedCurrency": "GBP", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, - { "id": 3, "type": "PriorAuth", "reference": "REF-3", "quantity": null, "copayAmount": null, "approver": "Dr. Smith", "issuedCurrency": "EUR", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } + { "id": 1, "type": "Bridge", "reference": "REF-1", "quantity": 5, "couponAmount": null, "approver": null, "issuedCurrency": "USD", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 2, "type": "Coupon", "reference": "REF-2", "quantity": null, "couponAmount": "12.50", "approver": null, "issuedCurrency": "GBP", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" }, + { "id": 3, "type": "Permit", "reference": "REF-3", "quantity": null, "couponAmount": null, "approver": "Dr. Smith", "issuedCurrency": "EUR", "autoCreatedAt": "2000-01-01T00:00:00", "autoUpdatedAt": "2000-01-01T00:00:00" } ] } diff --git a/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json b/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json index 93a29fd765..0a2d464a88 100644 --- a/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json +++ b/fixtures/conformance/error-tph-discriminator-value-duplicate/input/meta.demo.json @@ -11,7 +11,7 @@ { "field.enum": { "name": "type", - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, diff --git a/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json b/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json index 65b4f1ed03..cf87e2a870 100644 --- a/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json +++ b/fixtures/conformance/error-tph-discriminator-value-type-mismatch/input/meta.demo.json @@ -11,7 +11,7 @@ { "field.enum": { "name": "type", - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, diff --git a/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json b/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json index e09204e4c1..775c7d6206 100644 --- a/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json +++ b/fixtures/conformance/tph-discriminator-enum-with-subtypes/expected.json @@ -17,7 +17,7 @@ "name": "type", "@values": [ "Bridge", - "Copay" + "Coupon" ] } }, @@ -53,13 +53,13 @@ }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "demo::Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ { "field.decimal": { - "name": "copayAmount", + "name": "couponAmount", "@precision": 10, "@scale": 2 } diff --git a/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json b/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json index d1b9e53352..349eceffcf 100644 --- a/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json +++ b/fixtures/conformance/tph-discriminator-enum-with-subtypes/input/meta.demo.json @@ -11,7 +11,7 @@ { "field.enum": { "name": "type", - "@values": ["Bridge", "Copay"] + "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, @@ -31,11 +31,11 @@ }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "demo::Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } } diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json index f11226954f..0c7c63df7b 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/openapi.json @@ -414,11 +414,11 @@ } } }, - "/api/auths/copay": { + "/api/auths/coupon": { "get": { - "operationId": "listCopayAuth", + "operationId": "listCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "parameters": [ { @@ -457,10 +457,10 @@ "schema": { "oneOf": [ { - "$ref": "#/components/schemas/CopayAuthList" + "$ref": "#/components/schemas/CouponAuthList" }, { - "$ref": "#/components/schemas/CopayAuthPage" + "$ref": "#/components/schemas/CouponAuthPage" } ] } @@ -480,16 +480,16 @@ } }, "post": { - "operationId": "createCopayAuth", + "operationId": "createCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthCreate" + "$ref": "#/components/schemas/CouponAuthCreate" } } } @@ -500,7 +500,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -528,7 +528,7 @@ } } }, - "/api/auths/copay/{id}": { + "/api/auths/coupon/{id}": { "parameters": [ { "name": "id", @@ -541,9 +541,9 @@ } ], "get": { - "operationId": "getCopayAuth", + "operationId": "getCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "200": { @@ -551,7 +551,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -569,16 +569,16 @@ } }, "patch": { - "operationId": "updateCopayAuth", + "operationId": "updateCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -589,7 +589,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -627,16 +627,16 @@ } }, "put": { - "operationId": "putCopayAuth", + "operationId": "putCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -647,7 +647,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -685,9 +685,9 @@ } }, "delete": { - "operationId": "deleteCopayAuth", + "operationId": "deleteCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "204": { @@ -746,14 +746,14 @@ "$ref": "#/components/schemas/BridgeAuth" }, { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } ], "discriminator": { "propertyName": "type", "mapping": { "Bridge": "#/components/schemas/BridgeAuth", - "Copay": "#/components/schemas/CopayAuth" + "Coupon": "#/components/schemas/CouponAuth" } } }, @@ -864,8 +864,8 @@ } } }, - "CopayAuth": { - "title": "CopayAuth", + "CouponAuth": { + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -873,7 +873,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", @@ -894,8 +894,8 @@ "auditRef" ] }, - "CopayAuthCreate": { - "title": "CopayAuthCreate", + "CouponAuthCreate": { + "title": "CouponAuthCreate", "type": "object", "properties": { "reference": { @@ -908,15 +908,15 @@ "reference" ] }, - "CopayAuthList": { - "title": "CopayAuthList", + "CouponAuthList": { + "title": "CouponAuthList", "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, - "CopayAuthPage": { - "title": "CopayAuthPage", + "CouponAuthPage": { + "title": "CouponAuthPage", "type": "object", "required": [ "rows", @@ -926,7 +926,7 @@ "rows": { "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, "total": { @@ -934,8 +934,8 @@ } } }, - "CopayAuthUpdate": { - "title": "CopayAuthUpdate", + "CouponAuthUpdate": { + "title": "CouponAuthUpdate", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json index 8b67c7624b..a3a91c6820 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/Auth.schema.json @@ -7,7 +7,7 @@ "$ref": "./BridgeAuth.schema.json" }, { - "$ref": "./CopayAuth.schema.json" + "$ref": "./CouponAuth.schema.json" } ] } diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.create.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.create.schema.json similarity index 72% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.create.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.create.schema.json index 664615d88d..c59f3bdf54 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.create.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.create.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.create.schema.json", - "title": "CopayAuth.create", + "$id": "schemas/acme/auth/CouponAuth.create.schema.json", + "title": "CouponAuth.create", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.schema.json similarity index 81% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.schema.json index c302a0d48b..9891bb8dab 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.schema.json", - "title": "CopayAuth", + "$id": "schemas/acme/auth/CouponAuth.schema.json", + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -9,7 +9,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.strict.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.strict.schema.json similarity index 90% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.strict.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.strict.schema.json index 80c1ee1b79..2bfdc5fa2d 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.strict.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.strict.schema.json @@ -1,5 +1,5 @@ { - "title": "CopayAuth", + "title": "CouponAuth", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.update.schema.json b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.update.schema.json similarity index 68% rename from fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.update.schema.json rename to fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.update.schema.json index 48d05089b8..6e7dfaee91 100644 --- a/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CopayAuth.update.schema.json +++ b/fixtures/contract-conformance/tph-shared-marks/expected/schemas/acme/auth/CouponAuth.update.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.update.schema.json", - "title": "CopayAuth.update", + "$id": "schemas/acme/auth/CouponAuth.update.schema.json", + "title": "CouponAuth.update", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph-shared-marks/meta.json b/fixtures/contract-conformance/tph-shared-marks/meta.json index c3cff88705..a9157a87db 100644 --- a/fixtures/contract-conformance/tph-shared-marks/meta.json +++ b/fixtures/contract-conformance/tph-shared-marks/meta.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] @@ -23,9 +23,9 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ { "field.string": { "name": "token", "@maxLength": 100 } }, { "field.string": { "name": "auditRef", "@maxLength": 100 } } diff --git a/fixtures/contract-conformance/tph/expected/openapi.json b/fixtures/contract-conformance/tph/expected/openapi.json index 439dc9defb..f3f7c876ce 100644 --- a/fixtures/contract-conformance/tph/expected/openapi.json +++ b/fixtures/contract-conformance/tph/expected/openapi.json @@ -92,8 +92,8 @@ "type": "string", "enum": [ "Bridge", - "Copay", - "PriorAuth" + "Coupon", + "Permit" ] } }, @@ -104,8 +104,8 @@ "type": "string", "enum": [ "Bridge", - "Copay", - "PriorAuth" + "Coupon", + "Permit" ] } }, @@ -116,8 +116,8 @@ "type": "string", "enum": [ "Bridge", - "Copay", - "PriorAuth" + "Coupon", + "Permit" ] } }, @@ -813,11 +813,11 @@ } } }, - "/api/auths/copay": { + "/api/auths/coupon": { "get": { - "operationId": "listCopayAuth", + "operationId": "listCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "parameters": [ { @@ -937,7 +937,7 @@ } }, { - "name": "filter[copayAmount]", + "name": "filter[couponAmount]", "in": "query", "description": "Sugar for the eq operator.", "schema": { @@ -946,7 +946,7 @@ } }, { - "name": "filter[copayAmount][eq]", + "name": "filter[couponAmount][eq]", "in": "query", "schema": { "type": "string", @@ -954,7 +954,7 @@ } }, { - "name": "filter[copayAmount][ne]", + "name": "filter[couponAmount][ne]", "in": "query", "schema": { "type": "string", @@ -962,7 +962,7 @@ } }, { - "name": "filter[copayAmount][gt]", + "name": "filter[couponAmount][gt]", "in": "query", "schema": { "type": "string", @@ -970,7 +970,7 @@ } }, { - "name": "filter[copayAmount][gte]", + "name": "filter[couponAmount][gte]", "in": "query", "schema": { "type": "string", @@ -978,7 +978,7 @@ } }, { - "name": "filter[copayAmount][lt]", + "name": "filter[couponAmount][lt]", "in": "query", "schema": { "type": "string", @@ -986,7 +986,7 @@ } }, { - "name": "filter[copayAmount][lte]", + "name": "filter[couponAmount][lte]", "in": "query", "schema": { "type": "string", @@ -994,7 +994,7 @@ } }, { - "name": "filter[copayAmount][in]", + "name": "filter[couponAmount][in]", "in": "query", "schema": { "type": "string", @@ -1002,7 +1002,7 @@ } }, { - "name": "filter[copayAmount][isNull]", + "name": "filter[couponAmount][isNull]", "in": "query", "schema": { "type": "boolean" @@ -1020,9 +1020,9 @@ "reference", "reference:asc", "reference:desc", - "copayAmount", - "copayAmount:asc", - "copayAmount:desc" + "couponAmount", + "couponAmount:asc", + "couponAmount:desc" ] } }, @@ -1062,10 +1062,10 @@ "schema": { "oneOf": [ { - "$ref": "#/components/schemas/CopayAuthList" + "$ref": "#/components/schemas/CouponAuthList" }, { - "$ref": "#/components/schemas/CopayAuthPage" + "$ref": "#/components/schemas/CouponAuthPage" } ] } @@ -1085,16 +1085,16 @@ } }, "post": { - "operationId": "createCopayAuth", + "operationId": "createCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthCreate" + "$ref": "#/components/schemas/CouponAuthCreate" } } } @@ -1105,7 +1105,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1133,7 +1133,7 @@ } } }, - "/api/auths/copay/{id}": { + "/api/auths/coupon/{id}": { "parameters": [ { "name": "id", @@ -1146,9 +1146,9 @@ } ], "get": { - "operationId": "getCopayAuth", + "operationId": "getCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "200": { @@ -1156,7 +1156,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1174,16 +1174,16 @@ } }, "patch": { - "operationId": "updateCopayAuth", + "operationId": "updateCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -1194,7 +1194,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1232,16 +1232,16 @@ } }, "put": { - "operationId": "putCopayAuth", + "operationId": "putCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuthUpdate" + "$ref": "#/components/schemas/CouponAuthUpdate" } } } @@ -1252,7 +1252,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } } } @@ -1290,9 +1290,9 @@ } }, "delete": { - "operationId": "deleteCopayAuth", + "operationId": "deleteCouponAuth", "tags": [ - "CopayAuth" + "CouponAuth" ], "responses": { "204": { @@ -1321,11 +1321,11 @@ } } }, - "/api/auths/priorauth": { + "/api/auths/permit": { "get": { - "operationId": "listPriorAuthAuth", + "operationId": "listPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "parameters": [ { @@ -1542,10 +1542,10 @@ "schema": { "oneOf": [ { - "$ref": "#/components/schemas/PriorAuthAuthList" + "$ref": "#/components/schemas/PermitAuthList" }, { - "$ref": "#/components/schemas/PriorAuthAuthPage" + "$ref": "#/components/schemas/PermitAuthPage" } ] } @@ -1565,16 +1565,16 @@ } }, "post": { - "operationId": "createPriorAuthAuth", + "operationId": "createPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuthCreate" + "$ref": "#/components/schemas/PermitAuthCreate" } } } @@ -1585,7 +1585,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1613,7 +1613,7 @@ } } }, - "/api/auths/priorauth/{id}": { + "/api/auths/permit/{id}": { "parameters": [ { "name": "id", @@ -1626,9 +1626,9 @@ } ], "get": { - "operationId": "getPriorAuthAuth", + "operationId": "getPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "responses": { "200": { @@ -1636,7 +1636,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1654,16 +1654,16 @@ } }, "patch": { - "operationId": "updatePriorAuthAuth", + "operationId": "updatePermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuthUpdate" + "$ref": "#/components/schemas/PermitAuthUpdate" } } } @@ -1674,7 +1674,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1712,16 +1712,16 @@ } }, "put": { - "operationId": "putPriorAuthAuth", + "operationId": "putPermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuthUpdate" + "$ref": "#/components/schemas/PermitAuthUpdate" } } } @@ -1732,7 +1732,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } } } @@ -1770,9 +1770,9 @@ } }, "delete": { - "operationId": "deletePriorAuthAuth", + "operationId": "deletePermitAuth", "tags": [ - "PriorAuthAuth" + "PermitAuth" ], "responses": { "204": { @@ -1831,18 +1831,18 @@ "$ref": "#/components/schemas/BridgeAuth" }, { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" }, { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } ], "discriminator": { "propertyName": "type", "mapping": { "Bridge": "#/components/schemas/BridgeAuth", - "Copay": "#/components/schemas/CopayAuth", - "PriorAuth": "#/components/schemas/PriorAuthAuth" + "Coupon": "#/components/schemas/CouponAuth", + "Permit": "#/components/schemas/PermitAuth" } } }, @@ -1987,8 +1987,8 @@ } } }, - "CopayAuth": { - "title": "CopayAuth", + "CouponAuth": { + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -1996,7 +1996,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", @@ -2023,7 +2023,7 @@ ], "format": "date-time" }, - "copayAmount": { + "couponAmount": { "type": [ "string", "null" @@ -2038,11 +2038,11 @@ "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", - "copayAmount" + "couponAmount" ] }, - "CopayAuthCreate": { - "title": "CopayAuthCreate", + "CouponAuthCreate": { + "title": "CouponAuthCreate", "type": "object", "properties": { "reference": { @@ -2054,7 +2054,7 @@ "type": "string", "maxLength": 3 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number" @@ -2067,15 +2067,15 @@ "reference" ] }, - "CopayAuthList": { - "title": "CopayAuthList", + "CouponAuthList": { + "title": "CouponAuthList", "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, - "CopayAuthPage": { - "title": "CopayAuthPage", + "CouponAuthPage": { + "title": "CouponAuthPage", "type": "object", "required": [ "rows", @@ -2085,7 +2085,7 @@ "rows": { "type": "array", "items": { - "$ref": "#/components/schemas/CopayAuth" + "$ref": "#/components/schemas/CouponAuth" } }, "total": { @@ -2093,8 +2093,8 @@ } } }, - "CopayAuthUpdate": { - "title": "CopayAuthUpdate", + "CouponAuthUpdate": { + "title": "CouponAuthUpdate", "type": "object", "properties": { "reference": { @@ -2102,7 +2102,7 @@ "minLength": 1, "maxLength": 80 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number", @@ -2113,8 +2113,8 @@ } } }, - "PriorAuthAuth": { - "title": "PriorAuthAuth", + "PermitAuth": { + "title": "PermitAuth", "type": "object", "properties": { "id": { @@ -2122,7 +2122,7 @@ "format": "int64" }, "type": { - "const": "PriorAuth" + "const": "Permit" }, "reference": { "type": "string", @@ -2167,8 +2167,8 @@ "approver" ] }, - "PriorAuthAuthCreate": { - "title": "PriorAuthAuthCreate", + "PermitAuthCreate": { + "title": "PermitAuthCreate", "type": "object", "properties": { "reference": { @@ -2189,15 +2189,15 @@ "reference" ] }, - "PriorAuthAuthList": { - "title": "PriorAuthAuthList", + "PermitAuthList": { + "title": "PermitAuthList", "type": "array", "items": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } }, - "PriorAuthAuthPage": { - "title": "PriorAuthAuthPage", + "PermitAuthPage": { + "title": "PermitAuthPage", "type": "object", "required": [ "rows", @@ -2207,7 +2207,7 @@ "rows": { "type": "array", "items": { - "$ref": "#/components/schemas/PriorAuthAuth" + "$ref": "#/components/schemas/PermitAuth" } }, "total": { @@ -2215,8 +2215,8 @@ } } }, - "PriorAuthAuthUpdate": { - "title": "PriorAuthAuthUpdate", + "PermitAuthUpdate": { + "title": "PermitAuthUpdate", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json index 2ee81ea91e..ed89793bee 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/Auth.schema.json @@ -7,10 +7,10 @@ "$ref": "./BridgeAuth.schema.json" }, { - "$ref": "./CopayAuth.schema.json" + "$ref": "./CouponAuth.schema.json" }, { - "$ref": "./PriorAuthAuth.schema.json" + "$ref": "./PermitAuth.schema.json" } ] } diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.create.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.create.schema.json similarity index 83% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.create.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.create.schema.json index d669f9f28a..29c223ae05 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.create.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.create.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.create.schema.json", - "title": "CopayAuth.create", + "$id": "schemas/acme/auth/CouponAuth.create.schema.json", + "title": "CouponAuth.create", "type": "object", "properties": { "reference": { @@ -13,7 +13,7 @@ "type": "string", "maxLength": 3 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number" diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.schema.json similarity index 85% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.schema.json index a71e5f76bb..a4db653cc0 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.schema.json", - "title": "CopayAuth", + "$id": "schemas/acme/auth/CouponAuth.schema.json", + "title": "CouponAuth", "type": "object", "properties": { "id": { @@ -9,7 +9,7 @@ "format": "int64" }, "type": { - "const": "Copay" + "const": "Coupon" }, "reference": { "type": "string", @@ -36,7 +36,7 @@ ], "format": "date-time" }, - "copayAmount": { + "couponAmount": { "type": [ "string", "null" @@ -51,6 +51,6 @@ "issuedCurrency", "autoCreatedAt", "autoUpdatedAt", - "copayAmount" + "couponAmount" ] } diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.strict.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.strict.schema.json similarity index 90% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.strict.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.strict.schema.json index 8aeeb3445b..45ce869ffd 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.strict.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.strict.schema.json @@ -1,5 +1,5 @@ { - "title": "CopayAuth", + "title": "CouponAuth", "type": "object", "properties": { "reference": { @@ -13,7 +13,7 @@ "null" ] }, - "copayAmount": { + "couponAmount": { "description": "A decimal, as a string in JSON-number grammar or a JSON number. Precision 10, scale 2. Pattern: ^-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?$.", "type": [ "string", @@ -24,7 +24,7 @@ "required": [ "reference", "issuedCurrency", - "copayAmount" + "couponAmount" ], "additionalProperties": false } diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.update.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.update.schema.json similarity index 80% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.update.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.update.schema.json index 30d0ed1ddb..c45baa45df 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CopayAuth.update.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/CouponAuth.update.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/CopayAuth.update.schema.json", - "title": "CopayAuth.update", + "$id": "schemas/acme/auth/CouponAuth.update.schema.json", + "title": "CouponAuth.update", "type": "object", "properties": { "reference": { @@ -9,7 +9,7 @@ "minLength": 1, "maxLength": 80 }, - "copayAmount": { + "couponAmount": { "type": [ "string", "number", diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.create.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.create.schema.json similarity index 79% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.create.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.create.schema.json index c33766e807..98a7e41b78 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.create.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.create.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/PriorAuthAuth.create.schema.json", - "title": "PriorAuthAuth.create", + "$id": "schemas/acme/auth/PermitAuth.create.schema.json", + "title": "PermitAuth.create", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.schema.json similarity index 88% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.schema.json index d53d846f5d..f5dbff3c1e 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/PriorAuthAuth.schema.json", - "title": "PriorAuthAuth", + "$id": "schemas/acme/auth/PermitAuth.schema.json", + "title": "PermitAuth", "type": "object", "properties": { "id": { @@ -9,7 +9,7 @@ "format": "int64" }, "type": { - "const": "PriorAuth" + "const": "Permit" }, "reference": { "type": "string", diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.strict.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.strict.schema.json similarity index 94% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.strict.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.strict.schema.json index 96db0afeba..a37f33972c 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.strict.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.strict.schema.json @@ -1,5 +1,5 @@ { - "title": "PriorAuthAuth", + "title": "PermitAuth", "type": "object", "properties": { "reference": { diff --git a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.update.schema.json b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.update.schema.json similarity index 75% rename from fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.update.schema.json rename to fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.update.schema.json index 81d8db395c..3790b1b9eb 100644 --- a/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PriorAuthAuth.update.schema.json +++ b/fixtures/contract-conformance/tph/expected/schemas/acme/auth/PermitAuth.update.schema.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "schemas/acme/auth/PriorAuthAuth.update.schema.json", - "title": "PriorAuthAuth.update", + "$id": "schemas/acme/auth/PermitAuth.update.schema.json", + "title": "PermitAuth.update", "type": "object", "properties": { "reference": { diff --git a/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml b/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml index f049a5524a..9e036b2355 100644 --- a/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml +++ b/fixtures/cube-model/canonical/expected/model/cubes/Auth.yml @@ -19,7 +19,7 @@ cubes: type: count_distinct segments: - name: authsByKindScope - sql: '{CUBE}."type" <> ''PriorAuth''' + sql: '{CUBE}."type" <> ''Permit''' pre_aggregations: - name: AuthsByKind type: rollup diff --git a/fixtures/cube-model/canonical/expected/model/cubes/CopayAuth.yml b/fixtures/cube-model/canonical/expected/model/cubes/CouponAuth.yml similarity index 83% rename from fixtures/cube-model/canonical/expected/model/cubes/CopayAuth.yml rename to fixtures/cube-model/canonical/expected/model/cubes/CouponAuth.yml index 6ca62bd76e..fecda9a4e6 100644 --- a/fixtures/cube-model/canonical/expected/model/cubes/CopayAuth.yml +++ b/fixtures/cube-model/canonical/expected/model/cubes/CouponAuth.yml @@ -1,7 +1,7 @@ # @generated by @metaobjectsdev/codegen-ts — cube-model cubes: - - name: CopayAuth - sql: 'SELECT * FROM "auths" WHERE "type" = ''Copay''' + - name: CouponAuth + sql: 'SELECT * FROM "auths" WHERE "type" = ''Coupon''' dimensions: - name: id sql: '{CUBE}."id"' diff --git a/fixtures/cube-model/canonical/expected/model/cubes/PriorAuthAuth.yml b/fixtures/cube-model/canonical/expected/model/cubes/PermitAuth.yml similarity index 82% rename from fixtures/cube-model/canonical/expected/model/cubes/PriorAuthAuth.yml rename to fixtures/cube-model/canonical/expected/model/cubes/PermitAuth.yml index 057b00c807..f01b88f74d 100644 --- a/fixtures/cube-model/canonical/expected/model/cubes/PriorAuthAuth.yml +++ b/fixtures/cube-model/canonical/expected/model/cubes/PermitAuth.yml @@ -1,7 +1,7 @@ # @generated by @metaobjectsdev/codegen-ts — cube-model cubes: - - name: PriorAuthAuth - sql: 'SELECT * FROM "auths" WHERE "type" = ''PriorAuth''' + - name: PermitAuth + sql: 'SELECT * FROM "auths" WHERE "type" = ''Permit''' dimensions: - name: id sql: '{CUBE}."id"' diff --git a/fixtures/cube-model/canonical/seed.mysql.sql b/fixtures/cube-model/canonical/seed.mysql.sql index 8bf766218b..56d6c8e852 100644 --- a/fixtures/cube-model/canonical/seed.mysql.sql +++ b/fixtures/cube-model/canonical/seed.mysql.sql @@ -46,8 +46,8 @@ INSERT INTO `nodes` (`id`,`label`,`parentId`) VALUES INSERT INTO `auths` (`id`,`type`,`reference`,`quantity`,`urgency`) VALUES (1, 'Bridge', 'A-1', 2, NULL), (2, 'Bridge', 'A-1', 3, NULL), - (3, 'Copay', 'C-1', NULL, NULL), - (4, 'PriorAuth', 'P-1', NULL, NULL), + (3, 'Coupon', 'C-1', NULL, NULL), + (4, 'Permit', 'P-1', NULL, NULL), (5, 'Referral', 'R-1', NULL, 'routine'), (6, 'Referral', 'R-2', NULL, 'urgent'), (7, NULL, 'N-1', NULL, NULL); diff --git a/fixtures/cube-model/canonical/seed.sql b/fixtures/cube-model/canonical/seed.sql index 12bd66842d..1f60e3b4df 100644 --- a/fixtures/cube-model/canonical/seed.sql +++ b/fixtures/cube-model/canonical/seed.sql @@ -54,8 +54,8 @@ INSERT INTO "nodes" ("id","label","parentId") VALUES INSERT INTO "auths" ("id","type","reference","quantity","urgency") VALUES (1, 'Bridge', 'A-1', 2, NULL), (2, 'Bridge', 'A-1', 3, NULL), - (3, 'Copay', 'C-1', NULL, NULL), - (4, 'PriorAuth', 'P-1', NULL, NULL), + (3, 'Coupon', 'C-1', NULL, NULL), + (4, 'Permit', 'P-1', NULL, NULL), (5, 'Referral', 'R-1', NULL, 'routine'), (6, 'Referral', 'R-2', NULL, 'urgent'), (7, NULL, 'N-1', NULL, NULL); diff --git a/fixtures/cube-model/entity-tph-subtype/meta.json b/fixtures/cube-model/entity-tph-subtype/meta.json index 75982300e4..514dee2877 100644 --- a/fixtures/cube-model/entity-tph-subtype/meta.json +++ b/fixtures/cube-model/entity-tph-subtype/meta.json @@ -22,7 +22,7 @@ "name": "type", "@values": [ "Bridge", - "Copay" + "Coupon" ] } }, @@ -53,9 +53,9 @@ }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [] } } diff --git a/fixtures/persistence-conformance/README.md b/fixtures/persistence-conformance/README.md index 10ad3dfb69..05ffaa8621 100644 --- a/fixtures/persistence-conformance/README.md +++ b/fixtures/persistence-conformance/README.md @@ -280,7 +280,7 @@ PK → update every subtype → read back → delete → get-returns-null). #### TPH (table-per-hierarchy) scenarios The `tph-*.yaml` scenarios exercise single-table inheritance through the runtime -(`Auth` base + `BridgeAuth` / `CopayAuth` / `PriorAuthAuth` subtypes over the one +(`Auth` base + `BridgeAuth` / `CouponAuth` / `PermitAuth` subtypes over the one `auths` table). They require the port's **runtime TPH support** (resolving a subtype's inherited fields/identity/table via `extends`, plus discriminator inject/scope/strip). **All five ports run the `tph-*` scenarios green** — TypeScript diff --git a/fixtures/persistence-conformance/canonical/meta.fitness.json b/fixtures/persistence-conformance/canonical/meta.fitness.json index 1def091d29..1f03c0aebe 100644 --- a/fixtures/persistence-conformance/canonical/meta.fitness.json +++ b/fixtures/persistence-conformance/canonical/meta.fitness.json @@ -256,7 +256,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth", "Referral"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit", "Referral"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, { "dimension.attribute": { "name": "kind", "@of": "Auth.type" } }, @@ -273,17 +273,17 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] }}, { "object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "Auth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80 } } ] @@ -468,7 +468,7 @@ "@dimensions": ["parentLabel"], "@measures": ["nodes"], "children": [ { "source.rdb": { "@kind": "view", "@view": "v_nodes_by_parent" } } ] } }, { "object.report": { "name": "AuthsByKind", "@from": "Auth", - "@dimensions": ["kind"], "@measures": ["auths", "distinctRefs"], "@filter": { "type": { "ne": "PriorAuth" } }, + "@dimensions": ["kind"], "@measures": ["auths", "distinctRefs"], "@filter": { "type": { "ne": "Permit" } }, "children": [ { "source.rdb": { "@kind": "view", "@view": "v_auths_by_kind" } } ] } }, { "object.entity": { diff --git a/fixtures/persistence-conformance/canonical/schema.mysql.sql b/fixtures/persistence-conformance/canonical/schema.mysql.sql index b0126bc272..bbcc0626e7 100644 --- a/fixtures/persistence-conformance/canonical/schema.mysql.sql +++ b/fixtures/persistence-conformance/canonical/schema.mysql.sql @@ -59,7 +59,7 @@ CREATE TABLE `auths` ( `type` VARCHAR(16), `reference` VARCHAR(80) NOT NULL, `quantity` INT, - `copayAmount` DECIMAL(10,2), + `couponAmount` DECIMAL(10,2), `approver` VARCHAR(80), `urgency` VARCHAR(16) ); @@ -346,7 +346,7 @@ CREATE VIEW `v_auths_by_kind` AS COUNT(a.`id`) AS `auths`, COUNT(DISTINCT a.`reference`) AS `distinctRefs` FROM `auths` a - WHERE a.`type` <> 'PriorAuth' + WHERE a.`type` <> 'Permit' GROUP BY a.`type`; CREATE VIEW `v_gadget_events_by_label` AS diff --git a/fixtures/persistence-conformance/canonical/schema.postgres.sql b/fixtures/persistence-conformance/canonical/schema.postgres.sql index b49f5163ea..405005596a 100644 --- a/fixtures/persistence-conformance/canonical/schema.postgres.sql +++ b/fixtures/persistence-conformance/canonical/schema.postgres.sql @@ -99,11 +99,11 @@ CREATE TABLE "auths" ( "type" TEXT, "reference" VARCHAR(80) NOT NULL, "quantity" INTEGER, - "copayAmount" NUMERIC(10,2), + "couponAmount" NUMERIC(10,2), "approver" VARCHAR(80), "urgency" VARCHAR(16), CONSTRAINT "auths_pkey" PRIMARY KEY ("id"), - CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Copay', 'PriorAuth', 'Referral')) + CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Coupon', 'Permit', 'Referral')) ); CREATE TABLE "post_referrals" ( @@ -472,7 +472,7 @@ CREATE VIEW "v_auths_by_kind" AS COUNT(a."id") AS "auths", COUNT(DISTINCT a."reference") AS "distinctRefs" FROM "public"."auths" a - WHERE a."type" <> 'PriorAuth' + WHERE a."type" <> 'Permit' GROUP BY a."type"; COMMENT ON VIEW "v_auths_by_kind" IS 'metaobjects:v1:sha256:1c8464289f36afaa7132f22c64ba8e5c5d529d4866cc27bc57b01b148dbbffbd'; diff --git a/fixtures/persistence-conformance/canonical/schema.sqlite.sql b/fixtures/persistence-conformance/canonical/schema.sqlite.sql index 9d390b35a1..9b9ec69128 100644 --- a/fixtures/persistence-conformance/canonical/schema.sqlite.sql +++ b/fixtures/persistence-conformance/canonical/schema.sqlite.sql @@ -99,10 +99,10 @@ CREATE TABLE "auths" ( "type" TEXT, "reference" VARCHAR(80) NOT NULL, "quantity" INTEGER, - "copayAmount" NUMERIC(10,2), + "couponAmount" NUMERIC(10,2), "approver" VARCHAR(80), "urgency" VARCHAR(16), - CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Copay', 'PriorAuth', 'Referral')) + CONSTRAINT "auths_type_chk" CHECK ("type" IN ('Bridge', 'Coupon', 'Permit', 'Referral')) ); CREATE TABLE "post_referrals" ( @@ -421,7 +421,7 @@ CREATE VIEW "v_auths_by_kind" AS COUNT(a."id") AS "auths", COUNT(DISTINCT a."reference") AS "distinctRefs" FROM "auths" a - WHERE a."type" <> 'PriorAuth' + WHERE a."type" <> 'Permit' GROUP BY a."type"; CREATE VIEW "v_gadget_events_by_label" AS diff --git a/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml b/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml index 7085fd46c0..13008d9ca8 100644 --- a/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml +++ b/fixtures/persistence-conformance/queries/report-tph-base-filter.yaml @@ -1,18 +1,18 @@ name: report-tph-base-filter description: | AuthsByKind is declared from the TPH base (Auth), the supported way to report on a - subset of subtypes: an @filter on the discriminator (`type <> 'PriorAuth'`). A row whose + subset of subtypes: an @filter on the discriminator (`type <> 'Permit'`). A row whose type is null is dropped by the comparison, as in any SQL. - 1 Bridge A-1 2 Bridge A-1 3 Copay C-1 - 4 PriorAuth P-1 5 Referral R-1 6 Referral R-2 7 (no type) N-1 - Bridge: 2 rows, 1 distinct reference. Copay: 1, 1. Referral: 2, 2. + 1 Bridge A-1 2 Bridge A-1 3 Coupon C-1 + 4 Permit P-1 5 Referral R-1 6 Referral R-2 7 (no type) N-1 + Bridge: 2 rows, 1 distinct reference. Coupon: 1, 1. Referral: 2, 2. seed-data: | INSERT INTO "auths" ("id","type","reference","quantity","urgency") VALUES (1, 'Bridge', 'A-1', 2, NULL), (2, 'Bridge', 'A-1', 3, NULL), - (3, 'Copay', 'C-1', NULL, NULL), - (4, 'PriorAuth', 'P-1', NULL, NULL), + (3, 'Coupon', 'C-1', NULL, NULL), + (4, 'Permit', 'P-1', NULL, NULL), (5, 'Referral', 'R-1', NULL, 'routine'), (6, 'Referral', 'R-2', NULL, 'urgent'), (7, NULL, 'N-1', NULL, NULL); @@ -23,7 +23,7 @@ queries: sort: [{ field: kind, dir: asc }] expect: - { kind: "Bridge", auths: "2", distinctRefs: "1" } - - { kind: "Copay", auths: "1", distinctRefs: "1" } + - { kind: "Coupon", auths: "1", distinctRefs: "1" } - { kind: "Referral", auths: "2", distinctRefs: "2" } - name: filter-on-the-discriminator-dimension op: list diff --git a/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml b/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml index 235ccb53ce..cd34bfd639 100644 --- a/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml +++ b/fixtures/persistence-conformance/queries/tph-insert-then-find-by-id.yaml @@ -1,6 +1,6 @@ name: tph-insert-then-find-by-id description: | - FR-017 TPH: insert a BridgeAuth and a CopayAuth into the single `auths` table + FR-017 TPH: insert a BridgeAuth and a CouponAuth into the single `auths` table via the runtime, then find by id. A subtype create injects its discriminator value (the caller omits `type`); a subtype find-by-id is SCOPED to that subtype, so a different-subtype row is invisible (null) — the runtime's @@ -16,11 +16,11 @@ queries: data: { reference: "REF-1", quantity: 5 } expect: { id: "1", type: "Bridge", reference: "REF-1", quantity: 5 } - - name: insert-copay + - name: insert-coupon op: create - entity: CopayAuth - data: { reference: "REF-2", copayAmount: "12.50" } - expect: { id: "2", type: "Copay", reference: "REF-2", copayAmount: "12.5" } + entity: CouponAuth + data: { reference: "REF-2", couponAmount: "12.50" } + expect: { id: "2", type: "Coupon", reference: "REF-2", couponAmount: "12.5" } - name: find-bridge-by-id op: get diff --git a/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml b/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml index c4162328be..9c9e4d9690 100644 --- a/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml +++ b/fixtures/persistence-conformance/queries/tph-insert-three-subtypes-list.yaml @@ -14,17 +14,17 @@ queries: data: { reference: "B", quantity: 1 } expect: { id: "1", type: "Bridge", reference: "B", quantity: 1 } - - name: insert-copay + - name: insert-coupon op: create - entity: CopayAuth - data: { reference: "C", copayAmount: "9.99" } - expect: { id: "2", type: "Copay", reference: "C", copayAmount: "9.99" } + entity: CouponAuth + data: { reference: "C", couponAmount: "9.99" } + expect: { id: "2", type: "Coupon", reference: "C", couponAmount: "9.99" } - - name: insert-priorauth + - name: insert-permit op: create - entity: PriorAuthAuth + entity: PermitAuth data: { reference: "P", approver: "Dr. X" } - expect: { id: "3", type: "PriorAuth", reference: "P", approver: "Dr. X" } + expect: { id: "3", type: "Permit", reference: "P", approver: "Dr. X" } - name: list-all-auths-polymorphic op: list @@ -32,5 +32,5 @@ queries: sort: [{ field: id, dir: asc }] expect: - { id: "1", type: "Bridge", reference: "B" } - - { id: "2", type: "Copay", reference: "C" } - - { id: "3", type: "PriorAuth", reference: "P" } + - { id: "2", type: "Coupon", reference: "C" } + - { id: "3", type: "Permit", reference: "P" } diff --git a/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml b/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml index da35b80487..608d3903f0 100644 --- a/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml +++ b/fixtures/persistence-conformance/queries/tph-no-cross-subtype-update.yaml @@ -2,9 +2,9 @@ name: tph-no-cross-subtype-update description: | FR-017 TPH: a subtype's update surface is its OWN columns only, scoped to its own rows. Two cross-subtype writes must FAIL through the runtime: - (a) patching a BridgeAuth with a Copay-only column (copayAmount) — that + (a) patching a BridgeAuth with a Coupon-only column (couponAmount) — that column is not a field of BridgeAuth, so the write is rejected; - (b) patching id 2 (a Copay) through BridgeAuth — the row is invisible to the + (b) patching id 2 (a Coupon) through BridgeAuth — the row is invisible to the subtype scope, so it's not found. After both rejected writes the Bridge row is unchanged. @@ -16,17 +16,17 @@ queries: data: { reference: "REF-1", quantity: 5 } expect: { id: "1", type: "Bridge", reference: "REF-1", quantity: 5 } - - name: insert-copay + - name: insert-coupon op: create - entity: CopayAuth - data: { reference: "REF-2", copayAmount: "1.00" } - expect: { id: "2", type: "Copay", reference: "REF-2", copayAmount: "1" } + entity: CouponAuth + data: { reference: "REF-2", couponAmount: "1.00" } + expect: { id: "2", type: "Coupon", reference: "REF-2", couponAmount: "1" } - name: cross-subtype-column-rejected op: update entity: BridgeAuth by: { id: 1 } - data: { copayAmount: "9.99" } + data: { couponAmount: "9.99" } expect-error: true - name: cross-subtype-id-not-found diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs index 5e543698c7..1e65c43c8c 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesExtendsChainTests.cs @@ -38,12 +38,12 @@ public class NamesExtendsChainTests { "object.entity": { "name": "Auth", "@discriminator": "kind", "children": [ { "source.rdb": { "@table": "zz_auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@values": ["Copay"] } }, + { "field.enum": { "name": "kind", "@values": ["Coupon"] } }, { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } ]}}, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ - { "field.long": { "name": "copayAmount", "@column": "zz_copay_cents" } } + { "field.long": { "name": "couponAmount", "@column": "zz_coupon_cents" } } ]}}, { "object.value": { "name": "Money", "children": [ { "field.long": { "name": "cents", "@column": "zz_cents" } } @@ -107,9 +107,9 @@ public void The_child_extends_the_base_and_declares_only_its_own_column() [Fact] public void A_tph_subtype_inherits_the_shared_table_name_rather_than_restating_it() { - var src = Generate()["CopayAuthNames.g.cs"]; - Assert.Contains("public abstract class CopayAuthNames : AuthNames", src); - Assert.Contains("public const string CopayAmountColumn = \"zz_copay_cents\";", src); + var src = Generate()["CouponAuthNames.g.cs"]; + Assert.Contains("public abstract class CouponAuthNames : AuthNames", src); + Assert.Contains("public const string CouponAmountColumn = \"zz_coupon_cents\";", src); // The whole point: the subtype used to restate the base's table name and every one // of its columns. Assert.DoesNotContain("zz_auths", src); @@ -197,11 +197,11 @@ public static class Probe // An inherited const from a TPH base, including the shared table name. A TPH // subtype declares no own source, so `SourcePrimaryTable` is the base's, reached // through the base class — not restated here. - public const string B = CopayAuthNames.SourcePrimaryTable; - public const string C = CopayAuthNames.CopayAmountColumn; + public const string B = CouponAuthNames.SourcePrimaryTable; + public const string C = CouponAuthNames.CouponAmountColumn; // ColumnsByField stays COMPLETE on the subtype — it is the lookup surface, and a // miss on an inherited field is the fallback-to-literal this artifact removes. - public static readonly int Count = CopayAuthNames.ColumnsByField.Count; + public static readonly int Count = CouponAuthNames.ColumnsByField.Count; } """; var trees = files.Values.Append(probe) @@ -219,11 +219,11 @@ public static class Probe // A clean compile proves the members resolve; this proves the SUBTYPE's dictionary // is the complete one rather than the base's (a static field is hidden, not - // overridden, so `new` is what makes CopayAuthNames.ColumnsByField the 4-entry one). - var sub = files["CopayAuthNames.g.cs"]; + // overridden, so `new` is what makes CouponAuthNames.ColumnsByField the 4-entry one). + var sub = files["CouponAuthNames.g.cs"]; Assert.Contains("public static new readonly Dictionary ColumnsByField", sub); Assert.Contains("[\"id\"] = IdColumn,", sub); - Assert.Contains("[\"copayAmount\"] = CopayAmountColumn,", sub); + Assert.Contains("[\"couponAmount\"] = CouponAmountColumn,", sub); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs index 42ca27bc18..90d2972544 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs @@ -274,7 +274,7 @@ public void Real_P3_config_resolves_all_18_domains_correctly() ["acme::reporting"] = "Acme.Domain.Entities.ReportEntities", ["acme::domain::dataEnums"] = "Acme.Domain.DataEnums", ["acme::domain::dataEnums::authorizations"] = "Acme.Domain.DataEnums.Authorizations", - ["acme::domain::dataEnums::copayCards"] = "Acme.Domain.DataEnums.CopayCards", + ["acme::domain::dataEnums::couponCards"] = "Acme.Domain.DataEnums.CouponCards", ["acme::domain::dataEnums::dataExportIntegration"] = "Acme.Domain.DataEnums.DataExportIntegration", ["acme::domain::dataEnums::spIntegration"] = "Acme.Domain.DataEnums.SPIntegration", }, diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs index 3add671301..f35b0a8e38 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphCodegenTests.cs @@ -26,23 +26,23 @@ namespace MetaObjects.Codegen.Tests; public class TphCodegenTests { // Mirrors fixtures/api-contract-conformance/tph/meta.json: Auth base - // (@discriminator "type", table "auths") + Bridge/Copay/PriorAuth subtypes. + // (@discriminator "type", table "auths") + Bridge/Coupon/Permit subtypes. private const string Model = """ { "metadata.root": { "package": "acme::auth", "children": [ { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ]}}, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true, "@filterable": true, "@sortable": true } } ]}}, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ]}}, - { "object.entity": { "name": "PriorAuthAuth", "extends": "Auth", "@discriminatorValue": "PriorAuth", "children": [ + { "object.entity": { "name": "PermitAuth", "extends": "Auth", "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80, "@filterable": true, "@sortable": true } } ]}} ]}} @@ -75,14 +75,14 @@ public void Plan_resolves_base_and_subtypes_in_stable_order() var plan = TphPlanBuilder.For(auth, root); Assert.NotNull(plan); Assert.Equal("type", plan!.DiscriminatorField); - // Name-sorted: BridgeAuth, CopayAuth, PriorAuthAuth. - Assert.Equal(["BridgeAuth", "CopayAuth", "PriorAuthAuth"], plan.Subtypes.Select(s => s.Entity.Name)); - Assert.Equal(["Bridge", "Copay", "PriorAuth"], plan.Subtypes.Select(s => s.Value)); - Assert.Equal(["bridge", "copay", "priorauth"], plan.Subtypes.Select(s => s.RouteSegment)); + // Name-sorted: BridgeAuth, CouponAuth, PermitAuth. + Assert.Equal(["BridgeAuth", "CouponAuth", "PermitAuth"], plan.Subtypes.Select(s => s.Entity.Name)); + Assert.Equal(["Bridge", "Coupon", "Permit"], plan.Subtypes.Select(s => s.Value)); + Assert.Equal(["bridge", "coupon", "permit"], plan.Subtypes.Select(s => s.RouteSegment)); // The subtypes are NOT TPH bases; they ARE TPH subtypes. Assert.True(TphPlanBuilder.IsTphDiscriminatorBase(auth, root)); - foreach (var name in new[] { "BridgeAuth", "CopayAuth", "PriorAuthAuth" }) + foreach (var name in new[] { "BridgeAuth", "CouponAuth", "PermitAuth" }) { var sub = root.FindObject(name)!; Assert.False(TphPlanBuilder.IsTphDiscriminatorBase(sub, root)); @@ -127,8 +127,8 @@ public void Entity_base_declares_its_subtypes_for_polymorphic_serialization() var auth = FileContent(new EntityGenerator().Generate(Ctx(Load())), "Auth.g.cs"); Assert.Contains("[global::System.Text.Json.Serialization.JsonDerivedType(typeof(BridgeAuth))]", auth); - Assert.Contains("[global::System.Text.Json.Serialization.JsonDerivedType(typeof(CopayAuth))]", auth); - Assert.Contains("[global::System.Text.Json.Serialization.JsonDerivedType(typeof(PriorAuthAuth))]", auth); + Assert.Contains("[global::System.Text.Json.Serialization.JsonDerivedType(typeof(CouponAuth))]", auth); + Assert.Contains("[global::System.Text.Json.Serialization.JsonDerivedType(typeof(PermitAuth))]", auth); Assert.DoesNotContain("typeDiscriminator", auth); } @@ -174,15 +174,15 @@ public void Entity_subtypes_extend_base_with_only_own_fields_and_no_table() Assert.DoesNotContain("public long Id", bridge); Assert.DoesNotContain("public string Reference", bridge); - var copay = FileContent(files, "CopayAuth.g.cs"); - Assert.Contains("public class CopayAuth : Auth", copay); - Assert.DoesNotContain("[Table", copay); - Assert.Contains("public decimal? CopayAmount { get; set; }", copay); + var coupon = FileContent(files, "CouponAuth.g.cs"); + Assert.Contains("public class CouponAuth : Auth", coupon); + Assert.DoesNotContain("[Table", coupon); + Assert.Contains("public decimal? CouponAmount { get; set; }", coupon); - var priorAuth = FileContent(files, "PriorAuthAuth.g.cs"); - Assert.Contains("public class PriorAuthAuth : Auth", priorAuth); - Assert.DoesNotContain("[Table", priorAuth); - Assert.Contains("public string? Approver { get; set; }", priorAuth); + var permit = FileContent(files, "PermitAuth.g.cs"); + Assert.Contains("public class PermitAuth : Auth", permit); + Assert.DoesNotContain("[Table", permit); + Assert.Contains("public string? Approver { get; set; }", permit); } [Fact] @@ -192,8 +192,8 @@ public void DbContext_emits_single_dbset_and_has_discriminator() // Exactly one DbSet for the hierarchy (the base); no per-subtype DbSet. Assert.Contains("public DbSet Auths { get; set; }", db); Assert.DoesNotContain("DbSet", db); - Assert.DoesNotContain("DbSet", db); - Assert.DoesNotContain("DbSet", db); + Assert.DoesNotContain("DbSet", db); + Assert.DoesNotContain("DbSet", db); // HasDiscriminator + HasValue per subtype (the discriminator maps to the enum prop; // the enum's HasConversion() stores the symbol, so the column is TEXT). // Bare "Auth." stays bare: the global::-qualification (CSharpNaming.QualifiedOwnerTypeRef) @@ -201,8 +201,8 @@ public void DbContext_emits_single_dbset_and_has_discriminator() // a base entity named like e.g. "AllTypes" would get the qualified form. Assert.Contains("HasDiscriminator(e => e.Type)", db); Assert.Contains("HasValue(global::Acme.Auth.Auth.AuthType.Bridge)", db); - Assert.Contains("HasValue(global::Acme.Auth.Auth.AuthType.Copay)", db); - Assert.Contains("HasValue(global::Acme.Auth.Auth.AuthType.PriorAuth)", db); + Assert.Contains("HasValue(global::Acme.Auth.Auth.AuthType.Coupon)", db); + Assert.Contains("HasValue(global::Acme.Auth.Auth.AuthType.Permit)", db); } [Fact] @@ -213,8 +213,8 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() // Subtypes emit NO routes file (they are folded into the base). Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "BridgeAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "CopayAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "PriorAuthAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "CouponAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "PermitAuthRoutes.g.cs"); var auth = FileContent(files, "AuthRoutes.g.cs"); // Polymorphic list + get at the base path; NO base POST (can't create an abstract base). @@ -222,8 +222,8 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() Assert.Contains("prefix + \"/auths/{id}\"", auth); // Per-subtype segments are the @discriminatorValue lowercased. Assert.Contains("prefix + \"/auths/bridge\"", auth); - Assert.Contains("prefix + \"/auths/copay\"", auth); - Assert.Contains("prefix + \"/auths/priorauth\"", auth); + Assert.Contains("prefix + \"/auths/coupon\"", auth); + Assert.Contains("prefix + \"/auths/permit\"", auth); // Per-subtype CRUD: create scopes reads/mutations via OfType() and injects the // discriminator via the subtype CLR type on Add (the POST body omits it). FR-036 #4 — // because every subtype has a @required field (the base string `reference`, and @@ -236,8 +236,8 @@ public void Routes_base_emits_polymorphic_and_per_subtype_no_subtype_files() Assert.Matches(@"new\[\] \{[^}]*""reference""[^}]*\}", auth); // base @required string Assert.Matches(@"new\[\] \{[^}]*""quantity""[^}]*\}", auth); // own @required value-type Assert.Contains("OfType()", auth); - Assert.Contains("OfType()", auth); - Assert.Contains("OfType()", auth); + Assert.Contains("OfType()", auth); + Assert.Contains("OfType()", auth); // Polymorphic POST is NOT emitted on the base path itself. Assert.DoesNotContain("MapPost(prefix + \"/auths\",", auth); // Per-subtype list ?sort resolves the raw qs field through a per-subtype diff --git a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs index 967869d18f..0039efc202 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/TphM2mRoutesTests.cs @@ -25,8 +25,8 @@ // silent 404. // C. a THIRD, latent compile defect this model's abstract mid level (ScopedAuth) // surfaced under the DEFAULT config (EmitAbstractShapes: false — see Ctx() below): -// `class PriorAuthAuth : ScopedAuth` named a class that is never emitted, AND -// ScopedAuth's own field was silently excluded from PriorAuthAuth's member set as +// `class PermitAuth : ScopedAuth` named a class that is never emitted, AND +// ScopedAuth's own field was silently excluded from PermitAuth's member set as // "already inherited" by that never-emitted class — a dropped member, worse than // the compile error alone. Fixed by EntityGenerator.EmittedTphAncestor (walks past // any skipped abstract level to the nearest ancestor that IS emitted — ultimately @@ -42,9 +42,9 @@ // - BridgeAuth (subtype) declares "linkedAuths", a directed self-join onto // itself through AuthLink — subtype-declared AND a subtype-typed M:N target // in one relationship (rule b/c + defect B) -// - CopayAuth (subtype) declares nothing of its own; it still resolves "tags" +// - CouponAuth (subtype) declares nothing of its own; it still resolves "tags" // via extends (rule b, overlap with a) -// - ScopedAuth (ABSTRACT mid level between Auth and PriorAuthAuth) declares +// - ScopedAuth (ABSTRACT mid level between Auth and PermitAuth) declares // "auditors" -> Tag through AuthAudit — served nowhere but under the one // concrete subtype beneath it (rule d) // - Payer (non-TPH source) declares "bridgeAuths" -> BridgeAuth through @@ -73,7 +73,7 @@ public class TphM2mRoutesTests { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths2" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } @@ -83,14 +83,14 @@ public class TphM2mRoutesTests { "field.boolean": { "name": "verified", "@required": true, "@default": true } }, { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ]}}, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.int": { "name": "copayCents" } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.int": { "name": "couponCents" } } ]}}, { "object.entity": { "name": "ScopedAuth", "extends": "Auth", "abstract": true, "children": [ { "field.string": { "name": "auditNotes", "@maxLength": 200 } }, { "relationship.association": { "name": "auditors", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthAudit" } } ]}}, - { "object.entity": { "name": "PriorAuthAuth", "extends": "ScopedAuth", "@discriminatorValue": "PriorAuth", "children": [ + { "object.entity": { "name": "PermitAuth", "extends": "ScopedAuth", "@discriminatorValue": "Permit", "children": [ { "field.string": { "name": "approver", "@maxLength": 80 } } ]}}, { "object.entity": { "name": "AuthTag", "children": [ @@ -114,7 +114,7 @@ public class TphM2mRoutesTests { "field.long": { "name": "auditAuthId", "@required": true } }, { "field.long": { "name": "auditTagId", "@required": true } }, { "identity.primary": { "@fields": ["auditAuthId", "auditTagId"] } }, - { "identity.reference": { "name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PriorAuthAuth" } }, + { "identity.reference": { "name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PermitAuth" } }, { "identity.reference": { "name": "fkAuditTag", "@fields": "auditTagId", "@references": "Tag" } } ]}}, { "object.entity": { "name": "Payer", "children": [ @@ -136,10 +136,10 @@ public class TphM2mRoutesTests """; // DEFAULT config deliberately — EmitAbstractShapes is false (the GenConfig default), - // so ScopedAuth (the abstract TPH mid level between Auth and PriorAuthAuth) emits NO - // class of its own. That used to leave `class PriorAuthAuth : ScopedAuth` referencing + // so ScopedAuth (the abstract TPH mid level between Auth and PermitAuth) emits NO + // class of its own. That used to leave `class PermitAuth : ScopedAuth` referencing // a type that does not exist, AND silently dropped ScopedAuth's own fields (excluded - // from PriorAuthAuth's member set as "already inherited" by a class that was never + // from PermitAuth's member set as "already inherited" by a class that was never // emitted). See EntityGenerator.EmittedTphAncestor + the tests below. private static GenContext Ctx(MetaRoot root) => new() { @@ -215,16 +215,16 @@ public void Subtype_declared_selfjoin_gates_the_source_and_binds_target_through_ public void Inherited_m2m_is_served_at_the_base_and_under_every_concrete_subtype() { var routes = FileContent(new RoutesGenerator().Generate(Ctx(Load())), "AuthRoutes.g.cs"); - // "tags" is declared on Auth, so BridgeAuth/CopayAuth/PriorAuthAuth all resolve it + // "tags" is declared on Auth, so BridgeAuth/CouponAuth/PermitAuth all resolve it // too (rule b) — the base mount plus one per subtype is FOUR mounts total. This is // the independent oracle's rule (expectedRoutes), which walks every SERVED // object's RESOLVED relationships, not an own-only read. var tagMounts = System.Text.RegularExpressions.Regex.Matches(routes, "\\{id\\}/tags\"").Count; - Assert.Equal(4, tagMounts); // /auths, /auths/bridge, /auths/copay, /auths/priorauth - var copayMount = ExtractMount(routes, "/auths/copay/{id}/tags"); - Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", copayMount); - var priorAuthMount = ExtractMount(routes, "/auths/priorauth/{id}/tags"); - Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", priorAuthMount); + Assert.Equal(4, tagMounts); // /auths, /auths/bridge, /auths/coupon, /auths/permit + var couponMount = ExtractMount(routes, "/auths/coupon/{id}/tags"); + Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", couponMount); + var permitMount = ExtractMount(routes, "/auths/permit/{id}/tags"); + Assert.Contains("if (!await db.Auths.OfType().AnyAsync(x => x.Id == id))", permitMount); } [Fact] @@ -233,26 +233,26 @@ public void Abstract_mid_level_m2m_is_served_only_under_the_one_concrete_subtype var routes = FileContent(new RoutesGenerator().Generate(Ctx(Load())), "AuthRoutes.g.cs"); // "auditors" lives on ScopedAuth — abstract, so it has no path and no rows of its // own, and it is not on the base either. The ONLY place it can be served is - // beneath PriorAuthAuth, the one concrete subtype beneath that level. - var mount = ExtractMount(routes, "/auths/priorauth/{id}/auditors"); + // beneath PermitAuth, the one concrete subtype beneath that level. + var mount = ExtractMount(routes, "/auths/permit/{id}/auditors"); Assert.Contains("db.AuthAudits", mount); Assert.Contains("db.Tags.AsNoTracking()", mount); Assert.DoesNotContain("/auths/{id}/auditors\"", routes); Assert.DoesNotContain("/auths/bridge/{id}/auditors\"", routes); - Assert.DoesNotContain("/auths/copay/{id}/auditors\"", routes); + Assert.DoesNotContain("/auths/coupon/{id}/auditors\"", routes); } [Fact] public void Abstract_mid_level_extends_and_field_fold_under_the_default_config() { // GenConfig.EmitAbstractShapes defaults to false, so ScopedAuth (abstract, between - // Auth and PriorAuthAuth) emits NO class of its own. Two things must still be true: - // 1. PriorAuthAuth's base-class clause resolves PAST ScopedAuth to the nearest + // Auth and PermitAuth) emits NO class of its own. Two things must still be true: + // 1. PermitAuth's base-class clause resolves PAST ScopedAuth to the nearest // ancestor that DOES get emitted — here, the TPH discriminator base itself // (always emitted; never metadata-abstract) — instead of naming a type that // does not exist. // 2. ScopedAuth's OWN field ("auditNotes") still lands SOMEWHERE — on - // PriorAuthAuth, the one concrete subtype beneath it — rather than being + // PermitAuth, the one concrete subtype beneath it — rather than being // silently dropped because it was excluded as "already inherited" by a class // that was never emitted. A dropped member is worse than the compile error // fixing only the base-class clause would have left behind: the compile error @@ -260,17 +260,17 @@ public void Abstract_mid_level_extends_and_field_fold_under_the_default_config() var files = new EntityGenerator().Generate(Ctx(Load())).ToList(); Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "ScopedAuth.g.cs"); - var priorAuth = FileContent(files, "PriorAuthAuth.g.cs"); - Assert.Contains("public class PriorAuthAuth : Auth", priorAuth); - Assert.DoesNotContain("ScopedAuth", priorAuth); + var permit = FileContent(files, "PermitAuth.g.cs"); + Assert.Contains("public class PermitAuth : Auth", permit); + Assert.DoesNotContain("ScopedAuth", permit); // ScopedAuth's own field, folded onto the one concrete subtype beneath it. - Assert.Contains("public string? AuditNotes { get; set; }", priorAuth); + Assert.Contains("public string? AuditNotes { get; set; }", permit); // The sibling subtypes (which do NOT extend ScopedAuth) never see it. var bridge = FileContent(files, "BridgeAuth.g.cs"); Assert.DoesNotContain("AuditNotes", bridge); - var copay = FileContent(files, "CopayAuth.g.cs"); - Assert.DoesNotContain("AuditNotes", copay); + var coupon = FileContent(files, "CouponAuth.g.cs"); + Assert.DoesNotContain("AuditNotes", coupon); } [Fact] @@ -291,8 +291,8 @@ public void Subtypes_still_emit_no_standalone_routes_file() { var files = new RoutesGenerator().Generate(Ctx(Load())).ToList(); Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "BridgeAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "CopayAuthRoutes.g.cs"); - Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "PriorAuthAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "CouponAuthRoutes.g.cs"); + Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "PermitAuthRoutes.g.cs"); Assert.DoesNotContain(files, f => System.IO.Path.GetFileName(f.Path) == "ScopedAuthRoutes.g.cs"); } @@ -318,9 +318,9 @@ public void Full_model_compiles_against_ef_core_8_and_aspnetcore() // compiles clean everywhere else and only fails here, or in a live consumer's build. // // Also the regression guard for the abstract-TPH-mid-level defect (ScopedAuth, - // between Auth and PriorAuthAuth): Ctx() uses the DEFAULT config + // between Auth and PermitAuth): Ctx() uses the DEFAULT config // (EmitAbstractShapes: false), the shape a shared cross-port conformance fixture - // carries — a `class PriorAuthAuth : ScopedAuth` referencing a class that is never + // carries — a `class PermitAuth : ScopedAuth` referencing a class that is never // emitted is exactly what this compile assertion exists to catch. var ctx = Ctx(Load()); var sources = new EntityGenerator().Generate(ctx) diff --git a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs index d393cba5b8..b089e77f13 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/NamesGenerator.cs @@ -382,7 +382,7 @@ private static HashSet InheritedMembers(MetaObject obj, ColumnNamingStra // `abstract class`, not `static class`: a static class can neither inherit nor be // inherited, and this artifact now extends its parent's rather than restating it. // Abstract keeps the "never instantiate this" guarantee a static class gave, and a - // `const` is inherited — `CopayAuthNames.IdColumn` resolves through the base — so + // `const` is inherited — `CouponAuthNames.IdColumn` resolves through the base — so // every consumption site is unchanged. var extends = superCls is null ? "" : $" : {superCls}"; sb.AppendLine($"public abstract class {cls}{extends}"); diff --git a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs index 17c70322a1..01b7d4203a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/TphPlan.cs @@ -40,7 +40,7 @@ public static class TphPlanBuilder /// /// The per-subtype REST route segment for a discriminator value — the ONE place /// this rule lives (mirrors TS tphRouteSegment): the value lowercased - /// ("Bridge" → bridge, "PriorAuth" → priorauth). + /// ("Bridge" → bridge, "Permit" → permit). /// public static string RouteSegment(string discriminatorValue) => discriminatorValue.ToLowerInvariant(); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs index d4ff3e9a5f..25d70730e4 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCorpusPaths.cs @@ -47,7 +47,7 @@ internal static class ApiContractCorpusPaths public static readonly string M2mMetaJson = Path.Combine(M2mDir, "meta.json"); // FR-017 TPH polymorphic-CRUD corpus — a discriminator base (Auth) + concrete - // subtypes (Bridge/Copay/PriorAuth) sharing one `auths` table, under tph/. + // subtypes (Bridge/Coupon/Permit) sharing one `auths` table, under tph/. public static readonly string TphDir = Path.Combine(Corpus, "tph"); public static readonly string TphScenariosDir = Path.Combine(TphDir, "scenarios"); public static readonly string TphSeedFile = Path.Combine(TphDir, "seed.json"); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs index 7fd05aae18..c49dbd5bfb 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs @@ -1,8 +1,8 @@ // TphFixture — shared schema-provisioning + seed for the FR-017 TPH api-contract // lanes (reference + generated). One physical `auths` table holds every subtype; -// subtype-only columns (quantity / copayAmount / approver) are nullable. The DDL +// subtype-only columns (quantity / couponAmount / approver) are nullable. The DDL // mirrors fixtures/persistence-conformance/canonical/schema.postgres.sql's `auths` -// table (literal column naming — `copayAmount` stays camelCase under the C# literal +// table (literal column naming — `couponAmount` stays camelCase under the C# literal // strategy). The seed is tph/seed.json (rows keyed under the `auths` table name). using System.Globalization; @@ -32,7 +32,7 @@ internal static class TphFixture "type" TEXT, "reference" VARCHAR(80) NOT NULL, "quantity" INTEGER, - "copayAmount" NUMERIC(10,2), + "couponAmount" NUMERIC(10,2), "approver" VARCHAR(80), -- FR-037 R1: the @mutability "writeOnce" column, declared on the TPH BASE so -- every subtype inherits it. @@ -40,12 +40,12 @@ internal static class TphFixture "autoCreatedAt" TIMESTAMPTZ, "autoUpdatedAt" TIMESTAMPTZ, CONSTRAINT "auths_pkey" PRIMARY KEY ("id"), - CONSTRAINT "auths_type_chk" CHECK (type IN ('Bridge', 'Copay', 'PriorAuth')) + CONSTRAINT "auths_type_chk" CHECK (type IN ('Bridge', 'Coupon', 'Permit')) ); """; private static readonly string[] Cols = - { "id", "type", "reference", "quantity", "copayAmount", "approver", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt" }; + { "id", "type", "reference", "quantity", "couponAmount", "approver", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt" }; /// Create the single `auths` table on a fresh container. public static async Task ProvisionSchemaAsync(string connString) @@ -93,8 +93,8 @@ public static async Task ApplySeedAsync(string connString, string seedPath) : Cols[i] switch { "id" or "quantity" => v.GetValue(), - // copayAmount is authored as a string ("12.50") to preserve scale. - "copayAmount" => decimal.Parse(v.GetValue(), System.Globalization.CultureInfo.InvariantCulture), + // couponAmount is authored as a string ("12.50") to preserve scale. + "couponAmount" => decimal.Parse(v.GetValue(), System.Globalization.CultureInfo.InvariantCulture), // #203 / ADR-0045 — the seed writes the OLD @autoSet sentinel VERBATIM // (a direct insert, NOT a stamping create) so the seeded row keeps the // old value; the offset-less wire form is interpreted as UTC (the diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs index 0f5abfc918..8bdb9d964d 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs @@ -1,7 +1,7 @@ // TphGeneratedServerFactory — FR-017: the C# GENERATED-server lane for TPH. // // Runs the real MetaObjects.Codegen generators (Entity + DbContext + FilterAllowlist -// + Routes) on the tph corpus model (Auth + Bridge/Copay/PriorAuth subtypes), +// + Routes) on the tph corpus model (Auth + Bridge/Coupon/Permit subtypes), // Roslyn-compiles the emitted sources in-memory, and hosts them on a real ASP.NET // Core host (Kestrel) against Testcontainers Postgres. The EMITTED AuthRoutes // (polymorphic GET + per-subtype CRUD) is the artifact under test — a failing diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs index 1d5955b386..f0ca91e862 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs @@ -11,8 +11,8 @@ // PUT /api/auths//{id} alias of PATCH // DELETE /api/auths//{id} per-subtype delete (404 cross-subtype) // -// The per-subtype segment is the discriminator value lowercased (bridge/copay/ -// priorauth). This is the contract the GENERATED lane (TphGeneratedServerFactory) +// The per-subtype segment is the discriminator value lowercased (bridge/coupon/ +// permit). This is the contract the GENERATED lane (TphGeneratedServerFactory) // must also satisfy; the corpus + assertion vocabulary are shared. using System.Globalization; @@ -34,8 +34,8 @@ internal sealed class TphReferenceServer : IAsyncDisposable private static readonly Dictionary SegmentToValue = new(StringComparer.Ordinal) { ["bridge"] = "Bridge", - ["copay"] = "Copay", - ["priorauth"] = "PriorAuth", + ["coupon"] = "Coupon", + ["permit"] = "Permit", }; // Every column the `auths` table carries (base + every subtype-only column). @@ -43,7 +43,7 @@ internal sealed class TphReferenceServer : IAsyncDisposable // from this caller-settable projection, so a presented value is STRIPPED on PATCH // rather than rejected (the same treatment autoCreatedAt/autoUpdatedAt get by being // absent here). It IS written on create, explicitly, below. Do NOT add it here. - private static readonly string[] AllCols = { "id", "type", "reference", "quantity", "copayAmount", "approver" }; + private static readonly string[] AllCols = { "id", "type", "reference", "quantity", "couponAmount", "approver" }; private readonly PostgresContainer _pg; private readonly WebApplication _app; @@ -120,7 +120,7 @@ private async Task DispatchAsync(HttpContext ctx) return; } - // segs[2] is either a subtype segment (bridge/copay/priorauth) or an {id}. + // segs[2] is either a subtype segment (bridge/coupon/permit) or an {id}. if (segs.Length >= 3 && SegmentToValue.TryGetValue(segs[2], out var disc)) { // Per-subtype routes. @@ -140,9 +140,9 @@ private async Task DispatchAsync(HttpContext ctx) if (method == "POST") { var body = await ReadBodyAsync(ctx); - // ADR-0019 Amendment 1 (W3): copayAmount is decimal(10,2); a value it would + // ADR-0019 Amendment 1 (W3): couponAmount is decimal(10,2); a value it would // round or overflow is a 400 validation, never stored rounded. - if (!CopayAmountFits(body)) + if (!CouponAmountFits(body)) { await SendJsonAsync(ctx, 400, new Dictionary { ["error"] = "validation" }); return; @@ -176,7 +176,7 @@ private async Task DispatchAsync(HttpContext ctx) // FR-036 Program B: a present null on the @required (NOT NULL) base // `reference` column is a 400, matching the generated controller's // not-null merge guard. In the single TPH table only base-required - // columns are NOT NULL; subtype columns (quantity/copayAmount/approver) + // columns are NOT NULL; subtype columns (quantity/couponAmount/approver) // are nullable, so a present null there clears them (FR-035 tristate). if (body.ContainsKey("reference")) { @@ -189,7 +189,7 @@ private async Task DispatchAsync(HttpContext ctx) } // FR-036 — a present value exceeding @maxLength:80 (reference/approver) is a // 400, matching the generated controller's per-present-value PATCH validation. - if (ExceedsMaxLength(body) || !CopayAmountFits(body)) + if (ExceedsMaxLength(body) || !CouponAmountFits(body)) { await SendJsonAsync(ctx, 400, new Dictionary { ["error"] = "validation" }); return; @@ -230,13 +230,13 @@ private async Task DispatchAsync(HttpContext ctx) }; // A per-subtype collection filters by the base's columns plus that subtype's own. Only - // CopayAuth.copayAmount is filterable among the subtype columns the corpus exercises; a + // CouponAuth.couponAmount is filterable among the subtype columns the corpus exercises; a // decimal operand is compared exactly (ADR-0019 Amendment 1, W2). private static IReadOnlyDictionary SubtypeFilterOps(string discriminator) { var ops = new Dictionary(BaseFilterOps, StringComparer.Ordinal); ops.Remove("type"); - if (discriminator == "Copay") ops["copayAmount"] = new[] { "eq", "ne", "gt", "gte", "lt", "lte", "in" }; + if (discriminator == "Coupon") ops["couponAmount"] = new[] { "eq", "ne", "gt", "gte", "lt", "lte", "in" }; return ops; } @@ -258,7 +258,7 @@ private static (List Filters, string? Error, string? Field) ParseFil string raw = query[key].ToString(); string[] values = op == "in" ? raw.Split(',') : new[] { raw }; if (field == "id" && values.Any(v => !long.TryParse(v, out _))) return (filters, "invalid_filter_value", field); - if (field == "copayAmount" && values.Any(v => !DecimalWire.TryParse(v, out _))) return (filters, "invalid_filter_value", field); + if (field == "couponAmount" && values.Any(v => !DecimalWire.TryParse(v, out _))) return (filters, "invalid_filter_value", field); filters.Add(new BaseFilter(field, op, values)); } return (filters, null, null); @@ -278,7 +278,7 @@ private static (List Filters, string? Error, string? Field) ParseFil object Bind(string v) => f.Field switch { "id" => long.Parse(v), - "copayAmount" => DecimalWire.TryParse(v, out var d) ? d : throw new FormatException(v), + "couponAmount" => DecimalWire.TryParse(v, out var d) ? d : throw new FormatException(v), _ => v, }; var names = new List(); @@ -422,7 +422,7 @@ private async Task DeleteAsync(string discriminator, long id) // -------- helpers -------- // FR-036 — the TPH @maxLength:80 string columns: `reference` (base) and `approver` - // (PriorAuth subtype). A present value exceeding 80 chars is a 400 {error:"validation"} + // (Permit subtype). A present value exceeding 80 chars is a 400 {error:"validation"} // (mirrors the generated Dto's [MaxLength(80)] + the vanilla ExceedsAuthorMaxLength // guard), rejected before the PG write (which would otherwise 500 with 22001) — on the // per-subtype create AND on a present PATCH value. @@ -436,7 +436,7 @@ private static bool IsOverLength(JsonObject body, string col) => private static object CoerceColumn(string col, JsonNode v) => col switch { "quantity" => v.GetValue(), - "copayAmount" => ReadDecimal(v) ?? throw new FormatException("copayAmount"), + "couponAmount" => ReadDecimal(v) ?? throw new FormatException("couponAmount"), _ => v.GetValue(), }; @@ -448,11 +448,11 @@ private static bool IsOverLength(JsonObject body, string col) => ? d : null; - // W3: copayAmount is decimal(10,2); a value the column would round or overflow is refused + // W3: couponAmount is decimal(10,2); a value the column would round or overflow is refused // rather than stored rounded. Absent or null is the caller's business, not this check's. - private static bool CopayAmountFits(JsonObject body) + private static bool CouponAmountFits(JsonObject body) { - if (!body.TryGetPropertyValue("copayAmount", out var node) || node is null + if (!body.TryGetPropertyValue("couponAmount", out var node) || node is null || node.GetValueKind() == JsonValueKind.Null) return true; return ReadDecimal(node) is { } d && DecimalWire.Fits(d, 10, 2); } diff --git a/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs b/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs index 8a76d60fa7..f890bac36f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/AppDbContextModelTests.cs @@ -32,8 +32,8 @@ public void Model_builds_without_error() var auth = model.FindEntityType(typeof(Auth)); Assert.NotNull(auth); Assert.NotNull(model.FindEntityType(typeof(BridgeAuth))); - Assert.NotNull(model.FindEntityType(typeof(CopayAuth))); - Assert.NotNull(model.FindEntityType(typeof(PriorAuthAuth))); + Assert.NotNull(model.FindEntityType(typeof(CouponAuth))); + Assert.NotNull(model.FindEntityType(typeof(PermitAuth))); Assert.Equal("auths", auth!.GetTableName()); } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs index 218b851c47..37a2575de8 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs @@ -110,8 +110,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().Property(x => x.ExternalId).HasColumnType("uuid").HasConversion(v => global::System.Guid.Parse(v!), g => g.ToString("D")); modelBuilder.Entity().Property(x => x.Payload).HasColumnType("jsonb"); modelBuilder.Entity().Property(x => x.Type).HasConversion(); - modelBuilder.Entity().HasDiscriminator(e => e.Type).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Bridge).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Copay).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.PriorAuth).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Referral); - modelBuilder.Entity().Property(x => x.CopayAmount).HasPrecision(10, 2); + modelBuilder.Entity().HasDiscriminator(e => e.Type).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Bridge).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Coupon).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Permit).HasValue(global::MetaObjects.IntegrationTests.Generated.Auth.AuthType.Referral); + modelBuilder.Entity().Property(x => x.CouponAmount).HasPrecision(10, 2); modelBuilder.Entity().Property(x => x.Urgency).HasDefaultValue("routine").HasSentinel("routine"); modelBuilder.Entity().Property(x => x.Amount).HasPrecision(28, 10); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.FollowerId).OnDelete(DeleteBehavior.NoAction); diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/Auth.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/Auth.g.cs index 195c8e03d7..aec4e8f2ea 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/Auth.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/Auth.g.cs @@ -10,12 +10,12 @@ namespace MetaObjects.IntegrationTests.Generated; [Table(AuthNames.SourcePrimaryTable)] [global::System.Text.Json.Serialization.JsonDerivedType(typeof(BridgeAuth))] -[global::System.Text.Json.Serialization.JsonDerivedType(typeof(CopayAuth))] -[global::System.Text.Json.Serialization.JsonDerivedType(typeof(PriorAuthAuth))] +[global::System.Text.Json.Serialization.JsonDerivedType(typeof(CouponAuth))] +[global::System.Text.Json.Serialization.JsonDerivedType(typeof(PermitAuth))] [global::System.Text.Json.Serialization.JsonDerivedType(typeof(ReferralAuth))] public abstract class Auth { - public enum AuthType { Bridge, Copay, PriorAuth, Referral } + public enum AuthType { Bridge, Coupon, Permit, Referral } [Key] [Column(AuthNames.IdColumn)] public long Id { get; set; } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/AuthsByKind.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/AuthsByKind.g.cs index b232b1d9eb..d15b0725af 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/AuthsByKind.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/AuthsByKind.g.cs @@ -10,7 +10,7 @@ namespace MetaObjects.IntegrationTests.Generated; public class AuthsByKind { - public enum AuthsByKindKind { Bridge, Copay, PriorAuth, Referral } + public enum AuthsByKindKind { Bridge, Coupon, Permit, Referral } [Column("kind")] public AuthsByKindKind? Kind { get; set; } [Column("auths")] diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CopayAuth.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CouponAuth.g.cs similarity index 73% rename from server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CopayAuth.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CouponAuth.g.cs index 48dbdcc91e..fa58f91d44 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CopayAuth.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CouponAuth.g.cs @@ -8,9 +8,9 @@ namespace MetaObjects.IntegrationTests.Generated; -public class CopayAuth : Auth +public class CouponAuth : Auth { - [Column(CopayAuthNames.CopayAmountColumn)] + [Column(CouponAuthNames.CouponAmountColumn)] [DecimalWire.Declared(10, 2)] - public decimal? CopayAmount { get; set; } + public decimal? CouponAmount { get; set; } } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CopayAuthNames.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CouponAuthNames.g.cs similarity index 60% rename from server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CopayAuthNames.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CouponAuthNames.g.cs index e31365e918..e0a45f53db 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CopayAuthNames.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/CouponAuthNames.g.cs @@ -6,20 +6,20 @@ namespace MetaObjects.IntegrationTests.Generated; /// -/// GENERATED — per-object physical database names for CopayAuth (spec A1/A2/A6). +/// GENERATED — per-object physical database names for CouponAuth (spec A1/A2/A6). /// -public abstract class CopayAuthNames : AuthNames +public abstract class CouponAuthNames : AuthNames { public new const string Type = "object"; public new const string SubType = "entity"; - public new const string Name = "CopayAuth"; + public new const string Name = "CouponAuth"; - public const string CopayAmountField = "copayAmount"; - public const string CopayAmountColumn = "copayAmount"; + public const string CouponAmountField = "couponAmount"; + public const string CouponAmountColumn = "couponAmount"; public static new readonly Dictionary ColumnsByField = new(global::System.StringComparer.Ordinal) { - ["copayAmount"] = CopayAmountColumn, + ["couponAmount"] = CouponAmountColumn, ["id"] = IdColumn, ["reference"] = ReferenceColumn, ["type"] = TypeColumn, diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PriorAuthAuth.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PermitAuth.g.cs similarity index 82% rename from server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PriorAuthAuth.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PermitAuth.g.cs index a992da743f..6697114272 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PriorAuthAuth.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PermitAuth.g.cs @@ -8,9 +8,9 @@ namespace MetaObjects.IntegrationTests.Generated; -public class PriorAuthAuth : Auth +public class PermitAuth : Auth { - [Column(PriorAuthAuthNames.ApproverColumn)] + [Column(PermitAuthNames.ApproverColumn)] [MaxLength(80)] public string? Approver { get; set; } } diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PriorAuthAuthNames.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PermitAuthNames.g.cs similarity index 78% rename from server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PriorAuthAuthNames.g.cs rename to server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PermitAuthNames.g.cs index 93294c2793..71244657e2 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PriorAuthAuthNames.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/fitness/PermitAuthNames.g.cs @@ -6,13 +6,13 @@ namespace MetaObjects.IntegrationTests.Generated; /// -/// GENERATED — per-object physical database names for PriorAuthAuth (spec A1/A2/A6). +/// GENERATED — per-object physical database names for PermitAuth (spec A1/A2/A6). /// -public abstract class PriorAuthAuthNames : AuthNames +public abstract class PermitAuthNames : AuthNames { public new const string Type = "object"; public new const string SubType = "entity"; - public new const string Name = "PriorAuthAuth"; + public new const string Name = "PermitAuth"; public const string ApproverField = "approver"; public const string ApproverColumn = "approver"; diff --git a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt index e307a00419..3229e37335 100644 --- a/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt +++ b/server/java/codegen-kotlin-exposed1x-check/src/test/kotlin/com/metaobjects/generator/kotlin/exposed1x/Exposed1xControllerCompileTest.kt @@ -35,7 +35,7 @@ import kotlin.test.assertTrue * Generates the FULL shared fitness corpus (not a trimmed selection) with * `exposedApi=1`, using every generator a real build would wire alongside the controller * (Entity, ExposedTable, Names, Relations, FilterAllowlist, Validator, SpringController) so the - * corpus's TPH hierarchy (Auth/Bridge/Copay/PriorAuth/Referral — exercises `emitTph`), its M:N + * corpus's TPH hierarchy (Auth/Bridge/Coupon/Permit/Referral — exercises `emitTph`), its M:N * associations (tags/referrals/following/friends — exercises `emitM2mEndpoint` + * `KotlinRelationsGenerator`'s M:N join helpers), its view projections (exercises * `emitReadOnly`), and its mixed scalar subtypes (string/enum/int-backed-enum/boolean/numeric/ diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt index d45460a02f..e27534e9ae 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupport.kt @@ -34,7 +34,7 @@ object KotlinM2mSupport { /** * FW-3 — the target of an M:N is a TPH subtype: its rows live in the discriminator base's * shared table, so a stage-2 select against that table must be narrowed back to just this - * subtype's rows, or a sibling subtype's row (e.g. a Copay reached through `Auth`'s shared + * subtype's rows, or a sibling subtype's row (e.g. a Coupon reached through `Auth`'s shared * table) comes back tagged as this one. * * @property column the discriminator field's physical column name (on the STORAGE object) diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt index 2e865880db..2367064904 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGenerator.kt @@ -247,7 +247,7 @@ open class KotlinNamesGenerator : } // Inherited constants, re-exported by REFERENCE — the literal is spelled once, // on the base. `const val` folds the reference at compile time, so a consumer - // reading `CopayAuthNames.ID_COLUMN` is unaffected by which object declared it. + // reading `CouponAuthNames.ID_COLUMN` is unaffected by which object declared it. // A TPH subtype's SOURCE members arrive here for the same reason its inherited // columns do: it declares no source of its own, so the own set has none. if (inherited.isNotEmpty()) append("\n") diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index 4004a8fe92..6b229b15e5 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -812,7 +812,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseValidation shape // is built from, so the create/PATCH validated set never drifts from the annotated class. This - // is per-subtype so a PriorAuth patch never touches a Bridge-only column. + // is per-subtype so a Permit patch never touches a Bridge-only column. fun subtypePatchFields(st: KotlinTphPlan.Subtype) = KotlinTphPlan.subtypeSettableFields(st.entity) diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt index 8e4747eb6a..dd8fc00851 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinM2mSupportAbstractMidLevelTargetTest.kt @@ -18,7 +18,7 @@ import kotlin.test.assertNull */ class KotlinM2mSupportAbstractMidLevelTargetTest { - /** `Party` (`@discriminator`) -> abstract `Auth` (mid-level, no @discriminatorValue) -> {BridgeAuth, CopayAuth}. */ + /** `Party` (`@discriminator`) -> abstract `Auth` (mid-level, no @discriminatorValue) -> {BridgeAuth, CouponAuth}. */ private val abstractMidLevelFixture = """{ "metadata.root": { "package": "acme::auth", "children": [ { "object.entity": { "name": "Party", "children": [ @@ -31,14 +31,14 @@ class KotlinM2mSupportAbstractMidLevelTargetTest { { "object.entity": { "name": "Auth", "abstract": true, "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "PartyAuth", "children": [ { "source.rdb": { "@table": "party_auths" } }, diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt index 892ab40ad9..cf93a5b501 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinNamesGeneratorTest.kt @@ -434,26 +434,26 @@ class KotlinNamesGeneratorTest { { "object.entity": { "name": "Auth", "@discriminator": "kind", "children": [ { "source.rdb": { "@table": "zz_auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@values": ["Copay"] } }, + { "field.enum": { "name": "kind", "@values": ["Coupon"] } }, { "identity.primary": { "@fields": ["id"], "@generation": "increment" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ - { "field.long": { "name": "copayAmount", "@column": "zz_copay_cents" } } + { "field.long": { "name": "couponAmount", "@column": "zz_coupon_cents" } } ] } } ] } }""".trimIndent() - val src = emit(model).getValue("acme/CopayAuthNames.kt") + val src = emit(model).getValue("acme/CouponAuthNames.kt") // The subtype declares no source of its own, so every SOURCE_* member lands in the // inherited half and is re-exported by reference from the base. No `inheritsSource` // flag decides that — the own-source map is simply empty, which is the same // structural question answered by the accessor that had to be consulted anyway. assertTrue("const val SOURCE_PRIMARY_TABLE: String = AuthNames.SOURCE_PRIMARY_TABLE" in src, src) assertTrue("const val ID_COLUMN: String = AuthNames.ID_COLUMN" in src, src) - assertTrue("const val COPAY_AMOUNT_COLUMN: String = \"zz_copay_cents\"" in src, src) + assertTrue("const val COUPON_AMOUNT_COLUMN: String = \"zz_coupon_cents\"" in src, src) // ...while its OWN identity is restated, because it differs: `NAME` is the object's - // metamodel name, so the subtype's must say "CopayAuth", not the base's. - assertTrue("const val NAME: String = \"CopayAuth\"" in src, src) + // metamodel name, so the subtype's must say "CouponAuth", not the base's. + assertTrue("const val NAME: String = \"CouponAuth\"" in src, src) // The whole point: the subtype used to restate the base's table name and columns. assertFalse("zz_auths" in src, src) } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt index 472a946aba..eedc4ad991 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinOutputCompilesTest.kt @@ -55,7 +55,7 @@ class KotlinOutputCompilesTest { ] } }""".trimIndent() - // FR-017 TPH regression guard: a subtype's OWN field.enum (CopayAuth.tier) folds into the base + // FR-017 TPH regression guard: a subtype's OWN field.enum (CouponAuth.tier) folds into the base // Auth union data class, so the base must emit that enum class (owner = base) — else the union // references a type no generated file defines. The subtypes themselves emit nothing. private val tphSubtypeEnumFixture = """{ @@ -63,13 +63,13 @@ class KotlinOutputCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ { "field.enum": { "name": "tier", "@values": ["Standard", "Premium"] } } ] } } ] } @@ -87,15 +87,15 @@ class KotlinOutputCompilesTest { // The base emits the union + the discriminator enum + the folded subtype enum; the // subtypes emit NO entity data class or enum of their own (they fold into the base). assertTrue("AuthTier.kt" in names, - "the folded subtype enum (CopayAuth.tier) must be emitted by the base; got $names") - assertFalse("BridgeAuth.kt" in names || "CopayAuth.kt" in names, + "the folded subtype enum (CouponAuth.tier) must be emitted by the base; got $names") + assertFalse("BridgeAuth.kt" in names || "CouponAuth.kt" in names, "TPH subtypes must emit no entity data class of their own; got $names") - assertFalse("BridgeAuthTier.kt" in names || "CopayAuthTier.kt" in names, + assertFalse("BridgeAuthTier.kt" in names || "CouponAuthTier.kt" in names, "a subtype must not re-emit a folded enum under its own name; got $names") // FR-036: each concrete subtype DOES emit a validation-only Validation shape (the // base controller validates per-subtype POST/PATCH present values against it) — BridgeAuth - // has a @required `quantity`, CopayAuth an unconstrained enum `tier`. - assertTrue("BridgeAuthValidation.kt" in names && "CopayAuthValidation.kt" in names, + // has a @required `quantity`, CouponAuth an unconstrained enum `tier`. + assertTrue("BridgeAuthValidation.kt" in names && "CouponAuthValidation.kt" in names, "each concrete TPH subtype must emit its annotated Validation shape; got $names") val result = KotlinCompilation().apply { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt index 2ff2b1bf99..8d0277c9a0 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mCodegenTest.kt @@ -32,7 +32,7 @@ class KotlinTphM2mCodegenTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -43,8 +43,8 @@ class KotlinTphM2mCodegenTest { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -112,9 +112,9 @@ class KotlinTphM2mCodegenTest { assertTrue("@GetMapping(\"/bridge/{id}/tags\")" in src, "expected /bridge/{id}/tags; saw:\n$src") assertTrue("fun tagsBridge(@PathVariable id: Long): ResponseEntity>" in src, "expected tagsBridge() handler; saw:\n$src") - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in src, "expected /copay/{id}/tags; saw:\n$src") - assertTrue("fun tagsCopay(@PathVariable id: Long): ResponseEntity>" in src, - "expected tagsCopay() handler; saw:\n$src") + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in src, "expected /coupon/{id}/tags; saw:\n$src") + assertTrue("fun tagsCoupon(@PathVariable id: Long): ResponseEntity>" in src, + "expected tagsCoupon() handler; saw:\n$src") // Rule (c): Stage 0 verifies the source id names a row of THIS subtype before the SAME // AuthTable.tagsQuery(id) helper the base mount uses — a sibling's id must return []. assertTrue( @@ -138,9 +138,9 @@ class KotlinTphM2mCodegenTest { assertTrue("fun linkedAuthsBridge(@PathVariable id: Long): ResponseEntity>" in src, "expected linkedAuthsBridge() returning List (the storage/union type); saw:\n$src") assertFalse("List" in src, "BridgeAuth has no data class to reference; saw:\n$src") - // linkedAuths is declared on BridgeAuth only — Copay never resolves it. - assertFalse("/copay/{id}/linkedAuths" in src, "Copay must not mount linkedAuths; saw:\n$src") - assertFalse("linkedAuthsCopay" in src, "Copay must not get a linkedAuths handler; saw:\n$src") + // linkedAuths is declared on BridgeAuth only — Coupon never resolves it. + assertFalse("/coupon/{id}/linkedAuths" in src, "Coupon must not mount linkedAuths; saw:\n$src") + assertFalse("linkedAuthsCoupon" in src, "Coupon must not get a linkedAuths handler; saw:\n$src") } @Test fun subtypeOwnRelationTargetingASubtypeBindsToTheStorageTableAndFiltersByDiscriminator() { @@ -171,6 +171,6 @@ class KotlinTphM2mCodegenTest { val src = controller() assertTrue("@RequestMapping(\"/api/auths\")" in src) assertTrue("@GetMapping(\"/bridge\")" in src) - assertTrue("@GetMapping(\"/copay\")" in src) + assertTrue("@GetMapping(\"/coupon\")" in src) } } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt index 59fd54b74d..d339dd1d2b 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinTphM2mShadowedCodegenTest.kt @@ -21,13 +21,13 @@ import kotlin.test.assertTrue * so pre-fix the generated code COMPILES (every reference is a statically valid `Column`, * regardless of which query actually produced the `ResultRow`) but the per-subtype endpoint * calls the WRONG-target shared helper: `AuthTable.tagsQuery(id)` returns rows joined against - * `Tag`/`AuthTag`, then the Copay-scoped endpoint tries to read `SpecialTagTable.*` columns off + * `Tag`/`AuthTag`, then the Coupon-scoped endpoint tries to read `SpecialTagTable.*` columns off * those rows — a `ResultRow` access that is well-typed but throws at RUNTIME (the column was * never selected), or silently maps unrelated data. * * Model: `Auth` (base, `@discriminator: type`) declares a hetero M:N `tags -> Tag` through - * `AuthTag` (resolved unchanged by `BridgeAuth`). `CopayAuth` SHADOWS `tags`, redeclaring it as - * `tags -> SpecialTag` through `CopaySpecialTag` — same relation NAME, genuinely different + * `AuthTag` (resolved unchanged by `BridgeAuth`). `CouponAuth` SHADOWS `tags`, redeclaring it as + * `tags -> SpecialTag` through `CouponSpecialTag` — same relation NAME, genuinely different * target + junction. */ class KotlinTphM2mShadowedCodegenTest { @@ -37,7 +37,7 @@ class KotlinTphM2mShadowedCodegenTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -46,10 +46,10 @@ class KotlinTphM2mShadowedCodegenTest { { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } }, + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", - "@objectRef": "SpecialTag", "@through": "CopaySpecialTag" } } + "@objectRef": "SpecialTag", "@through": "CouponSpecialTag" } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -71,12 +71,12 @@ class KotlinTphM2mShadowedCodegenTest { { "identity.reference": { "name": "fkAuth", "@fields": "authId", "@references": "Auth" } }, { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } ] } }, - { "object.entity": { "name": "CopaySpecialTag", "children": [ - { "source.rdb": { "@table": "copay_special_tags" } }, - { "field.long": { "name": "copayAuthId", "@required": true } }, + { "object.entity": { "name": "CouponSpecialTag", "children": [ + { "source.rdb": { "@table": "coupon_special_tags" } }, + { "field.long": { "name": "couponAuthId", "@required": true } }, { "field.long": { "name": "specialTagId", "@required": true } }, - { "identity.primary": { "@fields": ["copayAuthId", "specialTagId"] } }, - { "identity.reference": { "name": "fkCopay", "@fields": "copayAuthId", "@references": "CopayAuth" } }, + { "identity.primary": { "@fields": ["couponAuthId", "specialTagId"] } }, + { "identity.reference": { "name": "fkCoupon", "@fields": "couponAuthId", "@references": "CouponAuth" } }, { "identity.reference": { "name": "fkSpecialTag", "@fields": "specialTagId", "@references": "SpecialTag" } } ] } } ] } @@ -119,8 +119,8 @@ class KotlinTphM2mShadowedCodegenTest { @Test fun shadowingSubtypeShapeGetsItsOwnDistinctHelper() { val src = relations() - // The shadowing CopayAuth->SpecialTag shape must NOT collapse into tagsQuery — it needs - // its own helper, joining SpecialTagTable/CopaySpecialTagTable, not TagTable/AuthTagTable. + // The shadowing CouponAuth->SpecialTag shape must NOT collapse into tagsQuery — it needs + // its own helper, joining SpecialTagTable/CouponSpecialTagTable, not TagTable/AuthTagTable. assertFalse( src.contains(Regex("""fun AuthTable\.tagsQuery\([^)]*\): Query =\s*\n\s*SpecialTagTable""")), "the shared tagsQuery helper must not join SpecialTagTable; saw:\n$src", @@ -134,34 +134,34 @@ class KotlinTphM2mShadowedCodegenTest { val shadowName = distinctHelpers.first { it != "tags" } val shadowFn = src.substringAfter("fun AuthTable.${shadowName}Query").substringBefore("\n\n") assertTrue("SpecialTagTable" in shadowFn, "expected the shadow helper to join SpecialTagTable; saw:\n$shadowFn") - assertTrue("CopaySpecialTagTable" in shadowFn, "expected the shadow helper to join CopaySpecialTagTable; saw:\n$shadowFn") + assertTrue("CouponSpecialTagTable" in shadowFn, "expected the shadow helper to join CouponSpecialTagTable; saw:\n$shadowFn") assertFalse( "AuthTagTable" in shadowFn, "the shadow helper must not join the BASE shape's junction (AuthTagTable); saw:\n$shadowFn", ) } - // --- controller: the Copay-scoped mount must call ITS OWN helper, not the base's ----- + // --- controller: the Coupon-scoped mount must call ITS OWN helper, not the base's ----- - @Test fun copayScopedMountReturnsSpecialTagAndCallsItsOwnHelper() { + @Test fun couponScopedMountReturnsSpecialTagAndCallsItsOwnHelper() { val src = controller() - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in src, "expected /copay/{id}/tags; saw:\n$src") - assertTrue("fun tagsCopay(@PathVariable id: Long): ResponseEntity>" in src, - "expected tagsCopay() to return List (already correct pre-fix); saw:\n$src") + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in src, "expected /coupon/{id}/tags; saw:\n$src") + assertTrue("fun tagsCoupon(@PathVariable id: Long): ResponseEntity>" in src, + "expected tagsCoupon() to return List (already correct pre-fix); saw:\n$src") - val tagsCopayBody = src.substringAfter("fun tagsCopay(").substringBefore("\n }\n") + val tagsCouponBody = src.substringAfter("fun tagsCoupon(").substringBefore("\n }\n") - // THE regression this fix targets: tagsCopay() must NOT delegate to the base/Bridge + // THE regression this fix targets: tagsCoupon() must NOT delegate to the base/Bridge // shape's AuthTable.tagsQuery(id) helper — that helper joins Tag/AuthTag, not - // SpecialTag/CopaySpecialTag, so reading SpecialTagTable columns off its rows throws + // SpecialTag/CouponSpecialTag, so reading SpecialTagTable columns off its rows throws // at runtime (a well-typed but empty-record-set ResultRow access). - assertFalse("AuthTable.tagsQuery(id)" in tagsCopayBody, - "tagsCopay() must not call the base-shape tagsQuery helper (wrong target/junction); saw:\n$tagsCopayBody") - assertTrue(Regex("""AuthTable\.tags\w+Query\(id\)""").containsMatchIn(tagsCopayBody), - "expected tagsCopay() to call its OWN disambiguated helper; saw:\n$tagsCopayBody") + assertFalse("AuthTable.tagsQuery(id)" in tagsCouponBody, + "tagsCoupon() must not call the base-shape tagsQuery helper (wrong target/junction); saw:\n$tagsCouponBody") + assertTrue(Regex("""AuthTable\.tags\w+Query\(id\)""").containsMatchIn(tagsCouponBody), + "expected tagsCoupon() to call its OWN disambiguated helper; saw:\n$tagsCouponBody") // And the row-mapping columns (already correct pre-fix) must be SpecialTagTable's. - assertTrue("row[SpecialTagTable." in tagsCopayBody, "expected row mapping off SpecialTagTable; saw:\n$tagsCopayBody") + assertTrue("row[SpecialTagTable." in tagsCouponBody, "expected row mapping off SpecialTagTable; saw:\n$tagsCouponBody") } @Test fun bridgeScopedMountIsUnaffectedByTheShadow() { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt index d348c13167..0e45df38f2 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinUuidPrimaryKeyCodegenTest.kt @@ -86,7 +86,7 @@ class KotlinUuidPrimaryKeyCodegenTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.uuid": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "@fields": "id", "@generation": "uuid" } } ] } }, @@ -94,9 +94,9 @@ class KotlinUuidPrimaryKeyCodegenTest { "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", - "@discriminatorValue": "Copay", "children": [ - { "field.string": { "name": "copayCode", "@maxLength": 40 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", + "@discriminatorValue": "Coupon", "children": [ + { "field.string": { "name": "couponCode", "@maxLength": 40 } } ] } } ] } }""".trimIndent() @@ -176,8 +176,8 @@ class KotlinUuidPrimaryKeyCodegenTest { "expected per-subtype getBridge(@PathVariable id: UUID); saw:\n$src") assertTrue("fun updateBridge(@PathVariable id: UUID," in src, "expected per-subtype updateBridge(@PathVariable id: UUID, ...); saw:\n$src") - assertTrue("fun deleteCopay(@PathVariable id: UUID)" in src, - "expected per-subtype deleteCopay(@PathVariable id: UUID); saw:\n$src") + assertTrue("fun deleteCoupon(@PathVariable id: UUID)" in src, + "expected per-subtype deleteCoupon(@PathVariable id: UUID); saw:\n$src") assertTrue("import java.util.UUID" in src, "expected import java.util.UUID; saw:\n$src") assertTrue("@PathVariable id: Long" !in src, diff --git a/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt b/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt index c207c43b62..d33e03f21f 100644 --- a/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt +++ b/server/java/codegen-kotlin/src/test/resources/ejected-at-base/KotlinSpringControllerGenerator.kt.txt @@ -712,7 +712,7 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBaseValidation shape // is built from, so the create/PATCH validated set never drifts from the annotated class. This - // is per-subtype so a PriorAuth patch never touches a Bridge-only column. + // is per-subtype so a Permit patch never touches a Bridge-only column. fun subtypePatchFields(st: KotlinTphPlan.Subtype) = KotlinTphPlan.subtypeSettableFields(st.entity) diff --git a/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json b/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json index 67ce6a00f9..6045a66275 100644 --- a/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json +++ b/server/java/codegen-kotlin/src/test/resources/fixtures/entity-with-tph/meta.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true, "@sortable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"], "@filterable": true } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true, "@sortable": true, "@sortableDefaultOrder": "desc" } }, { "relationship.composition": { "name": "lines", "@cardinality": "many", "@objectRef": "AuthLine", "@onDelete": "cascade" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } @@ -23,19 +23,19 @@ ] }}, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ] }}, { "object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "Auth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ - { "field.string": { "name": "priorAuthNumber", "@maxLength": 80, "@filterable": true, "@sortable": true } } + { "field.string": { "name": "permitNumber", "@maxLength": 80, "@filterable": true, "@sortable": true } } ] }}, { "object.entity": { diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt index e983b04037..e76dac64b7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/Auth.kt @@ -16,8 +16,8 @@ public data class Auth( public val reference: String? = null, public val quantity: Int? = null, @param:JsonDeserialize(using = MetaDecimalWire.Deserializer::class) - public val copayAmount: BigDecimal? = null, - public val priorAuthNumber: String? = null, + public val couponAmount: BigDecimal? = null, + public val permitNumber: String? = null, ) { /** * Fluent builder — lets a JAVA caller set a subset of properties. @@ -31,9 +31,9 @@ public data class Auth( private var quantity: Int? = null - private var copayAmount: BigDecimal? = null + private var couponAmount: BigDecimal? = null - private var priorAuthNumber: String? = null + private var permitNumber: String? = null public fun id(v: Long?): Builder { this.id = v @@ -55,13 +55,13 @@ public data class Auth( return this } - public fun copayAmount(v: BigDecimal?): Builder { - this.copayAmount = v + public fun couponAmount(v: BigDecimal?): Builder { + this.couponAmount = v return this } - public fun priorAuthNumber(v: String?): Builder { - this.priorAuthNumber = v + public fun permitNumber(v: String?): Builder { + this.permitNumber = v return this } @@ -70,8 +70,8 @@ public data class Auth( type = type, reference = reference, quantity = quantity, - copayAmount = copayAmount, - priorAuthNumber = priorAuthNumber + couponAmount = couponAmount, + permitNumber = permitNumber ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt index a796931a9a..1b050ba7e1 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt @@ -156,8 +156,8 @@ private fun coerceAuthValue(field: String, op: String, raw: String): AuthCoerced "type" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) "reference" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) "quantity" -> coerceAuthInt(op, raw) - "copayAmount" -> coerceAuthDecimal(op, raw) - "priorAuthNumber" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) + "couponAmount" -> coerceAuthDecimal(op, raw) + "permitNumber" -> if (op == "in") AuthCoercedValue(raw.split(",").map { it.trim() }) else AuthCoercedValue(raw) else -> null } } @@ -295,24 +295,24 @@ private fun AuthWhereOp(predicates: List): Op? { "isNull" -> if (p.value as Boolean) AuthTable.quantity.isNull() else AuthTable.quantity.isNotNull() else -> throw IllegalStateException("unsupported op for quantity: " + p.op) } - "copayAmount" -> when (p.op) { - "eq" -> AuthTable.copayAmount eq (p.value as BigDecimal) - "ne" -> AuthTable.copayAmount neq (p.value as BigDecimal) - "gt" -> AuthTable.copayAmount greater (p.value as BigDecimal) - "gte" -> AuthTable.copayAmount greaterEq (p.value as BigDecimal) - "lt" -> AuthTable.copayAmount less (p.value as BigDecimal) - "lte" -> AuthTable.copayAmount lessEq (p.value as BigDecimal) - "in" -> AuthTable.copayAmount inList (p.value as List) - "isNull" -> if (p.value as Boolean) AuthTable.copayAmount.isNull() else AuthTable.copayAmount.isNotNull() - else -> throw IllegalStateException("unsupported op for copayAmount: " + p.op) + "couponAmount" -> when (p.op) { + "eq" -> AuthTable.couponAmount eq (p.value as BigDecimal) + "ne" -> AuthTable.couponAmount neq (p.value as BigDecimal) + "gt" -> AuthTable.couponAmount greater (p.value as BigDecimal) + "gte" -> AuthTable.couponAmount greaterEq (p.value as BigDecimal) + "lt" -> AuthTable.couponAmount less (p.value as BigDecimal) + "lte" -> AuthTable.couponAmount lessEq (p.value as BigDecimal) + "in" -> AuthTable.couponAmount inList (p.value as List) + "isNull" -> if (p.value as Boolean) AuthTable.couponAmount.isNull() else AuthTable.couponAmount.isNotNull() + else -> throw IllegalStateException("unsupported op for couponAmount: " + p.op) } - "priorAuthNumber" -> when (p.op) { - "eq" -> AuthTable.priorAuthNumber eq (p.value as String) - "ne" -> AuthTable.priorAuthNumber neq (p.value as String) - "in" -> AuthTable.priorAuthNumber inList (p.value as List) - "like" -> AuthTable.priorAuthNumber like (p.value as String) - "isNull" -> if (p.value as Boolean) AuthTable.priorAuthNumber.isNull() else AuthTable.priorAuthNumber.isNotNull() - else -> throw IllegalStateException("unsupported op for priorAuthNumber: " + p.op) + "permitNumber" -> when (p.op) { + "eq" -> AuthTable.permitNumber eq (p.value as String) + "ne" -> AuthTable.permitNumber neq (p.value as String) + "in" -> AuthTable.permitNumber inList (p.value as List) + "like" -> AuthTable.permitNumber like (p.value as String) + "isNull" -> if (p.value as Boolean) AuthTable.permitNumber.isNull() else AuthTable.permitNumber.isNotNull() + else -> throw IllegalStateException("unsupported op for permitNumber: " + p.op) } else -> continue } @@ -328,8 +328,8 @@ private fun rowToAuth(row: ResultRow): Auth = Auth( type = row[AuthTable.type], reference = row[AuthTable.reference], quantity = row[AuthTable.quantity], - copayAmount = row[AuthTable.copayAmount], - priorAuthNumber = row[AuthTable.priorAuthNumber], + couponAmount = row[AuthTable.couponAmount], + permitNumber = row[AuthTable.permitNumber], ) /** @@ -425,8 +425,8 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat it[type] = AuthType.Bridge it[reference] = dto.reference!! it[quantity] = dto.quantity - it[copayAmount] = dto.copayAmount - it[priorAuthNumber] = dto.priorAuthNumber + it[couponAmount] = dto.couponAmount + it[permitNumber] = dto.permitNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) @@ -465,9 +465,9 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat else ResponseEntity.noContent().build() } - // --- subtype Copay (segment /copay) --- - @GetMapping("/copay") - fun listCopay( + // --- subtype Coupon (segment /coupon) --- + @GetMapping("/coupon") + fun listCoupon( @RequestParam(required = false) limit: Int?, @RequestParam(required = false) offset: Int?, @RequestParam(required = false) sort: String?, @@ -477,7 +477,7 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf("error" to filterResult.error, "field" to filterResult.field) as Any) val whereOp = AuthWhereOp(filterResult.predicates) var q = AuthTable.selectAll().where { - val d = AuthTable.type eq AuthType.Copay + val d = AuthTable.type eq AuthType.Coupon if (whereOp != null) d and whereOp else d } if (sort != null) { @@ -495,66 +495,66 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat ResponseEntity.ok(rows as Any) } - @GetMapping("/copay/{id}") - fun getCopay(@PathVariable id: Long): ResponseEntity = transaction { - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) }.singleOrNull() + @GetMapping("/coupon/{id}") + fun getCoupon(@PathVariable id: Long): ResponseEntity = transaction { + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) }.singleOrNull() ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) ResponseEntity.ok(rowToAuth(row) as Any) } - @PostMapping("/copay") - fun createCopay(@RequestBody dto: Auth): ResponseEntity = transaction { - if (validator.validateValue(CopayAuthValidation::class.java, "copayAmount", dto.copayAmount).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - if (!MetaDecimalWire.fits(dto.copayAmount, 10, 2)) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation", "field" to "copayAmount") as Any) - if (validator.validateValue(CopayAuthValidation::class.java, "reference", dto.reference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + @PostMapping("/coupon") + fun createCoupon(@RequestBody dto: Auth): ResponseEntity = transaction { + if (validator.validateValue(CouponAuthValidation::class.java, "couponAmount", dto.couponAmount).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + if (!MetaDecimalWire.fits(dto.couponAmount, 10, 2)) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation", "field" to "couponAmount") as Any) + if (validator.validateValue(CouponAuthValidation::class.java, "reference", dto.reference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) val newId = AuthTable.insert { - it[type] = AuthType.Copay + it[type] = AuthType.Coupon it[reference] = dto.reference!! it[quantity] = dto.quantity - it[copayAmount] = dto.copayAmount - it[priorAuthNumber] = dto.priorAuthNumber + it[couponAmount] = dto.couponAmount + it[permitNumber] = dto.permitNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) } - @RequestMapping(value = ["/copay/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) - fun updateCopay(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { + @RequestMapping(value = ["/coupon/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) + fun updateCoupon(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { if (!body.isObject) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) if (body.has("reference") && body.get("reference").isNull) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - if (listOf("copayAmount", "reference").any { body.has(it) }) { + if (listOf("couponAmount", "reference").any { body.has(it) }) { try { - val hasCopayAmount = body.has("copayAmount") - val nullCopayAmount = hasCopayAmount && body.get("copayAmount").isNull - val vCopayAmount: java.math.BigDecimal? = if (hasCopayAmount && !nullCopayAmount) runCatching { MetaDecimalWire.fromNode(body.get("copayAmount")) }.getOrElse { return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation", "field" to "copayAmount") as Any) } else null - if (hasCopayAmount && !nullCopayAmount && validator.validateValue(CopayAuthValidation::class.java, "copayAmount", vCopayAmount).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - if (!MetaDecimalWire.fits(vCopayAmount, 10, 2)) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation", "field" to "copayAmount") as Any) + val hasCouponAmount = body.has("couponAmount") + val nullCouponAmount = hasCouponAmount && body.get("couponAmount").isNull + val vCouponAmount: java.math.BigDecimal? = if (hasCouponAmount && !nullCouponAmount) runCatching { MetaDecimalWire.fromNode(body.get("couponAmount")) }.getOrElse { return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation", "field" to "couponAmount") as Any) } else null + if (hasCouponAmount && !nullCouponAmount && validator.validateValue(CouponAuthValidation::class.java, "couponAmount", vCouponAmount).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + if (!MetaDecimalWire.fits(vCouponAmount, 10, 2)) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation", "field" to "couponAmount") as Any) val hasReference = body.has("reference") val vReference: kotlin.String? = if (hasReference) objectMapper.treeToValue(body.get("reference"), object : TypeReference() {}) else null - if (hasReference && validator.validateValue(CopayAuthValidation::class.java, "reference", vReference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) }) { - if (hasCopayAmount) { if (nullCopayAmount) it[AuthTable.copayAmount] = null else it[AuthTable.copayAmount] = vCopayAmount } + if (hasReference && validator.validateValue(CouponAuthValidation::class.java, "reference", vReference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) }) { + if (hasCouponAmount) { if (nullCouponAmount) it[AuthTable.couponAmount] = null else it[AuthTable.couponAmount] = vCouponAmount } if (hasReference) it[AuthTable.reference] = vReference!! } } catch (e: com.fasterxml.jackson.databind.JsonMappingException) { return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) } } - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) }.singleOrNull() + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) }.singleOrNull() if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.ok(rowToAuth(row) as Any) } - @DeleteMapping("/copay/{id}") - fun deleteCopay(@PathVariable id: Long): ResponseEntity = transaction { - val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Copay) } } + @DeleteMapping("/coupon/{id}") + fun deleteCoupon(@PathVariable id: Long): ResponseEntity = transaction { + val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Coupon) } } if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.noContent().build() } - // --- subtype PriorAuth (segment /priorauth) --- - @GetMapping("/priorauth") - fun listPriorAuth( + // --- subtype Permit (segment /permit) --- + @GetMapping("/permit") + fun listPermit( @RequestParam(required = false) limit: Int?, @RequestParam(required = false) offset: Int?, @RequestParam(required = false) sort: String?, @@ -564,7 +564,7 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat if (filterResult.error != null) return@transaction ResponseEntity.badRequest().body(mapOf("error" to filterResult.error, "field" to filterResult.field) as Any) val whereOp = AuthWhereOp(filterResult.predicates) var q = AuthTable.selectAll().where { - val d = AuthTable.type eq AuthType.PriorAuth + val d = AuthTable.type eq AuthType.Permit if (whereOp != null) d and whereOp else d } if (sort != null) { @@ -582,57 +582,57 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat ResponseEntity.ok(rows as Any) } - @GetMapping("/priorauth/{id}") - fun getPriorAuth(@PathVariable id: Long): ResponseEntity = transaction { - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) }.singleOrNull() + @GetMapping("/permit/{id}") + fun getPermit(@PathVariable id: Long): ResponseEntity = transaction { + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) }.singleOrNull() ?: return@transaction ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) ResponseEntity.ok(rowToAuth(row) as Any) } - @PostMapping("/priorauth") - fun createPriorAuth(@RequestBody dto: Auth): ResponseEntity = transaction { - if (validator.validateValue(PriorAuthAuthValidation::class.java, "priorAuthNumber", dto.priorAuthNumber).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - if (validator.validateValue(PriorAuthAuthValidation::class.java, "reference", dto.reference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + @PostMapping("/permit") + fun createPermit(@RequestBody dto: Auth): ResponseEntity = transaction { + if (validator.validateValue(PermitAuthValidation::class.java, "permitNumber", dto.permitNumber).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + if (validator.validateValue(PermitAuthValidation::class.java, "reference", dto.reference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) val newId = AuthTable.insert { - it[type] = AuthType.PriorAuth + it[type] = AuthType.Permit it[reference] = dto.reference!! it[quantity] = dto.quantity - it[copayAmount] = dto.copayAmount - it[priorAuthNumber] = dto.priorAuthNumber + it[couponAmount] = dto.couponAmount + it[permitNumber] = dto.permitNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) } - @RequestMapping(value = ["/priorauth/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) - fun updatePriorAuth(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { + @RequestMapping(value = ["/permit/{id}"], method = [RequestMethod.PATCH, RequestMethod.PUT]) + fun updatePermit(@PathVariable id: Long, @RequestBody body: JsonNode): ResponseEntity = transaction { if (!body.isObject) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) if (body.has("reference") && body.get("reference").isNull) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - if (listOf("priorAuthNumber", "reference").any { body.has(it) }) { + if (listOf("permitNumber", "reference").any { body.has(it) }) { try { - val hasPriorAuthNumber = body.has("priorAuthNumber") - val nullPriorAuthNumber = hasPriorAuthNumber && body.get("priorAuthNumber").isNull - val vPriorAuthNumber: kotlin.String? = if (hasPriorAuthNumber && !nullPriorAuthNumber) objectMapper.treeToValue(body.get("priorAuthNumber"), object : TypeReference() {}) else null - if (hasPriorAuthNumber && !nullPriorAuthNumber && validator.validateValue(PriorAuthAuthValidation::class.java, "priorAuthNumber", vPriorAuthNumber).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + val hasPermitNumber = body.has("permitNumber") + val nullPermitNumber = hasPermitNumber && body.get("permitNumber").isNull + val vPermitNumber: kotlin.String? = if (hasPermitNumber && !nullPermitNumber) objectMapper.treeToValue(body.get("permitNumber"), object : TypeReference() {}) else null + if (hasPermitNumber && !nullPermitNumber && validator.validateValue(PermitAuthValidation::class.java, "permitNumber", vPermitNumber).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) val hasReference = body.has("reference") val vReference: kotlin.String? = if (hasReference) objectMapper.treeToValue(body.get("reference"), object : TypeReference() {}) else null - if (hasReference && validator.validateValue(PriorAuthAuthValidation::class.java, "reference", vReference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) - AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) }) { - if (hasPriorAuthNumber) { if (nullPriorAuthNumber) it[AuthTable.priorAuthNumber] = null else it[AuthTable.priorAuthNumber] = vPriorAuthNumber } + if (hasReference && validator.validateValue(PermitAuthValidation::class.java, "reference", vReference).isNotEmpty()) return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) + AuthTable.update({ (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) }) { + if (hasPermitNumber) { if (nullPermitNumber) it[AuthTable.permitNumber] = null else it[AuthTable.permitNumber] = vPermitNumber } if (hasReference) it[AuthTable.reference] = vReference!! } } catch (e: com.fasterxml.jackson.databind.JsonMappingException) { return@transaction ResponseEntity.badRequest().body(mapOf("error" to "validation") as Any) } } - val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) }.singleOrNull() + val row = AuthTable.selectAll().where { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) }.singleOrNull() if (row == null) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.ok(rowToAuth(row) as Any) } - @DeleteMapping("/priorauth/{id}") - fun deletePriorAuth(@PathVariable id: Long): ResponseEntity = transaction { - val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.PriorAuth) } } + @DeleteMapping("/permit/{id}") + fun deletePermit(@PathVariable id: Long): ResponseEntity = transaction { + val deleted = AuthTable.deleteWhere { with(SqlExpressionBuilder) { (AuthTable.id eq id) and (AuthTable.type eq AuthType.Permit) } } if (deleted == 0) ResponseEntity.status(HttpStatus.NOT_FOUND).body(mapOf("error" to "not_found") as Any) else ResponseEntity.noContent().build() } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt index 98d49ef76c..d02fcc202b 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthFilterAllowlist.kt @@ -11,8 +11,8 @@ object AuthFilterAllowlist { "type", "reference", "quantity", - "copayAmount", - "priorAuthNumber", + "couponAmount", + "permitNumber", ) val OPS_BY_FIELD: Map> = mapOf( @@ -20,7 +20,7 @@ object AuthFilterAllowlist { "type" to setOf("eq", "ne", "in", "like", "isNull"), "reference" to setOf("eq", "ne", "in", "like", "isNull"), "quantity" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "copayAmount" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), - "priorAuthNumber" to setOf("eq", "ne", "in", "like", "isNull") + "couponAmount" to setOf("eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"), + "permitNumber" to setOf("eq", "ne", "in", "like", "isNull") ) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt index fef003a3be..205dda5cc0 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthTable.kt @@ -8,8 +8,8 @@ object AuthTable : Table("auths") { val type = enumerationByName("type", 64, AuthType::class).nullable() val reference = varchar("reference", 80) val quantity = integer("quantity").nullable() - val copayAmount = portableDecimal("copay_amount", 10, 2).nullable() - val priorAuthNumber = varchar("prior_auth_number", 80).nullable() + val couponAmount = portableDecimal("coupon_amount", 10, 2).nullable() + val permitNumber = varchar("permit_number", 80).nullable() override val primaryKey = PrimaryKey(id) } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt index 8b0dd0211a..e4bea82374 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthType.kt @@ -8,6 +8,6 @@ import kotlinx.serialization.Serializable @Serializable public enum class AuthType { Bridge, - Copay, - PriorAuth, + Coupon, + Permit, } diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CopayAuthValidation.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CouponAuthValidation.kt similarity index 73% rename from server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CopayAuthValidation.kt rename to server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CouponAuthValidation.kt index ec665b3de8..adc4da3bd7 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CopayAuthValidation.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/CouponAuthValidation.kt @@ -7,12 +7,12 @@ import kotlin.String /** * GENERATED — do not hand-edit. Regenerated from metadata. - * FR-036 validation-only shape for the CopayAuth TPH subtype: the base controller's + * FR-036 validation-only shape for the CouponAuth TPH subtype: the base controller's * per-subtype POST/PATCH validates present values against these field constraints * (the folded union base data class is annotation-free). Never persisted or bound. */ -public data class CopayAuthValidation( - public val copayAmount: BigDecimal? = null, +public data class CouponAuthValidation( + public val couponAmount: BigDecimal? = null, @field:NotNull @field:Size(min = 1, max = 80) public val reference: String? = null, diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PriorAuthAuthValidation.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PermitAuthValidation.kt similarity index 73% rename from server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PriorAuthAuthValidation.kt rename to server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PermitAuthValidation.kt index e51e608de8..ce1dcfc7bb 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PriorAuthAuthValidation.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/PermitAuthValidation.kt @@ -6,13 +6,13 @@ import kotlin.String /** * GENERATED — do not hand-edit. Regenerated from metadata. - * FR-036 validation-only shape for the PriorAuthAuth TPH subtype: the base controller's + * FR-036 validation-only shape for the PermitAuth TPH subtype: the base controller's * per-subtype POST/PATCH validates present values against these field constraints * (the folded union base data class is annotation-free). Never persisted or bound. */ -public data class PriorAuthAuthValidation( +public data class PermitAuthValidation( @field:Size(max = 80) - public val priorAuthNumber: String? = null, + public val permitNumber: String? = null, @field:NotNull @field:Size(min = 1, max = 80) public val reference: String? = null, diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java index f8d94b1365..ee454e39f1 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringNamesGenerator.java @@ -601,7 +601,7 @@ protected boolean emit(MetaObject entity, Path outRoot, String strategy, boolean src.append(" * GENERATED — per-object physical database names for ").append(shortName).append(".\n"); src.append(" */\n"); // `abstract`, not `final`: this class is now a base other names classes extend - // rather than restate. Java inherits static members, so `CopayAuthNames.ID_COLUMN` + // rather than restate. Java inherits static members, so `CouponAuthNames.ID_COLUMN` // resolves through the base and every consumption site is unchanged; `abstract` // keeps the "no instances" guarantee `final` + a private constructor used to give, // while still allowing a subclass. diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java index 3d45060758..b98e7cc157 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/TphPlan.java @@ -39,7 +39,7 @@ public record Plan(MetaObject base, String discriminatorField, List sub /** * The per-subtype REST route segment for a discriminator value — the ONE place this rule * lives: the value lowercased ({@code "Bridge"} → {@code bridge}, - * {@code "PriorAuth"} → {@code priorauth}). + * {@code "Permit"} → {@code permit}). */ public static String routeSegment(String discriminatorValue) { return discriminatorValue.toLowerCase(Locale.ROOT); diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java index b72e34d363..b701a77c45 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/GeneratedTphM2mTraversalCompileRunTest.java @@ -74,8 +74,8 @@ public class GeneratedTphM2mTraversalCompileRunTest { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -121,9 +121,9 @@ public void generatedTphFindersEnforceBaseWideAndSubtypeScopedContracts() throws Map seed = Map.of( "auths", List.of( Map.of("id", 1, "type", "Bridge", "reference", "b1"), - Map.of("id", 2, "type", "Copay", "reference", "c1")), + Map.of("id", 2, "type", "Coupon", "reference", "c1")), "tags", List.of(Map.of("id", 10, "name", "red"), Map.of("id", 20, "name", "green")), - // auth 1 (Bridge) -> tag 10; auth 2 (Copay) -> tag 20. + // auth 1 (Bridge) -> tag 10; auth 2 (Coupon) -> tag 20. "auth_tags", List.of(Map.of("authId", 1, "tagId", 10), Map.of("authId", 2, "tagId", 20)), // auth 1 (Bridge) links to auth 2 — a hetero-looking row, but AuthLink only // ever references BridgeAuth ids on both sides by the fixture's own FK. @@ -135,21 +135,21 @@ public void generatedTphFindersEnforceBaseWideAndSubtypeScopedContracts() throws rows(seed, "auths"), rows(seed, "tags"), rows(seed, "auth_tags"), rows(seed, "auth_links")); // Rule (a): a base-declared relationship's finder is UNSCOPED — every row, - // Bridge or Copay, is a legitimate source. + // Bridge or Coupon, is a legitimate source. assertNamesEqual(List.of("red"), invokeFinder(repo, "findTags", 1L)); assertNamesEqual(List.of("green"), invokeFinder(repo, "findTags", 2L)); // Rule (b)+(c): the Bridge-scoped finder answers for a REAL Bridge id... assertNamesEqual(List.of("red"), invokeFinder(repo, "findTagsForBridge", 1L)); // ...and returns EMPTY — not the sibling's rows, not an exception — for a - // Copay id, because the junction FK cannot itself distinguish the subtypes. + // Coupon id, because the junction FK cannot itself distinguish the subtypes. assertNamesEqual(List.of(), invokeFinder(repo, "findTagsForBridge", 2L)); - // Symmetric proof on the Copay-scoped finder. - assertNamesEqual(List.of("green"), invokeFinder(repo, "findTagsForCopay", 2L)); - assertNamesEqual(List.of(), invokeFinder(repo, "findTagsForCopay", 1L)); + // Symmetric proof on the Coupon-scoped finder. + assertNamesEqual(List.of("green"), invokeFinder(repo, "findTagsForCoupon", 2L)); + assertNamesEqual(List.of(), invokeFinder(repo, "findTagsForCoupon", 1L)); // Subtype-OWN relationship (linkedAuths, self-join on BridgeAuth): resolves for - // a real Bridge id, empty for the Copay id. The target — BridgeAuth itself — is + // a real Bridge id, empty for the Coupon id. The target — BridgeAuth itself — is // ALSO a concrete TPH subtype, so the finder now takes the build-time-resolved // "Bridge" literal as a second argument (FW-8 follow-up, target-side gate). assertReferencesEqual(List.of("b1"), invokeFinderWithSubtype(repo, "findLinkedAuthsForBridge", 1L, "Bridge")); @@ -165,13 +165,13 @@ public void generatedTphFindersEnforceBaseWideAndSubtypeScopedContracts() throws * implementation that actually USES it to filter the join returns only rows of that * subtype, never a same-table sibling's. {@code linkedAuths}' {@code @objectRef} names * {@code BridgeAuth} — a concrete TPH subtype of {@code Auth} — so its rows physically - * share the {@code auths} table with {@code CopayAuth} rows; nothing in the junction FK + * share the {@code auths} table with {@code CouponAuth} rows; nothing in the junction FK * itself (a plain {@code Long} id) can distinguish them. Unlike the SOURCE-side rule (c), * Java's generated controller CANNOT enforce this itself (the join is entirely * consumer-owned) — the seam can only be WIDENED so a conforming implementation has what * it needs, exactly the same limitation the Python port documents for its own * {@code target_subtype} parameter. This test's junction data is deliberately corrupted - * (a link row pointing at a same-table Copay row) to prove a conforming, FILTERING + * (a link row pointing at a same-table Coupon row) to prove a conforming, FILTERING * repository correctly excludes it once it is handed {@code "Bridge"}. */ @Test @@ -194,12 +194,12 @@ public void generatedControllerThreadsTheResolvedTargetDiscriminatorLiteralToAFi Map seed = Map.of( "auths", List.of( Map.of("id", 1, "type", "Bridge", "reference", "b1"), - Map.of("id", 2, "type", "Copay", "reference", "c1")), + Map.of("id", 2, "type", "Coupon", "reference", "c1")), "tags", List.of(), "auth_tags", List.of(), // auth 1 (Bridge) links to itself (a GENUINE Bridge target) AND — a corrupted row // that should never exist under a correctly-enforced physical schema — to auth 2, - // whose type is Copay. Nothing in the junction FK's plain Long id distinguishes them. + // whose type is Coupon. Nothing in the junction FK's plain Long id distinguishes them. "auth_links", List.of( Map.of("fromAuthId", 1, "toAuthId", 1), Map.of("fromAuthId", 1, "toAuthId", 2))); @@ -216,7 +216,7 @@ public void generatedControllerThreadsTheResolvedTargetDiscriminatorLiteralToAFi Object controller = ctor.newInstance(repo, new ObjectMapper(), validator); // Direct repository call: the FILTERING implementation excludes the corrupted - // Copay-typed target even though the junction row itself does not. + // Coupon-typed target even though the junction row itself does not. assertReferencesEqual(List.of("b1"), invokeFinderWithSubtype(repo, "findLinkedAuthsForBridge", 1L, "Bridge")); @@ -231,7 +231,7 @@ public void generatedControllerThreadsTheResolvedTargetDiscriminatorLiteralToAFi /** * The distinguishing test: enforcement, not delegation. {@link NaiveAuthRepository}'s - * {@code findTagsForBridge}/{@code findTagsForCopay} are a copy-paste of the UNSCOPED + * {@code findTagsForBridge}/{@code findTagsForCoupon} are a copy-paste of the UNSCOPED * {@code findTags} — no discriminator check at all — which javac, the repository * interface's type system, and a corpus scenario against a delegating port all wave * through. Only the GENERATED CONTROLLER's own composition of @@ -264,7 +264,7 @@ public void generatedControllerEnforcesTheGateEvenWhenTheRepositoryDoesNotFilter Map seed = Map.of( "auths", List.of( Map.of("id", 1, "type", "Bridge", "reference", "b1"), - Map.of("id", 2, "type", "Copay", "reference", "c1")), + Map.of("id", 2, "type", "Coupon", "reference", "c1")), "tags", List.of(Map.of("id", 10, "name", "red"), Map.of("id", 20, "name", "green")), "auth_tags", List.of(Map.of("authId", 1, "tagId", 10), Map.of("authId", 2, "tagId", 20))); @@ -285,8 +285,8 @@ public void generatedControllerEnforcesTheGateEvenWhenTheRepositoryDoesNotFilter assertEquals(200, bridgeResp.getStatusCode().value()); assertNamesEqual(List.of("red"), (List) bridgeResp.getBody()); - // The Copay id: NaiveAuthRepository.findTagsForBridge would happily return the - // Copay's OWN tags (["green"]) if the controller ever called it — it has no + // The Coupon id: NaiveAuthRepository.findTagsForBridge would happily return the + // Coupon's OWN tags (["green"]) if the controller ever called it — it has no // discriminator check of its own. It must NOT be called: the controller's // findByIdAndType(2, "Bridge") composition returns empty first, short-circuiting // to [] before the naive finder runs. @@ -294,8 +294,8 @@ public void generatedControllerEnforcesTheGateEvenWhenTheRepositoryDoesNotFilter assertEquals(200, mismatchResp.getStatusCode().value()); assertNamesEqual(List.of(), (List) mismatchResp.getBody()); - // Mirror on the Copay-scoped finder with the Bridge id. - ResponseEntity mismatchResp2 = invokeControllerFinder(controller, "findTagsForCopay", 1L); + // Mirror on the Coupon-scoped finder with the Bridge id. + ResponseEntity mismatchResp2 = invokeControllerFinder(controller, "findTagsForCoupon", 1L); assertEquals(200, mismatchResp2.getStatusCode().value()); assertNamesEqual(List.of(), (List) mismatchResp2.getBody()); } @@ -441,8 +441,8 @@ public InMemoryAuthRepository(List> authRows, return isType(sourceId, "Bridge") ? tagsFor(sourceId) : List.of(); } - @Override public List findTagsForCopay(Long sourceId) { - return isType(sourceId, "Copay") ? tagsFor(sourceId) : List.of(); + @Override public List findTagsForCoupon(Long sourceId) { + return isType(sourceId, "Coupon") ? tagsFor(sourceId) : List.of(); } // Subtype-OWN "linkedAuths" (directed self-join through AuthLink). The relationship's @@ -550,7 +550,7 @@ public NaiveAuthRepository(List> authRows, // must not ship this, but nothing except the generated controller's own gate // stops it from doing so and still passing every OTHER test. @Override public List findTagsForBridge(Long sourceId) { return tagsFor(sourceId); } - @Override public List findTagsForCopay(Long sourceId) { return tagsFor(sourceId); } + @Override public List findTagsForCoupon(Long sourceId) { return tagsFor(sourceId); } @Override public List findLinkedAuthsForBridge(Long sourceId, String targetSubtype) { return List.of(); } private List tagsFor(Long sourceId) { @@ -631,7 +631,7 @@ public FilteringAuthRepository(List> authRows, @Override public List findTags(Long sourceId) { return List.of(); } @Override public List findTagsForBridge(Long sourceId) { return List.of(); } - @Override public List findTagsForCopay(Long sourceId) { return List.of(); } + @Override public List findTagsForCoupon(Long sourceId) { return List.of(); } // The load-bearing method: filters the joined targets down to rows whose OWN // discriminator matches the literal the generated controller now hands in — diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java index 7fdc79331e..2968104279 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringAutoSetStampingTest.java @@ -340,7 +340,7 @@ public void tphUnionDtoAndSubPatchCarryTheStampingHelpers() throws Exception { Path classesDir = tmp.newFolder("tph-classes").toPath(); MetaDataLoader loader = SpringTestFixtures.loadFixture(tmp.newFolder("tph-fx").toPath(), "auth", TPH_AUTOSET_JSON); runGenerator(new SpringDtoGenerator(), loader, srcDir); - // Real javac compile of the DTO layer (AuthDto + BridgeAuthDto/Copay.../Patch) — not just + // Real javac compile of the DTO layer (AuthDto + BridgeAuthDto/Coupon.../Patch) — not just // string assertions. Catches exactly the class of bug found while implementing this: a // subtype-typed stampForInsert(BridgeAuthDto) would NOT type-check if the controller ever // called it with an AuthDto argument (the union type repository.createWithType binds). diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java index 675ad1e215..55e57a2f1a 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringCreateDefaultsTest.java @@ -152,14 +152,14 @@ private Object build(String meta, String name, String repoFqn, String controller { "metadata.root": { "package": "acme::auth", "children": [ { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", "@values": ["OPEN", "SHUT"], "@default": "SHUT" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "acme::auth::Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@default": 3 } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "acme::auth::Auth", "@discriminatorValue": "Copay", + { "object.entity": { "name": "CouponAuth", "extends": "acme::auth::Auth", "@discriminatorValue": "Coupon", "children": [ { "field.int": { "name": "amount" } } ] } } ] } } """; diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java index 8b6100fe06..1743ac404b 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringFilterAllowlistGeneratorTest.java @@ -158,14 +158,14 @@ public void operatorGatingPerSubtype() throws Exception { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"], "@filterable": true } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"], "@filterable": true } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@filterable": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } } ] } } ] } } @@ -183,8 +183,8 @@ public void aTphSubtypeDecimalIsFilterableAndParsedExactly() throws Exception { gen.execute(loader); String src = Files.readString(outDir.resolve("acme/auth/AuthFilterAllowlist.java")); - assertTrue(src, src.contains("\"copayAmount\"")); - assertTrue(src, src.contains("DECIMAL_FIELDS = Set.of(\"copayAmount\")")); + assertTrue(src, src.contains("\"couponAmount\"")); + assertTrue(src, src.contains("DECIMAL_FIELDS = Set.of(\"couponAmount\")")); assertTrue(src, src.contains("\"quantity\"")); } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java index bc7a7c4b4e..6e5a475982 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringM2mTargetTphCodegenTest.java @@ -21,9 +21,9 @@ * non-TPH entity) declares a hetero M:N {@code bridgeAuths -> BridgeAuth}, where * {@code BridgeAuth} is a CONCRETE TPH subtype of {@code Auth} * ({@code @discriminatorValue: "Bridge"}). {@code BridgeAuth}'s rows physically - * live in the shared {@code auths} table alongside {@code CopayAuth} rows, so an + * live in the shared {@code auths} table alongside {@code CouponAuth} rows, so an * unscoped junction traversal cannot itself tell a genuine Bridge row from a - * same-table Copay row. Java's repository interface is consumer-implemented — it + * same-table Coupon row. Java's repository interface is consumer-implemented — it * cannot AND a discriminator into a join it does not write — so the fix widens the * finder seam with a build-time-literal {@code targetSubtype} argument, exactly as * for the self-join case in {@link SpringTphM2mCodegenTest}, but here proving the @@ -41,15 +41,15 @@ public class SpringM2mTargetTphCodegenTest extends SharedRegistryTestBase { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Sponsor", "children": [ { "source.rdb": { "@table": "sponsors" } }, diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java index 82d363976f..37597aa938 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mCodegenTest.java @@ -26,7 +26,7 @@ * {@code tags -> Tag} through {@code AuthTag} — resolved by the base AND, inherited, by * every concrete subtype. {@code BridgeAuth} ALSO declares its own directed self-join M:N * {@code linkedAuths -> BridgeAuth} through {@code AuthLink} — resolved by Bridge only. - * {@code CopayAuth} declares no M:N of its own.

    + * {@code CouponAuth} declares no M:N of its own.

    */ public class SpringTphM2mCodegenTest extends SharedRegistryTestBase { @@ -39,7 +39,7 @@ public class SpringTphM2mCodegenTest extends SharedRegistryTestBase { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -50,8 +50,8 @@ public class SpringTphM2mCodegenTest extends SharedRegistryTestBase { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -109,8 +109,8 @@ public void repositoryEmitsSubtypeScopedFinderForInheritedRelation() throws Exce String src = generate(new SpringRepositoryGenerator(), loadFixture(), "acme/auth/AuthRepository.java"); assertTrue("expected Bridge-scoped findTagsForBridge; saw:\n" + src, src.contains("List findTagsForBridge(Long sourceId);")); - assertTrue("expected Copay-scoped findTagsForCopay; saw:\n" + src, - src.contains("List findTagsForCopay(Long sourceId);")); + assertTrue("expected Coupon-scoped findTagsForCoupon; saw:\n" + src, + src.contains("List findTagsForCoupon(Long sourceId);")); } @Test @@ -120,12 +120,12 @@ public void repositoryEmitsSubtypeScopedFinderForSubtypeOwnRelation() throws Exc // finder also carries the target-subtype gate (FW-8 follow-up) — see // repositoryFinderForTphSubtypeTargetGainsTargetSubtypeParam below for the dedicated // coverage of that gate; this test's own concern is unchanged (subtype-OWN relation - // scoping + the Copay exclusion). + // scoping + the Coupon exclusion). assertTrue("expected Bridge-scoped findLinkedAuthsForBridge; saw:\n" + src, src.contains("List findLinkedAuthsForBridge(Long sourceId, String targetSubtype);")); - // linkedAuths is declared on BridgeAuth only — Copay never resolves it. - assertFalse("Copay must not get a linkedAuths finder; saw:\n" + src, - src.contains("findLinkedAuthsForCopay")); + // linkedAuths is declared on BridgeAuth only — Coupon never resolves it. + assertFalse("Coupon must not get a linkedAuths finder; saw:\n" + src, + src.contains("findLinkedAuthsForCoupon")); } // --- controller ------------------------------------------------------ @@ -151,10 +151,10 @@ public void controllerMountsInheritedRelationUnderEachSubtypeSegment() throws Ex assertTrue("expected repository.findTagsForBridge(id); saw:\n" + src, src.contains("repository.findTagsForBridge(id)")); - assertTrue("expected /copay/{id}/tags; saw:\n" + src, - src.contains("@GetMapping(\"/copay/{id}/tags\")")); - assertTrue("expected findTagsForCopay delegate; saw:\n" + src, - src.contains("public ResponseEntity> findTagsForCopay(@PathVariable Long id)")); + assertTrue("expected /coupon/{id}/tags; saw:\n" + src, + src.contains("@GetMapping(\"/coupon/{id}/tags\")")); + assertTrue("expected findTagsForCoupon delegate; saw:\n" + src, + src.contains("public ResponseEntity> findTagsForCoupon(@PathVariable Long id)")); } @Test @@ -164,11 +164,11 @@ public void controllerMountsSubtypeOwnRelationOnlyUnderItsOwnSegment() throws Ex src.contains("@GetMapping(\"/bridge/{id}/linkedAuths\")")); assertTrue("expected findLinkedAuthsForBridge delegate; saw:\n" + src, src.contains("public ResponseEntity> findLinkedAuthsForBridge(@PathVariable Long id)")); - // Copay resolves no linkedAuths relationship — no mount, no finder reference. - assertFalse("Copay must not mount /copay/{id}/linkedAuths; saw:\n" + src, - src.contains("/copay/{id}/linkedAuths")); - assertFalse("Copay must not reference a linkedAuths finder; saw:\n" + src, - src.contains("findLinkedAuthsForCopay")); + // Coupon resolves no linkedAuths relationship — no mount, no finder reference. + assertFalse("Coupon must not mount /coupon/{id}/linkedAuths; saw:\n" + src, + src.contains("/coupon/{id}/linkedAuths")); + assertFalse("Coupon must not reference a linkedAuths finder; saw:\n" + src, + src.contains("findLinkedAuthsForCoupon")); } @Test @@ -176,7 +176,7 @@ public void polymorphicAndPerSubtypeCrudMountsAreStillEmitted() throws Exception String src = generate(new SpringControllerGenerator(), loadFixture(), "acme/auth/AuthController.java"); assertTrue(src.contains("@GetMapping\n public ResponseEntity list(")); assertTrue(src.contains("@GetMapping(\"/bridge\")")); - assertTrue(src.contains("@GetMapping(\"/copay\")")); + assertTrue(src.contains("@GetMapping(\"/coupon\")")); } // --- target-side TPH gate (FW-8 follow-up) -------------------------- @@ -184,7 +184,7 @@ public void polymorphicAndPerSubtypeCrudMountsAreStillEmitted() throws Exception // linkedAuths' @objectRef is "BridgeAuth" — a CONCRETE TPH subtype of Auth // (@discriminatorValue "Bridge"). BridgeAuth's rows physically live in the // shared `auths` table, so an unscoped junction traversal cannot itself tell - // a genuine Bridge target from a same-table Copay row; Java cannot AND a + // a genuine Bridge target from a same-table Coupon row; Java cannot AND a // discriminator into a join it does not write (the interface is // consumer-implemented), so the fix widens the finder seam with a // build-time-literal `targetSubtype` argument (mirrors the Python @@ -215,14 +215,14 @@ public void nonTphTargetFindersStayUnwidened() throws Exception { String repoSrc = generate(new SpringRepositoryGenerator(), loadFixture(), "acme/auth/AuthRepository.java"); assertTrue(repoSrc.contains("List findTags(Long sourceId);")); assertTrue(repoSrc.contains("List findTagsForBridge(Long sourceId);")); - assertTrue(repoSrc.contains("List findTagsForCopay(Long sourceId);")); + assertTrue(repoSrc.contains("List findTagsForCoupon(Long sourceId);")); assertFalse(repoSrc.contains("findTags(Long sourceId, String targetSubtype)")); assertFalse(repoSrc.contains("findTagsForBridge(Long sourceId, String targetSubtype)")); - assertFalse(repoSrc.contains("findTagsForCopay(Long sourceId, String targetSubtype)")); + assertFalse(repoSrc.contains("findTagsForCoupon(Long sourceId, String targetSubtype)")); String ctrlSrc = generate(new SpringControllerGenerator(), loadFixture(), "acme/auth/AuthController.java"); assertTrue(ctrlSrc.contains("repository.findTags(id));")); assertTrue(ctrlSrc.contains("repository.findTagsForBridge(id));")); - assertTrue(ctrlSrc.contains("repository.findTagsForCopay(id));")); + assertTrue(ctrlSrc.contains("repository.findTagsForCoupon(id));")); } } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mShadowedTargetCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mShadowedTargetCodegenTest.java index 856f03a569..d91dda402f 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mShadowedTargetCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringTphM2mShadowedTargetCodegenTest.java @@ -22,12 +22,12 @@ *

    {@code Auth} (base, {@code @discriminator: type}) declares {@code helpers -> * Tag} (Tag is NOT TPH). {@code BridgeAuth} (subtype) SHADOWS {@code helpers} onto * {@code PriorityTicket} — a concrete TPH subtype of the UNRELATED {@code Ticket} - * hierarchy. {@code CopayAuth} does not shadow — it inherits the base's Tag-target + * hierarchy. {@code CouponAuth} does not shadow — it inherits the base's Tag-target * relationship unmodified.

    * *

    Because Java disambiguates every (relation name, source scope) pair into its * OWN interface method ({@code findHelpers} / {@code findHelpersForBridge} / - * {@code findHelpersForCopay}), each finder's {@code targetSubtype} threading is + * {@code findHelpersForCoupon}), each finder's {@code targetSubtype} threading is * decided from ITS OWN resolved {@link SpringM2mSupport.M2mNav} — independently * correct by construction, with no shared seam across mounts to desynchronize (the * arity-mismatch hazard Python's single shared {@code Protocol} seam has to guard @@ -53,7 +53,7 @@ public class SpringTphM2mShadowedTargetCodegenTest extends SharedRegistryTestBas { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "helpers", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthHelper" } }, @@ -64,8 +64,8 @@ public class SpringTphM2mShadowedTargetCodegenTest extends SharedRegistryTestBas { "relationship.association": { "name": "helpers", "@cardinality": "many", "@objectRef": "PriorityTicket", "@through": "BridgeHelper" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "AuthHelper", "children": [ { "source.rdb": { "@table": "auth_helpers" } }, @@ -130,9 +130,9 @@ public void shadowingSubtypeFinderIsWidenedForItsOwnTphTarget() throws Exception @Test public void nonShadowingSubtypeFinderInheritsTheUnwidenedNonTphTarget() throws Exception { String src = generate(new SpringRepositoryGenerator(), loadFixture(), "acme/auth/AuthRepository.java"); - assertTrue("expected unwidened findHelpersForCopay (inherits Tag, non-TPH); saw:\n" + src, - src.contains("List findHelpersForCopay(Long sourceId);")); - assertFalse(src.contains("findHelpersForCopay(Long sourceId, String targetSubtype)")); + assertTrue("expected unwidened findHelpersForCoupon (inherits Tag, non-TPH); saw:\n" + src, + src.contains("List findHelpersForCoupon(Long sourceId);")); + assertFalse(src.contains("findHelpersForCoupon(Long sourceId, String targetSubtype)")); } @Test @@ -142,8 +142,8 @@ public void everyMountOfTheShadowedNamePassesItsOwnCorrectCallSiteArgs() throws src.contains("repository.findHelpers(id));")); assertTrue("shadowing Bridge mount: repository.findHelpersForBridge(id, \"Priority\"); saw:\n" + src, src.contains("repository.findHelpersForBridge(id, \"Priority\")")); - assertTrue("non-shadowing Copay mount: repository.findHelpersForCopay(id); saw:\n" + src, - src.contains("repository.findHelpersForCopay(id));")); + assertTrue("non-shadowing Coupon mount: repository.findHelpersForCoupon(id); saw:\n" + src, + src.contains("repository.findHelpersForCoupon(id));")); assertFalse("Bridge mount must not stay unwidened; saw:\n" + src, src.contains("repository.findHelpersForBridge(id));")); } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringUuidPrimaryKeyCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringUuidPrimaryKeyCodegenTest.java index 2615ca47e0..7209403f41 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringUuidPrimaryKeyCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringUuidPrimaryKeyCodegenTest.java @@ -70,7 +70,7 @@ public class SpringUuidPrimaryKeyCodegenTest extends SharedRegistryTestBase { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.uuid": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "@fields": "id", "@generation": "uuid" } } ] } }, @@ -78,9 +78,9 @@ public class SpringUuidPrimaryKeyCodegenTest extends SharedRegistryTestBase { "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", - "@discriminatorValue": "Copay", "children": [ - { "field.string": { "name": "copayCode", "@maxLength": 40 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", + "@discriminatorValue": "Coupon", "children": [ + { "field.string": { "name": "couponCode", "@maxLength": 40 } } ] } } ] } } @@ -164,8 +164,8 @@ public void uuidPkTphControllerUsesUuidPathVariables() throws Exception { src.contains("getBridge(@PathVariable java.util.UUID id)")); assertTrue("expected per-subtype updateBridge(@PathVariable java.util.UUID id, ...); saw:\n" + src, src.contains("updateBridge(@PathVariable java.util.UUID id,")); - assertTrue("expected per-subtype deleteCopay(@PathVariable java.util.UUID id); saw:\n" + src, - src.contains("deleteCopay(@PathVariable java.util.UUID id)")); + assertTrue("expected per-subtype deleteCoupon(@PathVariable java.util.UUID id); saw:\n" + src, + src.contains("deleteCoupon(@PathVariable java.util.UUID id)")); assertFalse("uuid-PK TPH controller must not bind @PathVariable Long; saw:\n" + src, src.contains("@PathVariable Long id")); } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/TphDiscriminatorEnumConformanceTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/TphDiscriminatorEnumConformanceTest.java index ce2e1318ff..97a851e3de 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/TphDiscriminatorEnumConformanceTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/TphDiscriminatorEnumConformanceTest.java @@ -27,7 +27,7 @@ * assertion pins the static type so the discriminator can't silently regress to {@code String}. * Loads the SAME shared fixture the integration lane uses * ({@code fixtures/api-contract-conformance/tph/meta.json}: TPH base {@code Auth} with a - * {@code field.enum type} discriminator over {@code Bridge|Copay|PriorAuth}).

    + * {@code field.enum type} discriminator over {@code Bridge|Coupon|Permit}).

    */ public class TphDiscriminatorEnumConformanceTest extends SharedRegistryTestBase { @@ -58,7 +58,7 @@ public void tphEnumDiscriminatorIsTypedAsTheEnumNotString() throws Exception { assertTrue("the @discriminator field.enum must be typed as the generated enum; saw:\n" + src, src.contains("AuthType type")); assertTrue("the discriminator enum must be materialized with its @values; saw:\n" + src, - src.contains("public enum AuthType { Bridge, Copay, PriorAuth }")); + src.contains("public enum AuthType { Bridge, Coupon, Permit }")); assertFalse("the @discriminator must NOT regress to a raw String component; saw:\n" + src, src.contains("String type")); } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt index 66283863d4..b44da3d660 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/QueryScenarioRunner.kt @@ -547,7 +547,7 @@ object QueryScenarioRunner { // ADR-0019 Amendment 1: the decimal subject table. "Entry" -> EntryTable // FR-017 TPH: the discriminator base + all its subtypes share the single `auths` table. - "Auth", "BridgeAuth", "CopayAuth", "PriorAuthAuth" -> AuthTable + "Auth", "BridgeAuth", "CouponAuth", "PermitAuth" -> AuthTable else -> error("No Exposed Table registered for entity '$entity' — extend QueryScenarioRunner.tableFor or tables/ReportViews") } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt index 12c45efb04..9f845c2296 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphFullSuiteCompilesTest.kt @@ -30,8 +30,8 @@ import kotlin.test.assertTrue * The `Auth` base owns `lines: many AuthLine`, inherited by every subtype. If any generator failed * to fold a subtype into the base — the table's back-FK inference (`buildGlobalFkMap`), the relations * helper, or the validator registry — it would emit a reference to a `BridgeAuthTable` / - * `CopayAuthTable` / `PriorAuthAuthTable` that the table generator no longer emits, and this compile - * would fail. `CopayAuth` also carries a non-discriminator `@filterable field.enum` (`tier`) that + * `CouponAuthTable` / `PermitAuthTable` that the table generator no longer emits, and this compile + * would fail. `CouponAuth` also carries a non-discriminator `@filterable field.enum` (`tier`) that * folds into the union, so the TPH controller emits `castTo(TextColumnType())` for it — this * gate also covers the #179 enum-filter import block on the TPH controller path. */ @@ -43,7 +43,7 @@ class TphFullSuiteCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id", "@filterable": true } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80, "@filterable": true } }, { "relationship.composition": { "name": "lines", "@cardinality": "many", "@objectRef": "AuthLine", "@onDelete": "cascade" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } @@ -51,12 +51,12 @@ class TphFullSuiteCompilesTest { { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true, "@filterable": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2, "@filterable": true } }, + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2, "@filterable": true } }, { "field.enum": { "name": "tier", "@values": ["Standard", "Premium"], "@filterable": true } } ] } }, - { "object.entity": { "name": "PriorAuthAuth", "extends": "Auth", "@discriminatorValue": "PriorAuth", "children": [ - { "field.string": { "name": "priorAuthNumber", "@maxLength": 80, "@filterable": true } } + { "object.entity": { "name": "PermitAuth", "extends": "Auth", "@discriminatorValue": "Permit", "children": [ + { "field.string": { "name": "permitNumber", "@maxLength": 80, "@filterable": true } } ] } }, { "object.entity": { "name": "AuthLine", "children": [ { "source.rdb": { "@table": "auth_lines" } }, @@ -90,8 +90,8 @@ class TphFullSuiteCompilesTest { val names = emitted.map { it.fileName.toString() }.toSet() // The subtypes fold into the base — no per-subtype persistence artifact of any kind. for (dead in listOf( - "BridgeAuthTable.kt", "CopayAuthTable.kt", "PriorAuthAuthTable.kt", - "BridgeAuthRelations.kt", "CopayAuthRelations.kt", "PriorAuthAuthRelations.kt", + "BridgeAuthTable.kt", "CouponAuthTable.kt", "PermitAuthTable.kt", + "BridgeAuthRelations.kt", "CouponAuthRelations.kt", "PermitAuthRelations.kt", )) { assertFalse(dead in names, "TPH subtype must not emit $dead; got $names") } @@ -115,7 +115,7 @@ class TphFullSuiteCompilesTest { @Test fun `FR-017 full TPH generator suite with the names artifact in the run compiles and folds the subtype columns`() { // Task 6 — the names-ON arm. The base's AuthTable references `Names.
    _COLUMN` - // for every SUBTYPE column it folds in (quantity / copayAmount / tier / priorAuthNumber + // for every SUBTYPE column it folds in (quantity / couponAmount / tier / permitNumber // belong to the subtypes' artifacts, not AuthNames). A text assertion proves the // reference is SPELLED; only the compiler proves it RESOLVES, and only the compiled // Exposed object proves it folds to the column the database has. @@ -140,9 +140,9 @@ class TphFullSuiteCompilesTest { val emitted = Files.walk(outDir).filter { it.isRegularFile() }.sorted().toList() val authTable = emitted.first { it.fileName.toString() == "AuthTable.kt" }.readText() assertTrue("integer(BridgeAuthNames.QUANTITY_COLUMN).nullable()" in authTable, authTable) - assertTrue("portableDecimal(CopayAuthNames.COPAY_AMOUNT_COLUMN, 10, 2).nullable()" in authTable, authTable) - assertTrue("varchar(PriorAuthAuthNames.PRIOR_AUTH_NUMBER_COLUMN, 80).nullable()" in authTable, authTable) - assertTrue("enumerationByName(CopayAuthNames.TIER_COLUMN, 64, AuthTier::class).nullable()" in authTable, authTable) + assertTrue("portableDecimal(CouponAuthNames.COUPON_AMOUNT_COLUMN, 10, 2).nullable()" in authTable, authTable) + assertTrue("varchar(PermitAuthNames.PERMIT_NUMBER_COLUMN, 80).nullable()" in authTable, authTable) + assertTrue("enumerationByName(CouponAuthNames.TIER_COLUMN, 64, AuthTier::class).nullable()" in authTable, authTable) val sources = emitted.map { path -> SourceFile.kotlin(outDir.relativize(path).toString().replace('/', '_'), path.readText()) @@ -160,7 +160,7 @@ class TphFullSuiteCompilesTest { val table = result.classLoader.loadClass("acme.auth.AuthTable").getDeclaredField("INSTANCE").get(null) as Table assertEquals("auths", table.tableName) val columns = table.columns.map { it.name }.toSet() - for (col in listOf("id", "type", "reference", "quantity", "copay_amount", "tier", "prior_auth_number")) { + for (col in listOf("id", "type", "reference", "quantity", "coupon_amount", "tier", "permit_number")) { assertTrue(col in columns, "AuthTable is missing column $col; has $columns") } } finally { diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt index f0a516c332..30627ddd48 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphGeneratedApiContractConformanceTest.kt @@ -59,7 +59,7 @@ internal class TphGeneratedApiContractConformanceTest { @Test @Suppress("UNCHECKED_CAST") fun tphListsSupportFr009Filters() { - HARNESS.reset() // seed: Bridge id1 (quantity 5), Copay id2, PriorAuth id3 + HARNESS.reset() // seed: Bridge id1 (quantity 5), Coupon id2, Permit id3 val r1 = HARNESS.exchange("GET", "/api/auths?filter[quantity][eq]=5&sort=id:asc", null) assertEquals(200, r1.status) val rows1 = HARNESS.parseBody(r1.body) as List> @@ -76,7 +76,7 @@ internal class TphGeneratedApiContractConformanceTest { assertEquals("invalid_filter_field", (HARNESS.parseBody(r4.body) as Map)["error"]) // Polymorphic list filtered by the DISCRIMINATOR (FR-017 "Filter allowlists": the base // allowlist includes it). Kotlin excluded it until 1.0.5 and answered this with r4's 400. - val r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Copay&sort=id:asc", null) + val r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Coupon&sort=id:asc", null) assertEquals(200, r5.status, r5.body) val rows5 = HARNESS.parseBody(r5.body) as List> assertEquals(listOf(1, 2), rows5.map { (it["id"] as Number).toInt() }) diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt index 679fd9e287..8c2a564b52 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mFullSuiteCompilesTest.kt @@ -41,7 +41,7 @@ class TphM2mFullSuiteCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -52,8 +52,8 @@ class TphM2mFullSuiteCompilesTest { { "relationship.association": { "name": "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } } + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -103,7 +103,7 @@ class TphM2mFullSuiteCompilesTest { val names = emitted.map { it.fileName.toString() }.toSet() // The subtypes fold into the base — no per-subtype persistence artifact of any kind, // M:N included (the whole point: linkedAuths must NOT try to reference BridgeAuthTable). - for (dead in listOf("BridgeAuthTable.kt", "CopayAuthTable.kt", "BridgeAuthRelations.kt", "CopayAuthRelations.kt")) { + for (dead in listOf("BridgeAuthTable.kt", "CouponAuthTable.kt", "BridgeAuthRelations.kt", "CouponAuthRelations.kt")) { assertFalse(dead in names, "TPH subtype must not emit $dead; got $names") } @@ -119,9 +119,9 @@ class TphM2mFullSuiteCompilesTest { val controller = emitted.first { it.fileName.toString() == "AuthController.kt" }.readText() assertTrue("@GetMapping(\"/{id}/tags\")" in controller, controller) assertTrue("@GetMapping(\"/bridge/{id}/tags\")" in controller, controller) - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in controller, controller) + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in controller, controller) assertTrue("@GetMapping(\"/bridge/{id}/linkedAuths\")" in controller, controller) - assertFalse("/copay/{id}/linkedAuths" in controller, controller) + assertFalse("/coupon/{id}/linkedAuths" in controller, controller) val sources = emitted.map { path -> SourceFile.kotlin(outDir.relativize(path).toString().replace('/', '_'), path.readText()) diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt index 39e0e76e28..9e82dc3dfb 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/TphM2mShadowedFullSuiteCompilesTest.kt @@ -25,11 +25,11 @@ import kotlin.test.assertTrue * [TphM2mFullSuiteCompilesTest], which covers the (unshadowed) base-declared + subtype-own case. * * Before this fix, [com.metaobjects.generator.kotlin.KotlinRelationsGenerator]'s TPH-wide M:N nav - * union deduped by relation NAME alone (first-seen wins), so `CopayAuth`'s shadowing `tags -> + * union deduped by relation NAME alone (first-seen wins), so `CouponAuth`'s shadowing `tags -> * SpecialTag` nav was silently DROPPED and `AuthRelations.kt` emitted only ONE `tagsQuery` helper * — built from `Auth`'s own `tags -> Tag` shape. [com.metaobjects.generator.kotlin.KotlinSpringControllerGenerator], * however, independently RE-RESOLVES each subtype's own nav for its return type + row mapping, so - * the generated `tagsCopay()` endpoint declared `ResponseEntity>` and mapped + * the generated `tagsCoupon()` endpoint declared `ResponseEntity>` and mapped * `row[SpecialTagTable.*]` — off rows the WRONG-target `AuthTable.tagsQuery(id)` helper produced * (a `Tag`/`AuthTag` join). This is the "compiles, wrong at runtime" shape: every reference here * is a statically valid `Column`, so the pre-fix code compiles cleanly and only throws when the @@ -45,7 +45,7 @@ class TphM2mShadowedFullSuiteCompilesTest { { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { "name": "reference", "@required": true, "@maxLength": 80 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -54,10 +54,10 @@ class TphM2mShadowedFullSuiteCompilesTest { { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity", "@required": true } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "Auth", "@discriminatorValue": "Copay", "children": [ - { "field.decimal": { "name": "copayAmount", "@precision": 10, "@scale": 2 } }, + { "object.entity": { "name": "CouponAuth", "extends": "Auth", "@discriminatorValue": "Coupon", "children": [ + { "field.decimal": { "name": "couponAmount", "@precision": 10, "@scale": 2 } }, { "relationship.association": { "name": "tags", "@cardinality": "many", - "@objectRef": "SpecialTag", "@through": "CopaySpecialTag" } } + "@objectRef": "SpecialTag", "@through": "CouponSpecialTag" } } ] } }, { "object.entity": { "name": "Tag", "children": [ { "source.rdb": { "@table": "tags" } }, @@ -79,12 +79,12 @@ class TphM2mShadowedFullSuiteCompilesTest { { "identity.reference": { "name": "fkAuth", "@fields": "authId", "@references": "Auth" } }, { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } ] } }, - { "object.entity": { "name": "CopaySpecialTag", "children": [ - { "source.rdb": { "@table": "copay_special_tags" } }, - { "field.long": { "name": "copayAuthId", "@required": true } }, + { "object.entity": { "name": "CouponSpecialTag", "children": [ + { "source.rdb": { "@table": "coupon_special_tags" } }, + { "field.long": { "name": "couponAuthId", "@required": true } }, { "field.long": { "name": "specialTagId", "@required": true } }, - { "identity.primary": { "@fields": ["copayAuthId", "specialTagId"] } }, - { "identity.reference": { "name": "fkCopay", "@fields": "copayAuthId", "@references": "CopayAuth" } }, + { "identity.primary": { "@fields": ["couponAuthId", "specialTagId"] } }, + { "identity.reference": { "name": "fkCoupon", "@fields": "couponAuthId", "@references": "CouponAuth" } }, { "identity.reference": { "name": "fkSpecialTag", "@fields": "specialTagId", "@references": "SpecialTag" } } ] } } ] } @@ -111,7 +111,7 @@ class TphM2mShadowedFullSuiteCompilesTest { val emitted = Files.walk(outDir).filter { it.isRegularFile() }.sorted().toList() val names = emitted.map { it.fileName.toString() }.toSet() - for (dead in listOf("BridgeAuthTable.kt", "CopayAuthTable.kt", "BridgeAuthRelations.kt", "CopayAuthRelations.kt")) { + for (dead in listOf("BridgeAuthTable.kt", "CouponAuthTable.kt", "BridgeAuthRelations.kt", "CouponAuthRelations.kt")) { assertFalse(dead in names, "TPH subtype must not emit $dead; got $names") } @@ -124,25 +124,25 @@ class TphM2mShadowedFullSuiteCompilesTest { assertTrue("TagTable" in tagsQueryBody, tagsQueryBody) assertFalse("SpecialTagTable" in tagsQueryBody, tagsQueryBody) - // The shadowing CopayAuth shape must have gotten its OWN, distinctly-named helper - // (not collapsed into tagsQuery), joining SpecialTag/CopaySpecialTag. + // The shadowing CouponAuth shape must have gotten its OWN, distinctly-named helper + // (not collapsed into tagsQuery), joining SpecialTag/CouponSpecialTag. val helperNames = Regex("""fun AuthTable\.(tags\w*)Query\(""").findAll(relations) .map { it.groupValues[1] }.toSet() assertTrue(helperNames.size >= 2, "expected >=2 distinct tags*Query helpers; found $helperNames in:\n$relations") val shadowHelper = helperNames.first { it != "tags" } val shadowBody = relations.substringAfter("fun AuthTable.${shadowHelper}Query").substringBefore("\n\n") assertTrue("SpecialTagTable" in shadowBody, shadowBody) - assertTrue("CopaySpecialTagTable" in shadowBody, shadowBody) + assertTrue("CouponSpecialTagTable" in shadowBody, shadowBody) assertFalse("AuthTagTable" in shadowBody, shadowBody) val controller = emitted.first { it.fileName.toString() == "AuthController.kt" }.readText() - assertTrue("@GetMapping(\"/copay/{id}/tags\")" in controller, controller) - val tagsCopayBody = controller.substringAfter("fun tagsCopay(").substringBefore("\n }\n") - assertFalse("AuthTable.tagsQuery(id)" in tagsCopayBody, - "tagsCopay() must not delegate to the base-shape helper (wrong target); saw:\n$tagsCopayBody") - assertTrue("AuthTable.${shadowHelper}Query(id)" in tagsCopayBody, - "expected tagsCopay() to call its own $shadowHelper Query helper; saw:\n$tagsCopayBody") - assertTrue("row[SpecialTagTable." in tagsCopayBody, tagsCopayBody) + assertTrue("@GetMapping(\"/coupon/{id}/tags\")" in controller, controller) + val tagsCouponBody = controller.substringAfter("fun tagsCoupon(").substringBefore("\n }\n") + assertFalse("AuthTable.tagsQuery(id)" in tagsCouponBody, + "tagsCoupon() must not delegate to the base-shape helper (wrong target); saw:\n$tagsCouponBody") + assertTrue("AuthTable.${shadowHelper}Query(id)" in tagsCouponBody, + "expected tagsCoupon() to call its own $shadowHelper Query helper; saw:\n$tagsCouponBody") + assertTrue("row[SpecialTagTable." in tagsCouponBody, tagsCouponBody) // The unaffected mounts still delegate to the plain shared helper. val tagsBridgeBody = controller.substringAfter("fun tagsBridge(").substringBefore("\n }\n") diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt index df760476b7..f16c37afd3 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt @@ -30,7 +30,7 @@ import kotlin.io.path.readText /** * FR-017 Tier 4/5 — host the GENERATED Kotlin Spring `@RestController` for the TPH corpus - * (`Auth` base + `Bridge`/`Copay`/`PriorAuth` subtypes) over real HTTP (an embedded Tomcat) + * (`Auth` base + `Bridge`/`Coupon`/`Permit` subtypes) over real HTTP (an embedded Tomcat) * and drive the polymorphic-CRUD scenarios against it. * * Mechanism (the SP-F generate→compile→load pattern, mirroring [com.metaobjects.integration.kotlin.api.generated.GeneratedAuthorControllerHarness]): @@ -148,7 +148,7 @@ class GeneratedTphControllerHarness( // autoCreatedAt stays OLD — the two robustly diverge. // // `id` is OMITTED so the auto-increment PK assigns 1..3 in the seed's own order (empty table), - // exactly as the prior POST-seed did (1=Bridge, 2=Copay, 3=PriorAuth). Columns are matched by + // exactly as the prior POST-seed did (1=Bridge, 2=Coupon, 3=Permit). Columns are matched by // NAME normalized (lowercase, underscores stripped) so the field camelCase (autoCreatedAt) // resolves to the generated snake_case physical column (auto_created_at) regardless of naming // strategy; typed inserts (not raw SQL) let Exposed handle all dialect identifier quoting. @@ -172,7 +172,7 @@ class GeneratedTphControllerHarness( stmt[columnFor("autoCreatedAt")] = parseSeedInstant(r["autoCreatedAt"] as String) stmt[columnFor("autoUpdatedAt")] = parseSeedInstant(r["autoUpdatedAt"] as String) stmt[columnFor("quantity")] = (r["quantity"] as? Number)?.toInt() - stmt[columnFor("copayAmount")] = (r["copayAmount"] as? String)?.let { java.math.BigDecimal(it) } + stmt[columnFor("couponAmount")] = (r["couponAmount"] as? String)?.let { java.math.BigDecimal(it) } stmt[columnFor("approver")] = r["approver"] as String? } } diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt index 6c500413e7..78db46f75c 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/tables/AuthTable.kt @@ -5,7 +5,7 @@ import org.jetbrains.exposed.sql.Table /** * Hand-written reference Exposed Table for the FR-017 Table-Per-Hierarchy (TPH) `auths` table * from `fixtures/persistence-conformance/canonical/meta.fitness.json` — the SINGLE physical table - * shared by the `Auth` discriminator base and its `BridgeAuth` / `CopayAuth` / `PriorAuthAuth` + * shared by the `Auth` discriminator base and its `BridgeAuth` / `CouponAuth` / `PermitAuth` * subtypes (single-table inheritance). * * Every subtype-only column is NULLABLE — a row of any other subtype stores NULL there, even @@ -18,15 +18,15 @@ import org.jetbrains.exposed.sql.Table * - `type` TEXT (discriminator, CHECK in DDL) → `varchar("type", 64)` * - `reference` VARCHAR(80) NOT NULL → `varchar("reference", 80)` * - `quantity` INTEGER (BridgeAuth-only) → `integer("quantity").nullable()` - * - `copayAmount` NUMERIC(10,2) (CopayAuth-only) → `decimal("copayAmount", 10, 2).nullable()` - * - `approver` VARCHAR(80) (PriorAuthAuth-only) → `varchar("approver", 80).nullable()` + * - `couponAmount` NUMERIC(10,2) (CouponAuth-only) → `decimal("couponAmount", 10, 2).nullable()` + * - `approver` VARCHAR(80) (PermitAuth-only) → `varchar("approver", 80).nullable()` */ object AuthTable : Table("auths") { val id = long("id").autoIncrement() val type = varchar("type", 64) val reference = varchar("reference", 80) val quantity = integer("quantity").nullable() - val copayAmount = portableDecimal("copayAmount", 10, 2).nullable() + val couponAmount = portableDecimal("couponAmount", 10, 2).nullable() val approver = varchar("approver", 80).nullable() override val primaryKey = PrimaryKey(id) diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java index a62615fc69..677bee9ad5 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/QueryScenarioTests.java @@ -109,8 +109,8 @@ static void beforeAll() { // FR-017 TPH corpus entities — the discriminator base + its three subtypes (single table). bindings.put("fitness::Auth", ValueObject.class); bindings.put("fitness::BridgeAuth", ValueObject.class); - bindings.put("fitness::CopayAuth", ValueObject.class); - bindings.put("fitness::PriorAuthAuth", ValueObject.class); + bindings.put("fitness::CouponAuth", ValueObject.class); + bindings.put("fitness::PermitAuth", ValueObject.class); // ADR-0019 Amendment 1 decimal corpus + the redeclared-field report's tables. bindings.put("fitness::Entry", ValueObject.class); bindings.put("fitness::Gadget", ValueObject.class); diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java index 3279ef8aae..4f78d2b08d 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/TphGeneratedApiContractConformanceTest.java @@ -108,7 +108,7 @@ void scenario(String name, ApiScenario scenario) { @Test @SuppressWarnings("unchecked") void tphListsSupportFr009Filters() throws Exception { - HARNESS.reset(); // seed: Bridge id1 (quantity 5), Copay id2, PriorAuth id3 + HARNESS.reset(); // seed: Bridge id1 (quantity 5), Coupon id2, Permit id3 // (a) polymorphic list filtered by a SUBTYPE column — only the Bridge row carries quantity. var r1 = HARNESS.exchange("GET", "/api/auths?filter[quantity][eq]=5&sort=id:asc", null); org.junit.jupiter.api.Assertions.assertEquals(200, r1.status()); @@ -130,7 +130,7 @@ void tphListsSupportFr009Filters() throws Exception { ((Map) HARNESS.parseBody(r4.body())).get("error")); // (e) polymorphic list filtered by the DISCRIMINATOR (FR-017 "Filter allowlists": the base // allowlist includes it). Java excluded it until 1.0.5 and answered this with (d)'s 400. - var r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Copay&sort=id:asc", null); + var r5 = HARNESS.exchange("GET", "/api/auths?filter[type][in]=Bridge,Coupon&sort=id:asc", null); org.junit.jupiter.api.Assertions.assertEquals(200, r5.status(), r5.body()); var rows5 = (List>) HARNESS.parseBody(r5.body()); org.junit.jupiter.api.Assertions.assertEquals(List.of(1, 2), diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java index dbe315f4f9..700717bb4d 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java @@ -45,7 +45,7 @@ /** * FR-017 Tier 4/5 — host the GENERATED Java Spring {@code @RestController} for the TPH corpus - * ({@code Auth} base + {@code Bridge}/{@code Copay}/{@code PriorAuth} subtypes) over HTTP + * ({@code Auth} base + {@code Bridge}/{@code Coupon}/{@code Permit} subtypes) over HTTP * (a real embedded Tomcat, {@link TomcatHost}) and drive the polymorphic-CRUD scenarios against it. * *

    Mechanism (the SP-F generate→compile→load pattern, mirroring @@ -82,7 +82,7 @@ public final class GeneratedTphControllerHarness implements AutoCloseable { private final ObjectMapper mapper; private final URLClassLoader classLoader; // (Long id, AuthType type, String reference, Instant autoCreatedAt, Instant autoUpdatedAt, - // Integer quantity, BigDecimal copayAmount, String approver) + // Integer quantity, BigDecimal couponAmount, String approver) private final Constructor dtoCtor; private final Class authTypeClass; // the generated value-constrained enum discriminator (AuthDto.AuthType) private final Constructor controllerCtor; // (AuthRepository, ObjectMapper, Validator) @@ -224,15 +224,15 @@ private Object dtoFromRow(Map row) throws Exception { Object autoUpdatedRaw = row.get("autoUpdatedAt"); Instant autoUpdatedAt = autoUpdatedRaw == null ? null : parseInstant(String.valueOf(autoUpdatedRaw)); Integer quantity = row.get("quantity") == null ? null : ((Number) row.get("quantity")).intValue(); - Object copayRaw = row.get("copayAmount"); - BigDecimal copayAmount = copayRaw == null ? null : new BigDecimal(String.valueOf(copayRaw)); + Object couponRaw = row.get("couponAmount"); + BigDecimal couponAmount = couponRaw == null ? null : new BigDecimal(String.valueOf(couponRaw)); String approver = (String) row.get("approver"); // Coerce the seed's String discriminator into the generated AuthType enum value. @SuppressWarnings({ "unchecked", "rawtypes" }) Object typeEnum = type == null ? null : Enum.valueOf((Class) authTypeClass, type); return dtoCtor.newInstance( id, typeEnum, reference, issuedCurrency, autoCreatedAt, autoUpdatedAt, - quantity, copayAmount, approver); + quantity, couponAmount, approver); } /** diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java index 4f540110eb..69f05a4a1a 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java @@ -113,7 +113,7 @@ public AuthDto createWithType(String discriminator, AuthDto dto) { // FR-037 R1: writeOnce IS bound on create — settable exactly once. dto.issuedCurrency(), dto.autoCreatedAt(), dto.autoUpdatedAt(), - dto.quantity(), dto.copayAmount(), dto.approver()); + dto.quantity(), dto.couponAmount(), dto.approver()); rows.add(saved); return saved; } @@ -131,7 +131,7 @@ public Optional updateByIdAndType(Long id, String discriminator, AuthDt dto.autoCreatedAt() != null ? dto.autoCreatedAt() : cur.autoCreatedAt(), dto.autoUpdatedAt() != null ? dto.autoUpdatedAt() : cur.autoUpdatedAt(), dto.quantity() != null ? dto.quantity() : cur.quantity(), - dto.copayAmount() != null ? dto.copayAmount() : cur.copayAmount(), + dto.couponAmount() != null ? dto.couponAmount() : cur.couponAmount(), dto.approver() != null ? dto.approver() : cur.approver()); rows.set(i, merged); return Optional.of(merged); @@ -163,7 +163,7 @@ public Optional patchByIdAndType(Long id, String discriminator, Map a.type(); case "reference" -> a.reference(); case "quantity" -> a.quantity(); - case "copayAmount" -> a.copayAmount(); + case "couponAmount" -> a.couponAmount(); case "approver" -> a.approver(); default -> throw new IllegalStateException("unknown column: " + field); }; diff --git a/server/python/src/metaobjects/codegen/generators/tph_plan.py b/server/python/src/metaobjects/codegen/generators/tph_plan.py index 0d9c9b62a7..ef57c886f1 100644 --- a/server/python/src/metaobjects/codegen/generators/tph_plan.py +++ b/server/python/src/metaobjects/codegen/generators/tph_plan.py @@ -7,7 +7,7 @@ TPH-aware generator reads, so the route-segment rule and subtype set never drift. The per-subtype REST route segment is the ``@discriminatorValue`` lowercased -(``"Bridge"`` → ``bridge``, ``"PriorAuth"`` → ``priorauth``) — derived in exactly +(``"Bridge"`` → ``bridge``, ``"Permit"`` → ``permit``) — derived in exactly one place (:func:`route_segment`). """ from __future__ import annotations diff --git a/server/python/tests/codegen/test_names_extends_chain.py b/server/python/tests/codegen/test_names_extends_chain.py index 866ab7a400..970a338e55 100644 --- a/server/python/tests/codegen/test_names_extends_chain.py +++ b/server/python/tests/codegen/test_names_extends_chain.py @@ -65,18 +65,18 @@ "children": [ {"source.rdb": {"@table": "zz_auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "kind", "@values": ["Copay"]}}, + {"field.enum": {"name": "kind", "@values": ["Coupon"]}}, {"identity.primary": {"name": "pk", "@fields": "id", "@generation": "increment"}}, ], } }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - {"field.long": {"name": "copayAmount", "@column": "zz_copay_cents"}} + {"field.long": {"name": "couponAmount", "@column": "zz_coupon_cents"}} ], } }, @@ -135,15 +135,15 @@ def test_the_child_imports_the_base_constant_instead_of_restating_it(tmp_path: P def test_a_tph_subtype_references_the_shared_table_name_rather_than_restating_it(tmp_path: Path) -> None: - src = _generate(tmp_path)["copay_auth_names.py"] - assert "COPAYAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE" in src - assert "COPAYAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN" in src - assert 'COPAYAUTH_COPAY_AMOUNT_COLUMN: Final[str] = "zz_copay_cents"' in src + src = _generate(tmp_path)["coupon_auth_names.py"] + assert "COUPONAUTH_SOURCE_PRIMARY_TABLE: Final[str] = AUTH_SOURCE_PRIMARY_TABLE" in src + assert "COUPONAUTH_ID_COLUMN: Final[str] = AUTH_ID_COLUMN" in src + assert 'COUPONAUTH_COUPON_AMOUNT_COLUMN: Final[str] = "zz_coupon_cents"' in src # A single-table hierarchy legitimately has two OBJECT names; only the physical one # is shared. So the subtype keeps its own name/type/subType as literals. - assert 'COPAYAUTH_NAME: Final[str] = "CopayAuth"' in src + assert 'COUPONAUTH_NAME: Final[str] = "CouponAuth"' in src # An inherited identity is reached through the base's constant, not restated. - assert "COPAYAUTH_IDENTITY_PK_NAME: Final[str] = AUTH_IDENTITY_PK_NAME" in src + assert "COUPONAUTH_IDENTITY_PK_NAME: Final[str] = AUTH_IDENTITY_PK_NAME" in src # The whole point: the subtype used to restate the base's table name and every column. assert "zz_auths" not in src @@ -241,27 +241,27 @@ def test_the_emitted_modules_import_and_an_inherited_constant_resolves(tmp_path: (pkg / "__init__.py").write_text("") sys.path.insert(0, str(tmp_path)) try: - spec = importlib.util.spec_from_file_location("gen.copay_auth_names", pkg / "copay_auth_names.py") + spec = importlib.util.spec_from_file_location("gen.coupon_auth_names", pkg / "coupon_auth_names.py") assert spec is not None and spec.loader is not None mod = importlib.util.module_from_spec(spec) - sys.modules["gen.copay_auth_names"] = mod + sys.modules["gen.coupon_auth_names"] = mod spec.loader.exec_module(mod) # An inherited constant, reached through the reference the generator emitted. - assert mod.COPAYAUTH_SOURCE_PRIMARY_TABLE == "zz_auths" - assert mod.COPAYAUTH_SOURCE_PRIMARY_KIND == "table" - assert mod.COPAYAUTH_IDENTITY_PK_SUB_TYPE == "primary" - assert mod.COPAYAUTH_NAME == "CopayAuth" - assert mod.COPAYAUTH_ID_COLUMN == "id" - assert mod.COPAYAUTH_COPAY_AMOUNT_COLUMN == "zz_copay_cents" + assert mod.COUPONAUTH_SOURCE_PRIMARY_TABLE == "zz_auths" + assert mod.COUPONAUTH_SOURCE_PRIMARY_KIND == "table" + assert mod.COUPONAUTH_IDENTITY_PK_SUB_TYPE == "primary" + assert mod.COUPONAUTH_NAME == "CouponAuth" + assert mod.COUPONAUTH_ID_COLUMN == "id" + assert mod.COUPONAUTH_COUPON_AMOUNT_COLUMN == "zz_coupon_cents" # COLUMNS_BY_FIELD stays COMPLETE — it is the lookup surface, and a miss on an # inherited field is the fallback-to-literal this artifact removes. - assert mod.COPAYAUTH_COLUMNS_BY_FIELD == { - "copayAmount": "zz_copay_cents", "id": "id", "kind": "kind", + assert mod.COUPONAUTH_COLUMNS_BY_FIELD == { + "couponAmount": "zz_coupon_cents", "id": "id", "kind": "kind", } finally: sys.path.remove(str(tmp_path)) - sys.modules.pop("gen.copay_auth_names", None) + sys.modules.pop("gen.coupon_auth_names", None) assert tree # keep the generated tree referenced for a readable failure @@ -455,18 +455,18 @@ def test_two_REPLICAS_that_disagree_are_still_refused_by_this_module() -> None: "children": [ {"source.rdb": {"@table": "zz_auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "kind", "@values": ["Copay"]}}, + {"field.enum": {"name": "kind", "@values": ["Coupon"]}}, {"identity.primary": {"@fields": ["id"], "@generation": "increment"}}, ], } }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - {"field.long": {"name": "copayAmount", "@column": "zz_copay_cents"}}, + {"field.long": {"name": "couponAmount", "@column": "zz_coupon_cents"}}, ], } }, @@ -476,7 +476,7 @@ def test_two_REPLICAS_that_disagree_are_still_refused_by_this_module() -> None: def test_a_scoped_run_still_names_the_shared_table(tmp_path: Path) -> None: - # `metaobjects gen --entities CopayAuth`. Pass 1 emits the subtype; pass 2 walks up to + # `metaobjects gen --entities CouponAuth`. Pass 1 emits the subtype; pass 2 walks up to # `Auth` and used to render it as a FRAGMENT unconditionally. A fragment declares no # source, by design, because it has no physical name -- but `Auth` DOES have one: it is # the TPH base, and the shared table is named on it. So the base module came out with no @@ -492,7 +492,7 @@ def test_a_scoped_run_still_names_the_shared_table(tmp_path: Path) -> None: GenConfig(out_dir=str(out), column_naming="snake_case"), result.root, generators=[names_generator()], - entity_filter=["CopayAuth"], + entity_filter=["CouponAuth"], ) files = {str(p.relative_to(out)): p.read_text() for p in out.rglob("*.py")} @@ -501,7 +501,7 @@ def test_a_scoped_run_still_names_the_shared_table(tmp_path: Path) -> None: # Every name the subtype imports from the base must EXIST in it -- the assertion the # ImportError would have made at runtime, made here instead. - child = files["copay_auth_names.py"] + child = files["coupon_auth_names.py"] imported = [ alias.name for node in ast.walk(ast.parse(child)) diff --git a/server/python/tests/codegen/test_router_generator.py b/server/python/tests/codegen/test_router_generator.py index e57aaa8deb..ad771ecdfb 100644 --- a/server/python/tests/codegen/test_router_generator.py +++ b/server/python/tests/codegen/test_router_generator.py @@ -444,7 +444,7 @@ def test_no_primary_identity_defaults_to_int() -> None: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.uuid": {"name": "id", "@filterable": True, "@sortable": True}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"], "@filterable": True}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"], "@filterable": True}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"identity.primary": {"name": "id", "@fields": "id", "@generation": "uuid"}}, ], @@ -458,9 +458,9 @@ def test_no_primary_identity_defaults_to_int() -> None: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], diff --git a/server/python/tests/codegen/test_router_generator_m2m_target_tph.py b/server/python/tests/codegen/test_router_generator_m2m_target_tph.py index 383a3bc2d6..f0b14ba739 100644 --- a/server/python/tests/codegen/test_router_generator_m2m_target_tph.py +++ b/server/python/tests/codegen/test_router_generator_m2m_target_tph.py @@ -66,7 +66,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"identity.primary": {"name": "pk", "@fields": "id", "@generation": "increment"}}, ], @@ -80,9 +80,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], diff --git a/server/python/tests/codegen/test_router_generator_tph_m2m.py b/server/python/tests/codegen/test_router_generator_tph_m2m.py index 5038576b99..17bf679cf6 100644 --- a/server/python/tests/codegen/test_router_generator_tph_m2m.py +++ b/server/python/tests/codegen/test_router_generator_tph_m2m.py @@ -70,9 +70,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: # every rule: # Auth (base, @discriminator "type") --tags--> Tag [rule a] # BridgeAuth (subtype) --linkedAuths--> BridgeAuth [rule b/c, self-join] -# CopayAuth (subtype) [no own M:N] +# CouponAuth (subtype) [no own M:N] # ScopedAuth (ABSTRACT, extends Auth) --auditors--> Tag [rule d] -# PriorAuthAuth (subtype, extends ScopedAuth) +# PermitAuth (subtype, extends ScopedAuth) # Auth (base) --priorityTickets--> PriorityTicket [target-discriminator; base-declared # (Ticket is an UNRELATED TPH hierarchy — see below), so ungated, but target IS TPH] _TPH_M2M_META = { @@ -94,7 +94,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay", "PriorAuth"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon", "Permit"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, # Declared on the BASE: legitimate for every row of the shared table. {"relationship.association": { @@ -133,9 +133,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -154,9 +154,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "PriorAuthAuth", + "name": "PermitAuth", "extends": "ScopedAuth", - "@discriminatorValue": "PriorAuth", + "@discriminatorValue": "Permit", "children": [ {"field.string": {"name": "approver", "@maxLength": 80}}, ], @@ -194,12 +194,12 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: {"field.long": {"name": "auditAuthId", "@required": True}}, {"field.long": {"name": "auditTagId", "@required": True}}, {"identity.primary": {"name": "pk", "@fields": ["auditAuthId", "auditTagId"]}}, - {"identity.reference": {"name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PriorAuthAuth"}}, + {"identity.reference": {"name": "fkAuditAuth", "@fields": "auditAuthId", "@references": "PermitAuth"}}, {"identity.reference": {"name": "fkAuditTag", "@fields": "auditTagId", "@references": "Tag"}}, ], }}, # An UNRELATED TPH hierarchy — Auth.priorityTickets' target. Separate from - # Auth/BridgeAuth/CopayAuth/PriorAuthAuth entirely, so resolving the + # Auth/BridgeAuth/CouponAuth/PermitAuth entirely, so resolving the # relation via any Auth-hierarchy entity (base or subtype) never has # source is target (see the comment on priorityTickets above). {"object.entity": { @@ -291,12 +291,12 @@ def _gated_body( def test_inherited_m2m_mounted_under_every_concrete_subtype_too() -> None: # `tags` is declared on Auth, so every subtype resolves it. The overlap with the - # base mount is deliberate: /auths/bridge/{a Copay id}/tags must answer [] where + # base mount is deliberate: /auths/bridge/{a Coupon id}/tags must answer [] where # /auths/{that id}/tags does not, and only the subtype-scoped call can express that # — proven by the discriminator value actually being threaded through the GATE, # not just the join call. out = _render() - for value in ("Bridge", "Copay", "PriorAuth"): + for value in ("Bridge", "Coupon", "Permit"): segment = value.lower() assert f'@router.get("/{segment}/{{auth_id}}/tags")' in out, out assert _gated_body(value, "tags") in out, out @@ -309,14 +309,14 @@ def test_subtype_only_m2m_mounted_solely_under_its_own_subtype() -> None: # gate (this row must be a Bridge) AND the target-discriminator literal (the # related rows must be Bridge too) happen to carry the SAME value here — two # independent mechanisms, not one collapsed into the other (see - # test_priorauthlinks_target_discriminator_independent_of_source_gate below + # test_permitlinks_target_discriminator_independent_of_source_gate below # for a case where the two values DIFFER). assert _gated_body("Bridge", "linkedAuths", target_subtype="Bridge") in out # Not a base route (Auth does not declare/resolve linkedAuths)... assert '@router.get("/{auth_id}/linkedAuths")' not in out # ...and not on the sibling subtypes either (own-only on BridgeAuth, not inherited). - assert '@router.get("/copay/{auth_id}/linkedAuths")' not in out - assert '@router.get("/priorauth/{auth_id}/linkedAuths")' not in out + assert '@router.get("/coupon/{auth_id}/linkedAuths")' not in out + assert '@router.get("/permit/{auth_id}/linkedAuths")' not in out def test_priority_tickets_target_discriminator_independent_of_source_gate() -> None: @@ -336,20 +336,20 @@ def test_priority_tickets_target_discriminator_independent_of_source_gate() -> N ) in out # Inherited by every subtype too (rule b) — each subtype's OWN gate applies, # while the target literal stays fixed at "Priority" regardless. - for value in ("Bridge", "Copay", "PriorAuth"): + for value in ("Bridge", "Coupon", "Permit"): assert _gated_body(value, "priorityTickets", target_subtype="Priority") in out, out def test_abstract_mid_level_m2m_mounts_under_its_concrete_descendant_only() -> None: # `auditors` lives on ScopedAuth (abstract) — no path, no rows of its own. It is - # not on Auth either, so PriorAuthAuth (the one concrete descendant) is the ONLY + # not on Auth either, so PermitAuth (the one concrete descendant) is the ONLY # place it can be served. out = _render() - assert '@router.get("/priorauth/{auth_id}/auditors")' in out - assert _gated_body("PriorAuth", "auditors") in out + assert '@router.get("/permit/{auth_id}/auditors")' in out + assert _gated_body("Permit", "auditors") in out assert '@router.get("/{auth_id}/auditors")' not in out assert '@router.get("/bridge/{auth_id}/auditors")' not in out - assert '@router.get("/copay/{auth_id}/auditors")' not in out + assert '@router.get("/coupon/{auth_id}/auditors")' not in out def test_subtype_gate_reuses_the_existing_find_by_id_seam_method() -> None: @@ -383,6 +383,6 @@ def test_polymorphic_and_per_subtype_crud_mounts_still_present() -> None: out = _render() assert 'path="/api/auths"' in out or 'prefix="/api/auths"' in out assert '@router.get("/bridge/{auth_id}")' in out - assert '@router.get("/copay/{auth_id}")' in out - assert '@router.get("/priorauth/{auth_id}")' in out + assert '@router.get("/coupon/{auth_id}")' in out + assert '@router.get("/permit/{auth_id}")' in out assert '@router.get("/{auth_id}")' in out diff --git a/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py b/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py index 07036c3e07..d2924307df 100644 --- a/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py +++ b/server/python/tests/codegen/test_router_generator_tph_m2m_shadowed.py @@ -59,7 +59,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: # BridgeAuth (subtype) --helpers--> PriorityTicket [SHADOWS the name; TPH # target of the unrelated Ticket hierarchy, so the source-side gate and the # target-discriminator threading stay independent mechanisms] -# CopayAuth (subtype) [inherits, unshadowed] +# CouponAuth (subtype) [inherits, unshadowed] _META = { "metadata.root": { "package": "acme::auth", @@ -79,7 +79,7 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"relationship.association": { "name": "helpers", "@cardinality": "many", @@ -101,9 +101,9 @@ def _load_entities(meta: dict) -> dict[str, MetaObject]: ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -184,9 +184,9 @@ def test_every_mount_of_the_shadowed_name_passes_the_threaded_parameter() -> Non assert " rows: list[Any] = render_wire(repo.find_related_helpers(None, auth_id, None), _WIRE_TAG)" in out # Non-shadowing subtype (inherits the base's vanilla target): gated, None literal. assert ( - ' if repo.find_by_id("Copay", auth_id) is None:\n' + ' if repo.find_by_id("Coupon", auth_id) is None:\n' " return []\n" - ' rows: list[Any] = render_wire(repo.find_related_helpers("Copay", auth_id, None), _WIRE_TAG)' + ' rows: list[Any] = render_wire(repo.find_related_helpers("Coupon", auth_id, None), _WIRE_TAG)' ) in out # Shadowing subtype: its OWN target's discriminator literal. assert ( @@ -201,5 +201,5 @@ def test_no_two_argument_call_of_the_shadowed_name_remains() -> None: # name may call the seam without the parameter every other mount passes. out = _render() assert "repo.find_related_helpers(None, auth_id)\n" not in out - assert 'repo.find_related_helpers("Copay", auth_id)\n' not in out + assert 'repo.find_related_helpers("Coupon", auth_id)\n' not in out assert 'repo.find_related_helpers("Bridge", auth_id)\n' not in out diff --git a/server/python/tests/codegen/test_tph_codegen.py b/server/python/tests/codegen/test_tph_codegen.py index 7379fa2305..f5d2705e9d 100644 --- a/server/python/tests/codegen/test_tph_codegen.py +++ b/server/python/tests/codegen/test_tph_codegen.py @@ -71,10 +71,10 @@ def test_plan_detects_base_and_subtypes(entities, index) -> None: assert plan.discriminator_field == "type" assert [(s.entity.name, s.value, s.route_segment) for s in plan.subtypes] == [ ("BridgeAuth", "Bridge", "bridge"), - ("CopayAuth", "Copay", "copay"), - ("PriorAuthAuth", "PriorAuth", "priorauth"), + ("CouponAuth", "Coupon", "coupon"), + ("PermitAuth", "Permit", "permit"), ] - for sub in ("BridgeAuth", "CopayAuth", "PriorAuthAuth"): + for sub in ("BridgeAuth", "CouponAuth", "PermitAuth"): assert is_tph_subtype(entities[sub]) assert not is_tph_subtype(entities["Auth"]) @@ -92,12 +92,12 @@ def test_subtype_pins_discriminator_to_literal(entities, index) -> None: def test_base_entity_model_is_plain_base(entities, index) -> None: # The base is a plain BaseModel; its `type` enum legitimately emits the full - # Literal["Bridge","Copay","PriorAuth"] (the enum values), but it must NOT carry a + # Literal["Bridge","Coupon","Permit"] (the enum values), but it must NOT carry a # single-value discriminator PIN (that's the subtype's job). Python also defers the # discriminated-UNION alias (dict runtime; see the entity_model TPH note). src = render_entity_model(entities["Auth"], index) assert "class Auth(BaseModel):" in src - for val in ("Bridge", "Copay", "PriorAuth"): + for val in ("Bridge", "Coupon", "Permit"): assert f'type: Literal["{val}"] = "{val}"' not in src @@ -117,7 +117,7 @@ def test_base_router_polymorphic_plus_per_subtype(entities, index) -> None: # no polymorphic create (can't create an abstract base) assert '@router.post("", ' not in src # per-subtype CRUD at the lowercased segment, discriminator injected from the URL - for seg, val in (("bridge", "Bridge"), ("copay", "Copay"), ("priorauth", "PriorAuth")): + for seg, val in (("bridge", "Bridge"), ("coupon", "Coupon"), ("permit", "Permit")): assert f'@router.get("/{seg}")' in src assert f'@router.post("/{seg}", status_code=status.HTTP_201_CREATED)' in src assert f'@router.get("/{seg}/{{auth_id}}")' in src @@ -149,5 +149,5 @@ def test_base_allowlist_unions_subtype_fields(entities, index) -> None: assert '"id"' in src and '"type"' in src and '"reference"' in src # subtype-only filterable columns folded into the single-table base allowlist assert '"quantity"' in src # BridgeAuth - assert '"copayAmount"' in src # CopayAuth - assert '"approver"' in src # PriorAuthAuth + assert '"couponAmount"' in src # CouponAuth + assert '"approver"' in src # PermitAuth diff --git a/server/python/tests/integration/generated_tph_app.py b/server/python/tests/integration/generated_tph_app.py index cecbac6e4f..0b908dda16 100644 --- a/server/python/tests/integration/generated_tph_app.py +++ b/server/python/tests/integration/generated_tph_app.py @@ -1,7 +1,7 @@ """FR-017 Tier 4/5 — boot the GENERATED TPH router over HTTP. Peer to ``generated_m2m_app.py`` but for the single-table table-per-hierarchy -model (Auth base + BridgeAuth / CopayAuth / PriorAuthAuth). It runs the REAL +model (Auth base + BridgeAuth / CouponAuth / PermitAuth). It runs the REAL ``router_generator`` (+ the filter-allowlist generator it imports) for the discriminator BASE entity, writes the emitted modules to a temp package, imports the generated router UNMODIFIED, mounts it on a FastAPI app, and fills the diff --git a/server/python/tests/integration/test_m2m_target_tph_generated.py b/server/python/tests/integration/test_m2m_target_tph_generated.py index 95c0bef69c..96de59027a 100644 --- a/server/python/tests/integration/test_m2m_target_tph_generated.py +++ b/server/python/tests/integration/test_m2m_target_tph_generated.py @@ -52,7 +52,7 @@ "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"identity.primary": {"name": "pk", "@fields": "id", "@generation": "increment"}}, ], @@ -68,9 +68,9 @@ ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -244,14 +244,14 @@ def _seed(repo: _SponsorRepo) -> None: sponsors=[{"id": 1, "name": "Acme"}], auths=[ {"id": 10, "type": "Bridge", "reference": "b1", "quantity": 3, "pinHash": "bridge-pin"}, - {"id": 11, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 11, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], sponsor_auths=[(1, 10), (1, 11)], ) def test_compliant_repo_filters_target_to_the_resolved_discriminator() -> None: - # The junction links Sponsor 1 to BOTH a Bridge row (10) and a Copay row (11) + # The junction links Sponsor 1 to BOTH a Bridge row (10) and a Coupon row (11) # — the physical FK on SponsorAuth can only address the shared `auths` table, # it cannot itself tell subtypes apart. The router hands the compliant repo # target_subtype="Bridge" (resolved from BridgeAuth's @discriminatorValue at @@ -302,6 +302,6 @@ def spy(id: int, target_subtype: str) -> list[Any]: assert resp.status_code == 200 assert calls == [(1, "Bridge")] - # The hostile repo's own non-compliance leaks the Copay row — expected, and + # The hostile repo's own non-compliance leaks the Coupon row — expected, and # exactly the boundary this test documents rather than papers over. assert {r["id"] for r in resp.json()} == {10, 11} diff --git a/server/python/tests/integration/test_tph_m2m_generated.py b/server/python/tests/integration/test_tph_m2m_generated.py index 3b28ffb84a..4d40e084b5 100644 --- a/server/python/tests/integration/test_tph_m2m_generated.py +++ b/server/python/tests/integration/test_tph_m2m_generated.py @@ -43,7 +43,7 @@ # Auth (base, @discriminator "type") --tags--> Tag [rule a] # BridgeAuth (subtype) --linkedAuths--> BridgeAuth [rule b/c, self-join] -# CopayAuth (subtype) [no own M:N — inherits tags] +# CouponAuth (subtype) [no own M:N — inherits tags] _META = { "metadata.root": { "package": "acme::auth", @@ -63,7 +63,7 @@ "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"relationship.association": { "name": "tags", "@cardinality": "many", @@ -86,9 +86,9 @@ ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -306,11 +306,11 @@ def _build_app(repo_factory: type[_Repo] = _Repo) -> tuple[FastAPI, _Repo]: @pytest.fixture() def client_and_repo(): app, repo = _build_app() - # id=1 Bridge, id=2 Copay; tag 10 shared, tag 11 Bridge-only; a Bridge->Bridge link. + # id=1 Bridge, id=2 Coupon; tag 10 shared, tag 11 Bridge-only; a Bridge->Bridge link. repo.seed( auths=[ {"id": 1, "type": "Bridge", "reference": "b1", "quantity": 3}, - {"id": 2, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 2, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], tags=[{"id": 10, "name": "shared"}, {"id": 11, "name": "bridge-only"}], auth_tags=[(1, 10), (1, 11), (2, 10)], @@ -322,7 +322,7 @@ def client_and_repo(): def test_base_level_traversal_ignores_subtype(client_and_repo) -> None: # Rule (a): GET /auths/{id}/tags — every row of the shared table is a legitimate - # source, so both a Bridge id and a Copay id resolve their tags with no gate. + # source, so both a Bridge id and a Coupon id resolve their tags with no gate. client, _ = client_and_repo resp = client.get("/api/auths/1/tags") assert resp.status_code == 200 @@ -343,7 +343,7 @@ def test_subtype_level_traversal_returns_its_own_relations(client_and_repo) -> N def test_subtype_mismatch_returns_200_empty_list_not_404(client_and_repo) -> None: - # Rule (c): GET /auths/bridge/{a Copay id}/tags — the id names no Bridge row, so + # Rule (c): GET /auths/bridge/{a Coupon id}/tags — the id names no Bridge row, so # it has no relations. Must be 200 + [], never 404 and never the sibling's rows # (which the junction FK, addressing only the shared base table, would happily # return without this gate). @@ -352,7 +352,7 @@ def test_subtype_mismatch_returns_200_empty_list_not_404(client_and_repo) -> Non assert resp.status_code == 200 assert resp.json() == [] - resp2 = client.get("/api/auths/copay/1/tags") + resp2 = client.get("/api/auths/coupon/1/tags") assert resp2.status_code == 200 assert resp2.json() == [] @@ -367,7 +367,7 @@ def test_subtype_only_relation_traversal(client_and_repo) -> None: # ...and there is no such route at all on a sibling subtype or the base — the # router never mounted it there (proven at the codegen level too), so FastAPI # itself answers 404 (no matching route), not an application-level empty list. - assert client.get("/api/auths/copay/2/linkedAuths").status_code == 404 + assert client.get("/api/auths/coupon/2/linkedAuths").status_code == 404 assert client.get("/api/auths/1/linkedAuths").status_code == 404 @@ -379,7 +379,7 @@ def hostile_client_and_repo(): repo.seed( auths=[ {"id": 1, "type": "Bridge", "reference": "b1", "quantity": 3}, - {"id": 2, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 2, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], tags=[{"id": 10, "name": "shared"}, {"id": 11, "name": "bridge-only"}], auth_tags=[(1, 10), (1, 11), (2, 10)], @@ -395,7 +395,7 @@ def test_generated_router_enforces_subtype_gate_even_when_repo_does_not( # THE assertion that distinguishes ENFORCEMENT (in generated code) from # DELEGATION (trusting the consumer): _HostileRepo.find_related_tags does NOT # filter by subtype at all — if the router only ever called it directly (the - # pre-follow-up shape), GET /auths/bridge/2/tags (id=2 is a COPAY row) would + # pre-follow-up shape), GET /auths/bridge/2/tags (id=2 is a COUPON row) would # execute the join over id=2's real auth_tags rows and return tag 10 with a # 200, exactly the silent leak the maintainer flagged. With the composed # find_by_id("Bridge", 2) gate in _emit_tph_m2m_route, the router itself diff --git a/server/python/tests/integration/test_tph_m2m_shadowed_generated.py b/server/python/tests/integration/test_tph_m2m_shadowed_generated.py index 7427d4d9aa..770a605200 100644 --- a/server/python/tests/integration/test_tph_m2m_shadowed_generated.py +++ b/server/python/tests/integration/test_tph_m2m_shadowed_generated.py @@ -38,7 +38,7 @@ # Auth (base, @discriminator "type") --helpers--> Tag [non-TPH target] # BridgeAuth (subtype) --helpers--> PriorityTicket [SHADOWS the name; TPH target] -# CopayAuth (subtype) [inherits, unshadowed] +# CouponAuth (subtype) [inherits, unshadowed] _META = { "metadata.root": { "package": "acme::auth", @@ -58,7 +58,7 @@ "children": [ {"source.rdb": {"@table": "auths"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "type", "@values": ["Bridge", "Copay"]}}, + {"field.enum": {"name": "type", "@values": ["Bridge", "Coupon"]}}, {"field.string": {"name": "reference", "@required": True, "@maxLength": 80}}, {"relationship.association": { "name": "helpers", "@cardinality": "many", @@ -80,9 +80,9 @@ ], }}, {"object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ {"field.string": {"name": "payer", "@maxLength": 80}}, ], @@ -284,12 +284,12 @@ def _build_app() -> tuple[FastAPI, _StrictRepo]: @pytest.fixture() def client_and_repo(): app, repo = _build_app() - # id=1 Bridge, id=2 Copay; tag 10; tickets 20 (Priority) and 21 (Standard). + # id=1 Bridge, id=2 Coupon; tag 10; tickets 20 (Priority) and 21 (Standard). # auth 1 has tag 10 AND ticket 20; auth 2 has tag 10 only. repo.seed( auths=[ {"id": 1, "type": "Bridge", "reference": "b1", "quantity": 3}, - {"id": 2, "type": "Copay", "reference": "c1", "payer": "acme"}, + {"id": 2, "type": "Coupon", "reference": "c1", "payer": "acme"}, ], tags=[{"id": 10, "name": "shared"}], tickets=[ @@ -324,13 +324,13 @@ def test_base_mount_threads_an_explicit_none_and_returns_the_base_targets( def test_non_shadowing_subtype_mount_threads_an_explicit_none( client_and_repo, ) -> None: - # CopayAuth inherits the BASE's helpers→Tag unchanged: same widened arity, + # CouponAuth inherits the BASE's helpers→Tag unchanged: same widened arity, # gated by its own discriminator value, None for the target. client, repo = client_and_repo - resp = client.get("/api/auths/copay/2/helpers") + resp = client.get("/api/auths/coupon/2/helpers") assert resp.status_code == 200 assert [t["id"] for t in resp.json()] == [10] - assert repo.calls[-1] == ("Copay", 2, None) + assert repo.calls[-1] == ("Coupon", 2, None) def test_shadowing_subtype_mount_threads_its_own_target_discriminator( @@ -349,7 +349,7 @@ def test_shadowing_subtype_mount_threads_its_own_target_discriminator( def test_shadowed_subtype_gate_answers_empty_for_a_siblings_id( client_and_repo, ) -> None: - # Rule (c) composes unchanged under the shadow: id=2 is a Copay row, so the + # Rule (c) composes unchanged under the shadow: id=2 is a Coupon row, so the # bridge-segment mount short-circuits to [] before the join is ever reached. client, repo = client_and_repo resp = client.get("/api/auths/bridge/2/helpers") diff --git a/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts b/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts index e1f8cf0f8c..77e84bbc95 100644 --- a/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts +++ b/server/typescript/packages/codegen-ts-react/test/tph-form.test.ts @@ -30,7 +30,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -46,11 +46,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts index 17b21cb52e..2a03fe1a3d 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/tph-grid.test.ts @@ -27,7 +27,7 @@ import { renderColumnsFile } from "../src/templates/columns-file.js"; import { makeRenderContext, buildPkMap, buildRelationMap, runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { entityFile } from "@metaobjectsdev/test-generators"; -async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: MetaObject; copay: MetaObject }> { +async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: MetaObject; coupon: MetaObject }> { const loader = new MetaDataLoader(); const { root, errors } = await loader.load([ new InMemoryStringSource( @@ -41,7 +41,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, { "layout.dataGrid": { name: "default", "@columns": ["type", "id"] } }, @@ -58,13 +58,13 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", // Opted IN to a per-subtype grid by the OPT_IN predicate below — no // metadata attribute is involved any more. children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -76,7 +76,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me ]); if (errors.length > 0) throw new Error(errors.map((e) => e.message).join("; ")); const find = (n: string) => root.objects().find((o) => o.name === n)! as MetaObject; - return { root, base: find("Auth"), bridge: find("BridgeAuth"), copay: find("CopayAuth") }; + return { root, base: find("Auth"), bridge: find("BridgeAuth"), coupon: find("CouponAuth") }; } /** Same hierarchy, but the base's grid carries an `@filter` preset — the arm where an @@ -96,7 +96,7 @@ async function loadTphFiltered(): Promise<{ root: MetaRoot }> { "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"], "@filterable": true } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"], "@filterable": true } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, { @@ -130,7 +130,7 @@ async function loadTphFiltered(): Promise<{ root: MetaRoot }> { /** The per-subtype-grid opt-in, as an adopter would write it in metaobjects.config.ts. * Declared ONCE and passed to BOTH generators, which is the discipline the option * documents: two disagreeing predicates reproduce #287 exactly. */ -const OPT_IN = (e: MetaObject) => e.name === "CopayAuth"; +const OPT_IN = (e: MetaObject) => e.name === "CouponAuth"; function ctxFor(root: MetaRoot) { return makeRenderContext({ @@ -155,28 +155,28 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { expect(out).toContain('id: "type"'); expect(out).toContain('id: "id"'); expect(out).toContain('id: "quantity"'); - expect(out).toContain('id: "copayAmount"'); + expect(out).toContain('id: "couponAmount"'); // Discriminator column renders as a badge. expect(out).toMatch(/id: "type"[\s\S]*?renderer: "badge"/); }); test("grid filter: base emits; a subtype emits only when tphSubtypeGrids opts it in", async () => { - const { base, bridge, copay } = await loadTph(); + const { base, bridge, coupon } = await loadTph(); const gen = tanstackGrid({ tphSubtypeGrids: OPT_IN }); expect(gen.filter!(base)).toBe(true); // polymorphic grid expect(gen.filter!(bridge)).toBe(false); // inherits layout, but not opted in - expect(gen.filter!(copay)).toBe(true); // opted in + expect(gen.filter!(coupon)).toBe(true); // opted in }); test("tphSubtypeGrids defaults OFF — no TPH subtype emits without one", async () => { // The default is what every existing project gets, so it is the arm most worth // pinning: an option that silently defaulted ON would change output for models that // never asked for a per-subtype grid. - const { base, bridge, copay } = await loadTph(); + const { base, bridge, coupon } = await loadTph(); for (const gen of [tanstackGrid(), tanstackGridHook()]) { expect(gen.filter!(base)).toBe(true); expect(gen.filter!(bridge)).toBe(false); - expect(gen.filter!(copay)).toBe(false); + expect(gen.filter!(coupon)).toBe(false); } }); @@ -187,17 +187,17 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { // missing that clause, so BridgeAuth got a .grid.ts whose sibling .columns.tsx never // exists. With the clause now driven by a caller-supplied predicate, agreement is the // CALLER's discipline — so this asserts it holds when the same predicate is passed. - const { base, bridge, copay } = await loadTph(); + const { base, bridge, coupon } = await loadTph(); const hook = tanstackGridHook({ tphSubtypeGrids: OPT_IN }); expect(hook.filter!(base)).toBe(true); expect(hook.filter!(bridge)).toBe(false); - expect(hook.filter!(copay)).toBe(true); + expect(hook.filter!(coupon)).toBe(true); }); test("an opted-in subtype gets BOTH artifacts; an opted-out one gets NEITHER", async () => { // The pairing invariant on the OPT-IN path, asserted on a real run's output rather // than on the predicates. `tphSubtypeGrids` is passed to both generators — the - // discipline the option documents — so CopayAuth must get the pair and BridgeAuth + // discipline the option documents — so CouponAuth must get the pair and BridgeAuth // must get nothing. A one-sided wiring shows up here as a file set, not a subtlety. const { root } = await loadTph(); const tmp = mkdtempSync(join(tmpdir(), "tph-grid-optin-")); @@ -214,8 +214,8 @@ describe("FR-017 Tier 3 — TPH TanStack grid", () => { metadata: root, }); const files = readdirSync(tmp); - expect(files).toContain("CopayAuth.columns.tsx"); - expect(files).toContain("CopayAuth.grid.ts"); + expect(files).toContain("CouponAuth.columns.tsx"); + expect(files).toContain("CouponAuth.grid.ts"); expect(files).not.toContain("BridgeAuth.columns.tsx"); expect(files).not.toContain("BridgeAuth.grid.ts"); } finally { diff --git a/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts b/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts index a84efcc244..2d18d9d244 100644 --- a/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts +++ b/server/typescript/packages/codegen-ts-tanstack/test/tph-hooks.test.ts @@ -30,7 +30,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -46,11 +46,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -107,11 +107,11 @@ describe("FR-017 Tier 3 — TPH TanStack hooks", () => { expect(out).toContain("export function useCreateBridgeAuth("); expect(out).toContain("export function useUpdateBridgeAuth("); expect(out).toContain("export function useDeleteBridgeAuth("); - // Per-subtype CopayAuth too. - expect(out).toContain("export function useCreateCopayAuth("); + // Per-subtype CouponAuth too. + expect(out).toContain("export function useCreateCouponAuth("); // Sub-path derived from the lowercased discriminator value. expect(out).toContain("/bridge"); - expect(out).toContain("/copay"); + expect(out).toContain("/coupon"); // Create input omits the discriminator. expect(out).toContain('Omit'); }); diff --git a/server/typescript/packages/codegen-ts/src/constants.ts b/server/typescript/packages/codegen-ts/src/constants.ts index d16ad395bc..426c94bca6 100644 --- a/server/typescript/packages/codegen-ts/src/constants.ts +++ b/server/typescript/packages/codegen-ts/src/constants.ts @@ -143,7 +143,7 @@ export const RETIRED_CODEGEN_ATTRS: readonly RetiredCodegenAttr[] = [ name: "emitGrid", replacement: 'pass the `tphSubtypeGrids` option — tanstackGrid({ tphSubtypeGrids: (e) => e.name === ' + - '"CopayAuth" }) — and pass the SAME predicate to tanstackGridHook(), or the emitted ' + + '"CouponAuth" }) — and pass the SAME predicate to tanstackGridHook(), or the emitted ' + '.grid.ts has no .columns.tsx to import. This one is an opt-IN, so a `filter` ' + 'cannot express it: a filter is ANDed with the built-in gates and can only narrow', }, diff --git a/server/typescript/packages/codegen-ts/src/reference/routes.ts b/server/typescript/packages/codegen-ts/src/reference/routes.ts index a1c2cf0197..2f10b888e2 100644 --- a/server/typescript/packages/codegen-ts/src/reference/routes.ts +++ b/server/typescript/packages/codegen-ts/src/reference/routes.ts @@ -659,7 +659,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, diff --git a/server/typescript/packages/codegen-ts/src/templates/routes-file.ts b/server/typescript/packages/codegen-ts/src/templates/routes-file.ts index 247844f84c..e0c1158dc4 100644 --- a/server/typescript/packages/codegen-ts/src/templates/routes-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/routes-file.ts @@ -586,7 +586,7 @@ function renderTphRoutesFile( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: "/" + segment, diff --git a/server/typescript/packages/codegen-ts/test/api-model.test.ts b/server/typescript/packages/codegen-ts/test/api-model.test.ts index 157e4a09c5..0e3984954e 100644 --- a/server/typescript/packages/codegen-ts/test/api-model.test.ts +++ b/server/typescript/packages/codegen-ts/test/api-model.test.ts @@ -36,7 +36,7 @@ const AUTH_TPH = [ "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts index 79f2fb80e8..1a38ceee98 100644 --- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts @@ -259,14 +259,14 @@ describe("the three shapes", () => { const c = corpusCase("tph-shared-marks"); const tree = await contractTree(c); const keysOf = (path: string): string[] => Object.keys(jsonAt(tree, path)["properties"] as JsonDoc); - const copay = "schemas/acme/auth/CopayAuth"; + const coupon = "schemas/acme/auth/CouponAuth"; const bridge = "schemas/acme/auth/BridgeAuth"; - const row = { id: 1, type: "Copay", reference: "R-1", auditRef: "A-1" }; - expect(validatorOf(tree, `${copay}.schema.json`)(row)).toBe(true); - expect(keysOf(`${copay}.schema.json`)).not.toContain("token"); + const row = { id: 1, type: "Coupon", reference: "R-1", auditRef: "A-1" }; + expect(validatorOf(tree, `${coupon}.schema.json`)(row)).toBe(true); + expect(keysOf(`${coupon}.schema.json`)).not.toContain("token"); expect(keysOf(`${bridge}.schema.json`)).not.toContain("token"); for (const shape of ["create", "update"]) { - expect(keysOf(`${copay}.${shape}.schema.json`)).toEqual(["reference"]); + expect(keysOf(`${coupon}.${shape}.schema.json`)).toEqual(["reference"]); expect(keysOf(`${bridge}.${shape}.schema.json`)).toEqual(["reference"]); } diff --git a/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts b/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts index 2aa37d6a30..fbd18466fa 100644 --- a/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/build-cube-model.test.ts @@ -170,7 +170,7 @@ describe("Table A — what becomes a cube", () => { [ table("auths"), longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, pk, ], { "@discriminator": "type" }, @@ -1501,7 +1501,7 @@ describe("Table H — the canonical model", () => { // The other canonical entities (Node, Session, Measurement, the Auth family, AllTypes) and the // join-path cubes carry no report of Table H's; only their presence is asserted here. expect(model.cubes.map((c) => c.name)).toEqual([ - "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CopayAuth", "PriorAuthAuth", + "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth", "AllTypes", "Gadget", "GadgetEvent", "Entry", "Node_fkParent", "ProgramRosterFacts", "ProgramLongWeeksFacts", "ProgramFlagRosterFacts", "ProgramSessionsFacts", "ProgramSessions_fkWeek", ]); diff --git a/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts b/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts index f541f5c459..c2a5e29c65 100644 --- a/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/cube-model-canonical.test.ts @@ -18,14 +18,14 @@ describe("the cube-model canonical golden", () => { "model/cubes/Asset.yml", "model/cubes/Auth.yml", "model/cubes/BridgeAuth.yml", - "model/cubes/CopayAuth.yml", + "model/cubes/CouponAuth.yml", "model/cubes/Entry.yml", "model/cubes/Gadget.yml", "model/cubes/GadgetEvent.yml", "model/cubes/Measurement.yml", "model/cubes/Node.yml", "model/cubes/Node_fkParent.yml", - "model/cubes/PriorAuthAuth.yml", + "model/cubes/PermitAuth.yml", "model/cubes/Program.yml", "model/cubes/ProgramFlagRosterFacts.yml", "model/cubes/ProgramLongWeeksFacts.yml", diff --git a/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts b/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts index 6e793ea834..300be13b7b 100644 --- a/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/cube-yaml.test.ts @@ -1154,7 +1154,7 @@ describe("parse oracle", () => { test("the canonical cubes parse to the model's values", async () => { const model = await canonicalModel(); expect(model.cubes.map((c) => c.name)).toEqual([ - "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CopayAuth", "PriorAuthAuth", + "Program", "Week", "Node", "Session", "Measurement", "Asset", "Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth", "AllTypes", "Gadget", "GadgetEvent", "Entry", "Node_fkParent", "ProgramRosterFacts", "ProgramLongWeeksFacts", "ProgramFlagRosterFacts", "ProgramSessionsFacts", "ProgramSessions_fkWeek", ]); diff --git a/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts b/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts index 229ebaf4a7..3bc606a3b1 100644 --- a/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/report-rollups.test.ts @@ -519,7 +519,7 @@ describe("selection — a report writes into its @from cube whenever that cube i [ { "source.rdb": { "@table": "auths" } }, longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { name: "status" } }, pk, ], diff --git a/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts b/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts index 81c4df6054..aca7d50cc8 100644 --- a/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts +++ b/server/typescript/packages/codegen-ts/test/cube/report-spine.test.ts @@ -470,7 +470,7 @@ describe("other spine shapes", () => { entity("Auth", [ table("auths"), longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { name: "reference" } }, pk, ], { "@discriminator": "type" }), @@ -508,7 +508,7 @@ describe("other spine shapes", () => { entity("Auth", [ table("auths"), longId, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "programId" } }, { "field.int": { name: "quantity" } }, pk, diff --git a/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json b/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json index 91ba472b73..17c0607b62 100644 --- a/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json +++ b/server/typescript/packages/codegen-ts/test/fixtures/extends-chain.json @@ -30,18 +30,18 @@ "children": [ { "source.rdb": { "@table": "auths" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@values": ["Copay"] } }, + { "field.enum": { "name": "kind", "@values": ["Coupon"] } }, { "identity.primary": { "name": "pk", "@fields": "id", "@generation": "increment" } } ] } }, { "object.entity": { - "name": "CopayAuth", + "name": "CouponAuth", "extends": "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", "children": [ - { "field.long": { "name": "copayAmount", "@column": "copay_cents" } } + { "field.long": { "name": "couponAmount", "@column": "coupon_cents" } } ] } } diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts index f79aff45db..73b575e9cc 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts @@ -97,7 +97,7 @@ const FIXTURE = JSON.stringify({ "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], diff --git a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts index 6d84463db9..9532457a9c 100644 --- a/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-extends-chain.test.ts @@ -55,17 +55,17 @@ const MODEL = { children: [ { "source.rdb": { "@table": "zz_auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "kind", "@values": ["Copay"] } }, + { "field.enum": { name: "kind", "@values": ["Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ], }, }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.long": { name: "copayAmount", "@column": "zz_copay_cents" } }], + "@discriminatorValue": "Coupon", + children: [{ "field.long": { name: "couponAmount", "@column": "zz_coupon_cents" } }], }, }, ], @@ -150,15 +150,15 @@ describe("names artifacts extend rather than restate", () => { test("a TPH subtype spreads the WHOLE base — the shared table is named once", async () => { const { tree, dir } = await generate(); try { - const sub = tree["CopayAuth.names.ts"]; + const sub = tree["CouponAuth.names.ts"]; expect(sub).toContain('import { AuthNames } from "./Auth.names"'); // A TPH subtype spreads the base's SOURCES — the shared table is named once, on the // base — rather than the whole artifact. Spreading the whole thing would carry the // base's `name`/`subType` onto the child, which are the child's own now. expect(sub).toContain("...AuthNames.sources,"); - expect(sub).toContain('name: "CopayAuth"'); + expect(sub).toContain('name: "CouponAuth"'); expect(sub).toContain("...AuthNames.fields,"); - expect(sub).toContain('copayAmount: { name: "copayAmount", column: "zz_copay_cents" }'); + expect(sub).toContain('couponAmount: { name: "couponAmount", column: "zz_coupon_cents" }'); // The whole point: the subtype used to restate the base's table name and every one // of its columns. expect(sub).not.toContain("zz_auths"); @@ -178,12 +178,12 @@ describe("names artifacts extend rather than restate", () => { const { writeFileSync } = await import("node:fs"); writeFileSync(probe, [ `import { AuthorNames } from "./Author.names";`, - `import { CopayAuthNames } from "./CopayAuth.names";`, + `import { CouponAuthNames } from "./CouponAuth.names";`, // An INHERITED column, reached through the spread. `const a: "zz_made_at" = AuthorNames.fields.createdAt.column;`, // An inherited TOP-LEVEL member, reached through the whole-base spread. - `const b: "zz_auths" = CopayAuthNames.sources.primary.table;`, - `const c: "zz_copay_cents" = CopayAuthNames.fields.copayAmount.column;`, + `const b: "zz_auths" = CouponAuthNames.sources.primary.table;`, + `const c: "zz_coupon_cents" = CouponAuthNames.fields.couponAmount.column;`, `export const probe = [a, b, c];`, ].join("\n"), "utf8"); @@ -306,12 +306,12 @@ describe("a key-only abstract is a link in the chain, not a node to walk past", describe("a scoped run still names the shared table", () => { test("generating only the TPH subtype emits a base its sources actually reach", async () => { - // `meta gen --entities CopayAuth`. Pass 1 emits the subtype; pass 2 walks up to `Auth` + // `meta gen --entities CouponAuth`. Pass 1 emits the subtype; pass 2 walks up to `Auth` // and used to render it as a FRAGMENT unconditionally — and a fragment declares no // source, by design, because it has no physical name. But `Auth` DOES have one: it is // the TPH base, and the shared table is named on it. So the base came out with // `sources: {}` while the subtype emitted `...AuthNames.sources`, and the entity module - // referenced `CopayAuthNames.sources.primary.table` — a member that resolved to + // referenced `CouponAuthNames.sources.primary.table` — a member that resolved to // nothing. "Fragment" means "declares no source", so it is DERIVED from the source now // rather than asserted by the caller. const { root, errors } = await new MetaDataLoader().load([ @@ -327,7 +327,7 @@ describe("a scoped run still names the shared table", () => { generators: [namesFile(), entityFile()], }), metadata: root, - entityFilter: ["CopayAuth"], + entityFilter: ["CouponAuth"], }); const tree: Record = {}; const walk = (d: string): void => { @@ -348,8 +348,8 @@ describe("a scoped run still names the shared table", () => { const probe = join(dir, "zz-probe.ts"); const { writeFileSync } = await import("node:fs"); writeFileSync(probe, [ - `import { CopayAuthNames } from "./CopayAuth.names";`, - `const t: "zz_auths" = CopayAuthNames.sources.primary.table;`, + `import { CouponAuthNames } from "./CouponAuth.names";`, + `const t: "zz_auths" = CouponAuthNames.sources.primary.table;`, `export const probe = [t];`, ].join("\n"), "utf8"); @@ -393,7 +393,7 @@ describe("namesFile({ filter }) narrows emission without breaking the extends ch expect(names).toEqual(["Author.names.ts", "BaseEntity.names.ts"]); // The TPH pair belongs to another tier here and must be gone. expect(tree["Auth.names.ts"]).toBeUndefined(); - expect(tree["CopayAuth.names.ts"]).toBeUndefined(); + expect(tree["CouponAuth.names.ts"]).toBeUndefined(); // And the surviving artifact still really extends the base it kept. expect(tree["Author.names.ts"]).toContain("BaseEntityNames"); } finally { @@ -406,7 +406,7 @@ describe("namesFile({ filter }) narrows emission without breaking the extends ch try { const names = Object.keys(tree).filter((f) => f.endsWith(".names.ts")).sort(); expect(names).toEqual([ - "Auth.names.ts", "Author.names.ts", "BaseEntity.names.ts", "CopayAuth.names.ts", + "Auth.names.ts", "Author.names.ts", "BaseEntity.names.ts", "CouponAuth.names.ts", ]); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/server/typescript/packages/codegen-ts/test/names.test.ts b/server/typescript/packages/codegen-ts/test/names.test.ts index 439513a281..472f5b9e89 100644 --- a/server/typescript/packages/codegen-ts/test/names.test.ts +++ b/server/typescript/packages/codegen-ts/test/names.test.ts @@ -354,25 +354,25 @@ describe("resolveObjectNames — extends chain", () => { children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Copay"] } }, + { "field.enum": { name: "type", "@values": ["Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ], }, }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.long": { name: "copayAmount", "@column": "copay_cents" } }], + "@discriminatorValue": "Coupon", + children: [{ "field.long": { name: "couponAmount", "@column": "coupon_cents" } }], }, }, ]); - const n = resolveObjectNames(obj(root, "CopayAuth"), "snake_case"); + const n = resolveObjectNames(obj(root, "CouponAuth"), "snake_case"); expect(n?.superNames?.name).toBe("Auth"); // The whole point of the TPH case: the subtype restated `auths` and every base column. expect(n?.inheritsSource).toBe(true); - expect(Object.keys(n?.ownFields ?? {})).toEqual(["copayAmount"]); + expect(Object.keys(n?.ownFields ?? {})).toEqual(["couponAmount"]); }); test("a base with no own fields and no source is NOT an artifact — there is nothing to extend", async () => { diff --git a/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts b/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts index 0846d75266..24f6eee3cd 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts @@ -1,27 +1,27 @@ // Phase 5, bug TPH-scope: a TPH subtype shares its base's table, so a view whose base is a // subtype, or whose join or origin.first lands on one, must add the subtype's discriminator -// predicate. Without it a "copay authorizations" view read every authorization row. +// predicate. Without it a "coupon authorizations" view read every authorization row. import { describe, test, expect } from "bun:test"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; const ENTITIES = [ - { "object.entity": { name: "CopayCard", children: [ - { "source.rdb": { "@table": "copay_cards" } }, + { "object.entity": { name: "CouponCard", children: [ + { "source.rdb": { "@table": "coupon_cards" } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, { "object.entity": { name: "Authorization", "@discriminator": "type", children: [ { "source.rdb": { "@table": "authorizations" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@required": true, "@values": ["Copay", "Prior", "Medical", "Pharmacy"], "@intValueMap": { Copay: 1, Prior: 2, Medical: 3, Pharmacy: 4 } } }, + { "field.enum": { name: "type", "@required": true, "@values": ["Coupon", "Prior", "Medical", "Pharmacy"], "@intValueMap": { Coupon: 1, Prior: 2, Medical: 3, Pharmacy: 4 } } }, { "field.string": { name: "code" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, - { "object.entity": { name: "CopayAuthorization", extends: "Authorization", "@discriminatorValue": "Copay", children: [ - { "field.long": { name: "copayCardId" } }, - { "identity.reference": { name: "copayCard", "@fields": "copayCardId", "@references": "CopayCard" } }, + { "object.entity": { name: "CouponAuthorization", extends: "Authorization", "@discriminatorValue": "Coupon", children: [ + { "field.long": { name: "couponCardId" } }, + { "identity.reference": { name: "couponCard", "@fields": "couponCardId", "@references": "CouponCard" } }, ] } }, // An abstract level between the base and two concrete subtypes: its rows are both subtypes'. { "object.entity": { name: "BenefitAuthorization", extends: "Authorization", abstract: true, children: [ @@ -41,11 +41,11 @@ async function viewSql(projections: unknown[]): Promise { describe("TPH-scope — a view over a TPH subtype carries its discriminator", () => { test("a subtype base filters the shared table to its rows", async () => { - const sql = await viewSql([{ "object.projection": { name: "CopayAuthView", children: [ - { "source.rdb": { "@kind": "view", "@table": "v_copay_auth" } }, - { "field.long": { name: "id", extends: "CopayAuthorization.id" } }, - { "field.string": { name: "code", extends: "CopayAuthorization.code" } }, - { "identity.primary": { name: "id", extends: "CopayAuthorization.id" } }, + const sql = await viewSql([{ "object.projection": { name: "CouponAuthView", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_coupon_auth" } }, + { "field.long": { name: "id", extends: "CouponAuthorization.id" } }, + { "field.string": { name: "code", extends: "CouponAuthorization.code" } }, + { "identity.primary": { name: "id", extends: "CouponAuthorization.id" } }, ] } }]); expect(sql).toContain("FROM public.authorizations c"); expect(sql).toContain("WHERE c.type = 1"); @@ -54,13 +54,13 @@ describe("TPH-scope — a view over a TPH subtype carries its discriminator", () test("a join onto a subtype scopes the join, not the base rows", async () => { const sql = await viewSql([{ "object.projection": { name: "CardAuthCount", children: [ { "source.rdb": { "@kind": "view", "@table": "v_card_auth_count" } }, - { "field.long": { name: "id", extends: "CopayCard.id" } }, - { "field.int": { name: "auths", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CopayAuthorization.id", "@via": "CopayCard.copayAuthorizations" } }] } }, - { "field.string": { name: "latestCode", children: [{ "origin.first": { "@of": "CopayAuthorization.code", "@via": "CopayCard.copayAuthorizations", "@orderBy": ["id:desc"] } }] } }, - { "identity.primary": { name: "id", extends: "CopayCard.id" } }, + { "field.long": { name: "id", extends: "CouponCard.id" } }, + { "field.int": { name: "auths", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CouponAuthorization.id", "@via": "CouponCard.couponAuthorizations" } }] } }, + { "field.string": { name: "latestCode", children: [{ "origin.first": { "@of": "CouponAuthorization.code", "@via": "CouponCard.couponAuthorizations", "@orderBy": ["id:desc"] } }] } }, + { "identity.primary": { name: "id", extends: "CouponCard.id" } }, ] } }]); - expect(sql).toMatch(/LEFT OUTER JOIN public\.authorizations (\w+) ON \1\.copay_card_id = c\.id AND \1\.type = 1/); - expect(sql).toMatch(/FROM public\.authorizations (\w+) WHERE \1\.copay_card_id = c\.id AND \1\.type = 1 ORDER BY/); + expect(sql).toMatch(/LEFT OUTER JOIN public\.authorizations (\w+) ON \1\.coupon_card_id = c\.id AND \1\.type = 1/); + expect(sql).toMatch(/FROM public\.authorizations (\w+) WHERE \1\.coupon_card_id = c\.id AND \1\.type = 1 ORDER BY/); expect(sql).not.toContain("WHERE c.type"); }); diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 0532446e17..1f1b038744 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -843,11 +843,11 @@ describe("ADR-0034 — the cube-model reference is byte-identical to the built-i // facts cube; ProgramSessions reaches its facts through the Session -> Week reference. expect("tree" in a ? a.tree.map(([p]) => p) : a).toEqual([ "model/cubes/AllTypes.yml", "model/cubes/Asset.yml", "model/cubes/Auth.yml", "model/cubes/BridgeAuth.yml", - "model/cubes/CopayAuth.yml", + "model/cubes/CouponAuth.yml", "model/cubes/Entry.yml", "model/cubes/Gadget.yml", "model/cubes/GadgetEvent.yml", "model/cubes/Measurement.yml", "model/cubes/Node.yml", "model/cubes/Node_fkParent.yml", - "model/cubes/PriorAuthAuth.yml", "model/cubes/Program.yml", "model/cubes/ProgramFlagRosterFacts.yml", + "model/cubes/PermitAuth.yml", "model/cubes/Program.yml", "model/cubes/ProgramFlagRosterFacts.yml", "model/cubes/ProgramLongWeeksFacts.yml", "model/cubes/ProgramRosterFacts.yml", "model/cubes/ProgramSessionsFacts.yml", "model/cubes/ProgramSessions_fkWeek.yml", "model/cubes/ReferralAuth.yml", "model/cubes/Session.yml", "model/cubes/Week.yml", "model/views/ProgramFlagRoster.yml", "model/views/ProgramLongWeeks.yml", diff --git a/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts b/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts index 0dde01b860..1ef5812c5c 100644 --- a/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts +++ b/server/typescript/packages/codegen-ts/test/relation-resolver-m2m-unpairable.test.ts @@ -32,7 +32,7 @@ const MODEL = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "relationship.association": { name: "bridgeTags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, diff --git a/server/typescript/packages/codegen-ts/test/routes-expose.test.ts b/server/typescript/packages/codegen-ts/test/routes-expose.test.ts index da04e331f0..53d6c99db5 100644 --- a/server/typescript/packages/codegen-ts/test/routes-expose.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-expose.test.ts @@ -29,7 +29,7 @@ const META = JSON.stringify({ // TPH base + subtype: the polymorphic mount is read-only BY CONSTRUCTION. { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts b/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts index a0b6a1fd0b..4f1e71347f 100644 --- a/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-hono-parity.test.ts @@ -32,7 +32,7 @@ const META = JSON.stringify({ // TPH base + two subtypes. { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts b/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts index aaa6105259..9ed1ed116b 100644 --- a/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts +++ b/server/typescript/packages/codegen-ts/test/routes-register-all.test.ts @@ -28,7 +28,7 @@ const META = JSON.stringify({ // TPH: the base is registered, the subtype is not (its routes live in the base's file). { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts index 0733e2f934..392ab717b9 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-discriminator.test.ts @@ -2,7 +2,7 @@ // // For an entity with @discriminator + concrete subtypes carrying // @discriminatorValue, entityFile additionally emits: -// - The union type `Auth = BridgeAuth | CopayAuth | ...` +// - The union type `Auth = BridgeAuth | CouponAuth | ...` // - Type guards `isBridgeAuth(a): a is BridgeAuth` // - The `parseAuth(row)` dispatcher // @@ -36,7 +36,7 @@ async function loadTph() { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, @@ -54,13 +54,13 @@ async function loadTph() { }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ { "field.decimal": { - name: "copayAmount", + name: "couponAmount", "@precision": 10, "@scale": 2, }, @@ -77,8 +77,8 @@ async function loadTph() { if (errors.length > 0) throw new Error(errors.map((e) => e.message).join("; ")); const base = root.objects().find((o) => o.name === "Auth")! as MetaObject; const bridge = root.objects().find((o) => o.name === "BridgeAuth")! as MetaObject; - const copay = root.objects().find((o) => o.name === "CopayAuth")! as MetaObject; - return { root, base, bridge, copay }; + const coupon = root.objects().find((o) => o.name === "CouponAuth")! as MetaObject; + return { root, base, bridge, coupon }; } describe("FR-017 Tier 1 — renderTphDiscriminatorUnion", () => { @@ -87,19 +87,19 @@ describe("FR-017 Tier 1 — renderTphDiscriminatorUnion", () => { const out = renderTphDiscriminatorUnion(base, root)!.toString(); // Union type spans every concrete subtype, base does not appear in members. - expect(out).toContain("export type Auth = BridgeAuth | CopayAuth"); + expect(out).toContain("export type Auth = BridgeAuth | CouponAuth"); // Type guards per subtype. expect(out).toContain("export function isBridgeAuth(value: Auth)"); - expect(out).toContain("export function isCopayAuth(value: Auth)"); + expect(out).toContain("export function isCouponAuth(value: Auth)"); expect(out).toContain('value.type === "Bridge"'); - expect(out).toContain('value.type === "Copay"'); + expect(out).toContain('value.type === "Coupon"'); // Dispatcher function reads the discriminator without committing to a // subtype yet, then dispatches via switch. expect(out).toContain("export function parseAuth(row: unknown): Auth"); expect(out).toContain('case "Bridge":'); - expect(out).toContain('case "Copay":'); + expect(out).toContain('case "Coupon":'); }); test("returns null for an entity that has no @discriminator", async () => { @@ -116,10 +116,10 @@ describe("FR-017 Tier 1 — subtype Zod pins discriminator via z.literal", () => expect(out).toContain('z.literal("Bridge")'); }); - test("CopayAuth's Zod schema pins type to z.literal(\"Copay\")", async () => { - const { copay } = await loadTph(); - const out = renderZodValidators(copay).toString(); - expect(out).toContain('z.literal("Copay")'); + test("CouponAuth's Zod schema pins type to z.literal(\"Coupon\")", async () => { + const { coupon } = await loadTph(); + const out = renderZodValidators(coupon).toString(); + expect(out).toContain('z.literal("Coupon")'); }); test("BridgeAuth's schema still emits the subtype-only field", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts index b1f2db3478..e9c939ea78 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-drizzle.test.ts @@ -33,7 +33,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" }, @@ -47,19 +47,19 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me extends: "Auth", "@discriminatorValue": "Bridge", // @required on a subtype-only column — must STILL be nullable in - // the single TPH table (Copay rows store NULL here). + // the single TPH table (Coupon rows store NULL here). children: [{ "field.int": { name: "quantity", "@required": true } }], }, }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ { "field.decimal": { - name: "copayAmount", + name: "couponAmount", "@precision": 10, "@scale": 2, }, @@ -101,7 +101,7 @@ describe("FR-017 Tier 2 — Drizzle TPH single-table", () => { expect(out).toContain("type:"); // Subtype-only columns folded into the single table. expect(out).toContain("quantity:"); - expect(out).toContain("copay_amount"); + expect(out).toContain("coupon_amount"); }); test("subtype-only columns are nullable even when the field is @required", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts index 3741a9dfa2..9780eed677 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-queries.test.ts @@ -37,7 +37,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -53,11 +53,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts index 4c809bbf9c..afe6964cad 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-read-schema.test.ts @@ -33,7 +33,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, // increment generation → InsertSchema OMITS id, read schema KEEPS it. { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, @@ -50,11 +50,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -122,7 +122,7 @@ describe("FR-017 Tier 2 — per-subtype full read schema", () => { // Exactly one `export type Auth =` — the discriminated union. const count = (out.match(/export type Auth =/g) ?? []).length; expect(count).toBe(1); - expect(out).toContain("export type Auth = BridgeAuth | CopayAuth"); + expect(out).toContain("export type Auth = BridgeAuth | CouponAuth"); // The raw single-table row type is emitted under the non-colliding `AuthRow`. expect(out).toContain("export type AuthRow ="); }); diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts index a1dd540566..0184cafa3e 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier2-routes.test.ts @@ -33,7 +33,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -49,11 +49,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, @@ -94,7 +94,7 @@ describe("FR-017 Tier 2 — TPH routes file", () => { const out = renderRoutesFile(base, ctxFor(root)); // Segment is the lowercased discriminator value. expect(out).toContain('Auth.$path + "/bridge"'); - expect(out).toContain('Auth.$path + "/copay"'); + expect(out).toContain('Auth.$path + "/coupon"'); // Scoped via the runtime discriminator option. expect(out).toContain('discriminator: { column: "type", value: "Bridge" }'); // Create body OMITS the discriminator. @@ -104,10 +104,10 @@ describe("FR-017 Tier 2 — TPH routes file", () => { test("the polymorphic mount sends a decimal only a subtype declares as its canonical string", async () => { const { root, base } = await loadTph(); const out = renderRoutesFile(base, ctxFor(root)); - // The base declares no decimal, but its list/get serve CopayAuth rows, so the polymorphic - // mount must rewrite `copayAmount` too (ADR-0019 Amendment 1; Postgres returns "12.50"). + // The base declares no decimal, but its list/get serve CouponAuth rows, so the polymorphic + // mount must rewrite `couponAmount` too (ADR-0019 Amendment 1; Postgres returns "12.50"). const polymorphic = out.slice(out.indexOf("path: Auth.$path,"), out.indexOf('Auth.$path + "/')); - expect(polymorphic).toContain('decimalColumns: ["copayAmount"]'); + expect(polymorphic).toContain('decimalColumns: ["couponAmount"]'); }); test("routesFile generator skips TPH subtypes", async () => { diff --git a/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts b/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts index 70ef660e6e..23ee673db1 100644 --- a/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/tph-tier3-allowlists.test.ts @@ -34,7 +34,7 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me children: [ { "source.rdb": { "@table": "auths" } }, // Discriminator is filterable on the base (polymorphic GET). - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"], "@filterable": true } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"], "@filterable": true } }, { "field.long": { name: "id" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -50,11 +50,11 @@ async function loadTph(): Promise<{ root: MetaRoot; base: MetaObject; bridge: Me }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", + "@discriminatorValue": "Coupon", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts b/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts index 1a1e25f4c9..c02401a483 100644 --- a/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-m2m-credential.test.ts @@ -23,14 +23,14 @@ const MODEL = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ]}}, { "object.entity": { name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", children: [ { "field.string": { name: "pinHash", children: [{ "view.password": {} }] } }, ]}}, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.int": { name: "copayCents" } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.int": { name: "couponCents" } }, ]}}, { "object.entity": { name: "PayerAuth", children: [ { "source.rdb": { "@table": "payer_auths" } }, diff --git a/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts b/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts index e17ae51d57..d6c912afeb 100644 --- a/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts +++ b/server/typescript/packages/codegen-ts/test/tph-m2m-routes.test.ts @@ -44,7 +44,7 @@ const MODEL = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { name: "reference", "@required": true, "@maxLength": 80 } }, // Declared on the BASE: legitimate for every row of the table. { "relationship.association": { name: "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthTag" } }, @@ -55,15 +55,15 @@ const MODEL = { // Declared on a SUBTYPE, and a directed self-join onto that same subtype. { "relationship.association": { name: "linkedAuths", "@cardinality": "many", "@objectRef": "BridgeAuth", "@through": "AuthLink", "@sourceRefField": "fromAuthId" } }, ]}}, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.int": { name: "copayCents" } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.int": { name: "couponCents" } }, ]}}, // An ABSTRACT intermediate level that declares an M:N. It is neither the base nor // a concrete subtype, so it is the level an own-only filter loses entirely. { "object.entity": { name: "ScopedAuth", extends: "Auth", abstract: true, children: [ { "relationship.association": { name: "auditors", "@cardinality": "many", "@objectRef": "Tag", "@through": "AuthAudit" } }, ]}}, - { "object.entity": { name: "PriorAuthAuth", extends: "ScopedAuth", "@discriminatorValue": "PriorAuth", children: [ + { "object.entity": { name: "PermitAuth", extends: "ScopedAuth", "@discriminatorValue": "Permit", children: [ { "field.string": { name: "approver", "@maxLength": 80 } }, ]}}, // The junction references the CONCRETE subtype, not the base. That is the supported @@ -76,7 +76,7 @@ const MODEL = { { "field.long": { name: "auditAuthId", "@required": true } }, { "field.long": { name: "auditTagId", "@required": true } }, { "identity.primary": { name: "pk", "@fields": ["auditAuthId", "auditTagId"] } }, - { "identity.reference": { name: "fkAuditAuth", "@fields": "auditAuthId", "@references": "PriorAuthAuth" } }, + { "identity.reference": { name: "fkAuditAuth", "@fields": "auditAuthId", "@references": "PermitAuth" } }, { "identity.reference": { name: "fkAuditTag", "@fields": "auditTagId", "@references": "Tag" } }, ]}}, { "object.entity": { name: "AuthTag", children: [ @@ -193,13 +193,13 @@ describe("M:N traversal in a TPH hierarchy", () => { // `tags` is declared on Auth, so every subtype resolves it. A subtype resource is a // resource: it carries the same sub-resources as any other. The overlap is not // redundancy — the subtype segment is a type assertion, and only the subtype mount - // gates the source id, so /auths/bridge/{a Copay id}/tags is [] where /auths/{that + // gates the source id, so /auths/bridge/{a Coupon id}/tags is [] where /auths/{that // id}/tags is not. This is the independent oracle's rule (expectedRoutes), which // walks every SERVED object's RESOLVED relationships. const tagMounts = routes.match(/relationName: "tags"/g) ?? []; - expect(tagMounts.length).toBe(4); // the base, plus /bridge, /copay and /priorauth - const copayTags = m2mMount(routes.slice(routes.indexOf('Auth.$path + "/copay"')), "tags"); - expect(copayTags).toMatch(/sourceDiscriminator: \{ table: auths, pkColumn: \S+, column: \S+, value: "Copay",? \}/); + expect(tagMounts.length).toBe(4); // the base, plus /bridge, /coupon and /permit + const couponTags = m2mMount(routes.slice(routes.indexOf('Auth.$path + "/coupon"')), "tags"); + expect(couponTags).toMatch(/sourceDiscriminator: \{ table: auths, pkColumn: \S+, column: \S+, value: "Coupon",? \}/); }); test("an M:N from a NON-subtype onto a subtype filters the target, not the source", async () => { @@ -219,11 +219,11 @@ describe("M:N traversal in a TPH hierarchy", () => { // own. It is not on the base either, so the ONLY place it can be served is beneath // each concrete subtype under that level. const mount = m2mMount(routes, "auditors"); - expect(mount).toContain('path: Auth.$path + "/priorauth",'); + expect(mount).toContain('path: Auth.$path + "/permit",'); expect(mount).toContain("junctionTable: authAudits,"); expect(mount).toContain("targetTable: tags,"); expect(mount).toMatch( - /sourceDiscriminator: \{ table: auths, pkColumn: AuthNames\.fields\.id\.column, column: AuthNames\.fields\.type\.column, value: "PriorAuth",? \}/, + /sourceDiscriminator: \{ table: auths, pkColumn: AuthNames\.fields\.id\.column, column: AuthNames\.fields\.type\.column, value: "Permit",? \}/, ); // It is NOT mounted at the base path: Auth does not resolve `auditors`, and // ScopedAuth is abstract, so it is served nowhere else. Matches the oracle, whose @@ -235,6 +235,6 @@ describe("M:N traversal in a TPH hierarchy", () => { const routes = fileNamed(await generate(await loadModel()), "Auth.routes.ts"); expect(routes).toContain("mountCrudRoutes({ fastify: fastify, path: Auth.$path, db: db,"); expect(routes).toContain('path: Auth.$path + "/bridge",'); - expect(routes).toContain('path: Auth.$path + "/copay",'); + expect(routes).toContain('path: Auth.$path + "/coupon",'); }); }); diff --git a/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts b/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts index ad47113826..77bfbc4f20 100644 --- a/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts +++ b/server/typescript/packages/integration-tests/cube-live/cube-model-shapes.live.ts @@ -53,7 +53,7 @@ INSERT INTO matches (id, home_team_id, away_team_id) VALUES (1, 1, 2), (2, 1, 2), (3, 2, 1), (4, 3, 1), (5, 3, 2); CREATE TABLE auths (id BIGINT PRIMARY KEY, type TEXT NOT NULL); -INSERT INTO auths (id, type) VALUES (1, 'Bridge'), (2, 'Copay'), (3, 'Bridge'), (4, 'Copay'), (5, 'Copay'), (6, 'Bridge'), (7, 'Bridge'); +INSERT INTO auths (id, type) VALUES (1, 'Bridge'), (2, 'Coupon'), (3, 'Bridge'), (4, 'Coupon'), (5, 'Coupon'), (6, 'Bridge'), (7, 'Bridge'); -- programs: 1 and 3 have a profile, 2 has none; program 4 has sessions through no week (spine row, no facts). CREATE TABLE programs (id BIGINT PRIMARY KEY, title TEXT); diff --git a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts index f486d1100e..3959253251 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts @@ -43,14 +43,14 @@ const READ_PATHS = { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "identity.primary": { name: "pk", "@fields": "id", "@generation": "increment" } }, ] } }, { "object.entity": { name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", children: [ { "field.string": { name: "pinHash", "@maxLength": 100, children: [{ "view.password": {} }] } }, ] } }, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.int": { name: "copayCents" } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.int": { name: "couponCents" } }, ] } }, { "object.entity": { name: "PayerAuth", children: [ { "source.rdb": { "@table": "payer_auths" } }, @@ -132,7 +132,7 @@ export const db = drizzle(pool); "id" bigserial PRIMARY KEY, "type" varchar(16) NOT NULL, "pin_hash" varchar(100), - "copay_cents" integer + "coupon_cents" integer ); CREATE TABLE IF NOT EXISTS "payer_auths" ( "payer_id" bigint NOT NULL, @@ -140,7 +140,7 @@ export const db = drizzle(pool); PRIMARY KEY ("payer_id", "auth_id") ); INSERT INTO "payers" ("id") VALUES (1); - INSERT INTO "auths" ("id", "type", "pin_hash", "copay_cents") VALUES (1, 'Bridge', 'auth-pin-1', NULL), (2, 'Copay', NULL, 500); + INSERT INTO "auths" ("id", "type", "pin_hash", "coupon_cents") VALUES (1, 'Bridge', 'auth-pin-1', NULL), (2, 'Coupon', NULL, 500); INSERT INTO "payer_auths" ("payer_id", "auth_id") VALUES (1, 1), (1, 2);`, ); diff --git a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts index 948b836783..dc1fe8623d 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts @@ -2,7 +2,7 @@ // deployed artifact) over HTTP and drives them against the FR-017 TPH corpus. // // Mirrors api-contract-m2m-generated-server.ts but for the single-table -// table-per-hierarchy model (Auth + BridgeAuth / CopayAuth / PriorAuthAuth). It: +// table-per-hierarchy model (Auth + BridgeAuth / CouponAuth / PermitAuth). It: // 1. runs the real codegen (runGen from @metaobjectsdev/codegen-ts) over the // TPH meta into a temp dir, emitting the single Drizzle `auths` table + // per-subtype Zod/allowlists AND Auth.routes.ts — which mounts the @@ -32,7 +32,7 @@ export interface TphSeed { type: string; reference: string; quantity: number | null; - copayAmount: string | null; + couponAmount: string | null; approver: string | null; // FR-037 R1 — the @mutability "writeOnce" column, declared on the TPH BASE so // every subtype inherits it (which also exercises the resolving-accessor rule: @@ -94,7 +94,7 @@ export const db = drizzle(pool); writeFileSync(join(tmp, "db.ts"), dbModule, "utf8"); // 3. Provision the SINGLE TPH table to match the EMITTED Drizzle table. - // Subtype-only columns (quantity / copay_amount / approver) are nullable. + // Subtype-only columns (quantity / coupon_amount / approver) are nullable. // #203 / ADR-0045 — auto_created_at/auto_updated_at mirror the emitted // Auth.ts columns (physical snake_case naming). Plain `timestamp` here // (not `timestamptz`) matches the precedent in api-contract-generated-server.ts @@ -106,7 +106,7 @@ export const db = drizzle(pool); "type" text, "reference" varchar(80) NOT NULL, "quantity" integer, - "copay_amount" numeric(10,2), + "coupon_amount" numeric(10,2), "approver" varchar(80), "issued_currency" varchar(3), "auto_created_at" timestamp, @@ -152,8 +152,8 @@ export async function seedTph(connectionUri: string, seed: TphSeed): Promise [check("chk_auths_type", sql`type IN ('Bridge', 'Copay', 'PriorAuth')`)], + () => [check("chk_auths_type", sql`type IN ('Bridge', 'Coupon', 'Permit')`)], ); // Base entity: polymorphic read surface only (no polymorphic create). const AuthInsertSchema = z.object({ - type: z.enum(["Bridge", "Copay", "PriorAuth"]).optional(), + type: z.enum(["Bridge", "Coupon", "Permit"]).optional(), reference: z.string().min(1).max(80), }); const AuthUpdateSchema = AuthInsertSchema.partial(); @@ -92,10 +92,10 @@ const writeOnceInsertShape = { issuedCurrency: z.string().max(3).nullable().optional(), }; -// CopayAuth.copayAmount is decimal(10,2): a string or a JSON number in, its canonical string +// CouponAuth.couponAmount is decimal(10,2): a string or a JSON number in, its canonical string // stored, and a value the column would round or overflow refused (ADR-0019 Amendment 1, W2/W3), // as the generated write schema does it. -const copayAmount = z +const couponAmount = z .union([z.string(), z.number()]) .transform((v, ctx) => { const c = parseDecimalInput(v); @@ -108,23 +108,23 @@ const copayAmount = z }) .nullable() .optional(); -const DECIMAL_COLUMNS = ["copayAmount"] as const; +const DECIMAL_COLUMNS = ["couponAmount"] as const; // The decimal output form is the corpus's own `wire` setting (ADR-0019 Amendment 2), read from // its .metaobjects/config.json like the generated lanes, never a literal here. const DECIMAL_WIRE = nearestWireFormat(API_CONTRACT_TPH_DIR).decimals; // Per-subtype insert schemas (discriminator pinned, omitted at the route boundary). const BridgeInsert = z.object({ reference: z.string().min(1).max(80), quantity: z.number().int(), ...writeOnceInsertShape, ...autoSetInsertShape }); -const CopayInsert = z.object({ reference: z.string().min(1).max(80), copayAmount, ...writeOnceInsertShape, ...autoSetInsertShape }); -const PriorAuthInsert = z.object({ reference: z.string().min(1).max(80), approver: z.string().max(80).nullable().optional(), ...writeOnceInsertShape, ...autoSetInsertShape }); +const CouponInsert = z.object({ reference: z.string().min(1).max(80), couponAmount, ...writeOnceInsertShape, ...autoSetInsertShape }); +const PermitInsert = z.object({ reference: z.string().min(1).max(80), approver: z.string().max(80).nullable().optional(), ...writeOnceInsertShape, ...autoSetInsertShape }); // Per-subtype update schemas — NOT derived via `.partial()` (that would // carry autoCreatedAt's stamping transform into every PATCH, re-writing the // creation timestamp on every update — the exact lost-update bug this gate // exists to catch). Declared explicitly instead, omitting autoCreatedAt. const BridgeUpdate = z.object({ reference: z.string().min(1).max(80).optional(), quantity: z.number().int().optional(), ...autoSetUpdateShape }); -const CopayUpdate = z.object({ reference: z.string().min(1).max(80).optional(), copayAmount, ...autoSetUpdateShape }); -const PriorAuthUpdate = z.object({ reference: z.string().min(1).max(80).optional(), approver: z.string().max(80).nullable().optional(), ...autoSetUpdateShape }); +const CouponUpdate = z.object({ reference: z.string().min(1).max(80).optional(), couponAmount, ...autoSetUpdateShape }); +const PermitUpdate = z.object({ reference: z.string().min(1).max(80).optional(), approver: z.string().max(80).nullable().optional(), ...autoSetUpdateShape }); const numberOps = ["eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull"] as const; const stringOps = ["eq", "ne", "in", "like", "isNull"] as const; @@ -133,19 +133,19 @@ const BridgeFilterAllowlist = { reference: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, quantity: { ops: numberOps, subType: "number" as const, leadingWildcard: false }, } as const satisfies FilterAllowlist; -const CopayFilterAllowlist = { +const CouponFilterAllowlist = { id: { ops: numberOps, subType: "number" as const, leadingWildcard: false }, reference: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, - copayAmount: { ops: numberOps, subType: "number" as const, leadingWildcard: false, format: "decimal" as const }, + couponAmount: { ops: numberOps, subType: "number" as const, leadingWildcard: false, format: "decimal" as const }, } as const satisfies FilterAllowlist; -const PriorAuthFilterAllowlist = { +const PermitFilterAllowlist = { id: { ops: numberOps, subType: "number" as const, leadingWildcard: false }, reference: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, approver: { ops: stringOps, subType: "string" as const, leadingWildcard: false }, } as const satisfies FilterAllowlist; const BridgeSortAllowlist = { id: {}, reference: {}, quantity: {} } as const satisfies SortAllowlist; -const PriorAuthSortAllowlist = { id: {}, reference: {}, approver: {} } as const satisfies SortAllowlist; -const CopaySortAllowlist = { id: {}, reference: {} } as const satisfies SortAllowlist; +const PermitSortAllowlist = { id: {}, reference: {}, approver: {} } as const satisfies SortAllowlist; +const CouponSortAllowlist = { id: {}, reference: {} } as const satisfies SortAllowlist; export async function startTphServer(connectionUri: string): Promise { const pool = new pg.Pool({ connectionString: connectionUri, types: bigintAsNumberTypes }); @@ -157,7 +157,7 @@ export async function startTphServer(connectionUri: string): Promise { expect(Object.keys(one)).not.toContain("pinHash"); const auths = await getJson(server, "/api/payers/1/auths"); - expect(auths.map((r) => [r.id, r.type]).sort()).toEqual([[1, "Bridge"], [2, "Copay"]]); + expect(auths.map((r) => [r.id, r.type]).sort()).toEqual([[1, "Bridge"], [2, "Coupon"]]); for (const row of auths) expect(Object.keys(row)).not.toContain("pinHash"); } finally { if (server) await server.close(); diff --git a/server/typescript/packages/integration-tests/test/enum-intvaluemap-pg.test.ts b/server/typescript/packages/integration-tests/test/enum-intvaluemap-pg.test.ts index e330665b08..86a3f55059 100644 --- a/server/typescript/packages/integration-tests/test/enum-intvaluemap-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/enum-intvaluemap-pg.test.ts @@ -476,8 +476,8 @@ describe("int-backed field.enum under TPH — real Postgres", () => { "metadata.root": { "package": "demo", "children": [ { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ { "source.rdb": { "@table": "auths" } }, - { "field.enum": { "name": "type", "@values": ["Bridge", "Copay"], - "@intValueMap": { "Bridge": 1, "Copay": 2 } } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Coupon"], + "@intValueMap": { "Bridge": 1, "Coupon": 2 } } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "title" } }, { "field.enum": { "name": "status", "@values": ["OPEN", "SHUT"], @@ -487,8 +487,8 @@ describe("int-backed field.enum under TPH — real Postgres", () => { { "object.entity": { "name": "BridgeAuth", "extends": "demo::Auth", "@discriminatorValue": "Bridge", "children": [ { "field.int": { "name": "quantity" } } ] } }, - { "object.entity": { "name": "CopayAuth", "extends": "demo::Auth", - "@discriminatorValue": "Copay", "children": [ + { "object.entity": { "name": "CouponAuth", "extends": "demo::Auth", + "@discriminatorValue": "Coupon", "children": [ { "field.int": { "name": "amount" } } ] } } ] } }`; @@ -545,7 +545,7 @@ describe("int-backed field.enum under TPH — real Postgres", () => { SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE conname = 'auths_type_chk' `.execute(k); - // Unquoted integers, not 'Bridge'/'Copay' — the discriminator's CHECK is + // Unquoted integers, not 'Bridge'/'Coupon' — the discriminator's CHECK is // subject to the same int-backing as any other enum column. expect(chk.rows[0]?.def).toContain("1"); expect(chk.rows[0]?.def).toContain("2"); @@ -586,8 +586,8 @@ describe("int-backed field.enum under TPH — real Postgres", () => { ).execute(k); const bridges = await q.listBridgeAuths(tphDb); expect(bridges.map((r: any) => r.title).sort()).toEqual(["b", "d"]); - const copays = await q.listCopayAuths(tphDb); - expect(copays.map((r: any) => r.title)).toEqual(["c"]); + const coupons = await q.listCouponAuths(tphDb); + expect(coupons.map((r: any) => r.title)).toEqual(["c"]); }, 120_000); test("the polymorphic read dispatches on the DECODED discriminator", async () => { @@ -596,9 +596,9 @@ describe("int-backed field.enum under TPH — real Postgres", () => { ).execute(k); const all = await q.listAuths(tphDb); expect(all).toHaveLength(1); - // parseAuth read `type` as "Copay" and dispatched to CopayAuthSchema — a raw 2 + // parseAuth read `type` as "Coupon" and dispatched to CouponAuthSchema — a raw 2 // would have thrown on the z.enum head parse. - expect(all[0].type).toBe("Copay"); + expect(all[0].type).toBe("Coupon"); expect(all[0].amount).toBe(42); }, 120_000); @@ -607,9 +607,9 @@ describe("int-backed field.enum under TPH — real Postgres", () => { `INSERT INTO "auths" ("type", "title", "status") VALUES (2, 'c', 7);`, ).execute(k); const [{ id }] = (await sql<{ id: string }>`SELECT "id" FROM "auths"`.execute(k)).rows as any; - // The row IS a Copay, so asking for it as a Bridge must miss — proving the AND'd + // The row IS a Coupon, so asking for it as a Bridge must miss — proving the AND'd // discriminator predicate encoded to 1 rather than binding 'Bridge'. expect(await q.findBridgeAuthById(tphDb, Number(id))).toBeNull(); - expect((await q.findCopayAuthById(tphDb, Number(id)))?.title).toBe("c"); + expect((await q.findCouponAuthById(tphDb, Number(id)))?.title).toBe("c"); }, 120_000); }); diff --git a/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts b/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts index 487920436d..e654c86ee4 100644 --- a/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts +++ b/server/typescript/packages/metadata/test/fr014-tph-discriminator.test.ts @@ -54,7 +54,7 @@ describe("FR-014 happy paths", () => { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, @@ -72,10 +72,10 @@ describe("FR-014 happy paths", () => { }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }], + "@discriminatorValue": "Coupon", + children: [{ "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }], }, }, ], @@ -181,7 +181,7 @@ describe("FR-014 ERR_DISCRIMINATOR_VALUE_DUPLICATE", () => { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, @@ -306,7 +306,7 @@ describe("FR-014 ERR_DISCRIMINATOR_VALUE_TYPE_MISMATCH", () => { { "field.enum": { name: "type", - "@values": ["Bridge", "Copay"], + "@values": ["Bridge", "Coupon"], }, }, { "field.long": { name: "id" } }, diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts index 7d30ae8565..27486f3613 100644 --- a/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts +++ b/server/typescript/packages/migrate-ts/test/expected-schema-tph.test.ts @@ -20,17 +20,17 @@ async function loadTph() { { "object.entity": { name: "Auth", "@discriminator": "type", children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay", "PriorAuth"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon", "Permit"] } }, { "field.string": { name: "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ]}}, { "object.entity": { name: "BridgeAuth", extends: "Auth", "@discriminatorValue": "Bridge", children: [ { "field.int": { name: "quantity", "@required": true } }, ]}}, - { "object.entity": { name: "CopayAuth", extends: "Auth", "@discriminatorValue": "Copay", children: [ - { "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }, + { "object.entity": { name: "CouponAuth", extends: "Auth", "@discriminatorValue": "Coupon", children: [ + { "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }, ]}}, - { "object.entity": { name: "PriorAuthAuth", extends: "Auth", "@discriminatorValue": "PriorAuth", children: [ + { "object.entity": { name: "PermitAuth", extends: "Auth", "@discriminatorValue": "Permit", children: [ { "field.string": { name: "approver", "@maxLength": 80 } }, ]}}, ], @@ -48,8 +48,8 @@ describe("buildExpectedSchema — TPH single table", () => { const names = snap.tables.map((t) => t.name).sort(); expect(names).toContain("auths"); expect(names).not.toContain("bridge_auths"); - expect(names).not.toContain("copay_auths"); - expect(names).not.toContain("prior_auth_auths"); + expect(names).not.toContain("coupon_auths"); + expect(names).not.toContain("permit_auths"); // exactly one table expect(snap.tables.length).toBe(1); }); @@ -58,7 +58,7 @@ describe("buildExpectedSchema — TPH single table", () => { const snap = buildExpectedSchema(await loadTph(), { dialect: "postgres" }); const auths = snap.tables.find((t) => t.name === "auths")!; const cols = auths.columns.map((c) => c.name).sort(); - expect(cols).toEqual(["approver", "copay_amount", "id", "quantity", "reference", "type"]); + expect(cols).toEqual(["approver", "coupon_amount", "id", "quantity", "reference", "type"]); }); test("subtype-only columns are NULLABLE even when the field is @required", async () => { @@ -67,8 +67,8 @@ describe("buildExpectedSchema — TPH single table", () => { const quantity = auths.columns.find((c) => c.name === "quantity")!; // quantity is @required on BridgeAuth, but must be nullable in the single table. expect(quantity.nullable).toBe(true); - const copay = auths.columns.find((c) => c.name === "copay_amount")!; - expect(copay.nullable).toBe(true); + const coupon = auths.columns.find((c) => c.name === "coupon_amount")!; + expect(coupon.nullable).toBe(true); }); // A TPH subtype-only column must carry NO DB default, for the same reason it is diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts index 78baf3f97a..8785538f7e 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/index.ts @@ -328,7 +328,7 @@ export function mountUpdateRoute(opts: VerbOptions): void { } const discCond = discriminatorCond(opts); // FR-017 TPH: a row's subtype is immutable — strip the discriminator from - // the patch so a client can't flip a Bridge into a Copay. + // the patch so a client can't flip a Bridge into a Coupon. let data = parsed.data as Record; if (opts.discriminator) { const { [opts.discriminator.column]: _omit, ...rest } = data; diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts index b975e61b63..ffb804776e 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts @@ -105,7 +105,7 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { } // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Copay's id}/linkedAuths` return that Copay's relations, because + // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because // the junction FK cannot tell the subtypes apart: it points at the shared base table. const srcDisc = opts.sourceDiscriminator; if (srcDisc !== undefined) { diff --git a/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts b/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts index 9fb851f980..96e0441b7b 100644 --- a/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts +++ b/server/typescript/packages/runtime-ts/test/drizzle-fastify/mount-tph-discriminator.test.ts @@ -25,11 +25,11 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, quantity INTEGER, - copay_amount TEXT + coupon_amount TEXT ); `); await client.execute( - `INSERT INTO auths (id, type, quantity, copay_amount) VALUES (1,'Bridge',5,NULL),(2,'Copay',NULL,'10.00');`, + `INSERT INTO auths (id, type, quantity, coupon_amount) VALUES (1,'Bridge',5,NULL),(2,'Coupon',NULL,'10.00');`, ); const db = drizzle(client); @@ -37,7 +37,7 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { id: integer("id").primaryKey({ autoIncrement: true }), type: text("type").notNull(), quantity: integer("quantity"), - copay_amount: text("copay_amount"), + coupon_amount: text("coupon_amount"), }); // Per-subtype schemas omit the discriminator (the route injects it). @@ -96,7 +96,7 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { // Own update, with a sneaky discriminator in the body — must be stripped. const own = await fastify.inject({ - method: "PATCH", url: "/auths/bridge/1", payload: { quantity: 9, type: "Copay" }, + method: "PATCH", url: "/auths/bridge/1", payload: { quantity: 9, type: "Coupon" }, }); expect(own.statusCode).toBe(200); const row = JSON.parse(own.body) as { type: string; quantity: number }; @@ -114,7 +114,7 @@ describe("mountCrudRoutes — TPH discriminator scoping", () => { // patch must never reach the driver. test("PATCH carrying ONLY the discriminator is a no-op 200, not a 500", async () => { const res = await fastify.inject({ - method: "PATCH", url: "/auths/bridge/1", payload: { type: "Copay" }, + method: "PATCH", url: "/auths/bridge/1", payload: { type: "Coupon" }, }); expect(res.statusCode).toBe(200); const row = JSON.parse(res.body) as { type: string; quantity: number }; diff --git a/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts b/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts index 012370aec7..a55ade50ee 100644 --- a/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts +++ b/server/typescript/packages/runtime-ts/test/object-manager-tph.test.ts @@ -30,7 +30,7 @@ const TPH_META = JSON.stringify({ children: [ { "source.rdb": { "@table": "auths" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@values": ["Bridge", "Copay"] } }, + { "field.enum": { name: "type", "@values": ["Bridge", "Coupon"] } }, { "field.string": { name: "reference", "@required": true, "@maxLength": 80 } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, ], @@ -46,10 +46,10 @@ const TPH_META = JSON.stringify({ }, { "object.entity": { - name: "CopayAuth", + name: "CouponAuth", extends: "Auth", - "@discriminatorValue": "Copay", - children: [{ "field.decimal": { name: "copayAmount", "@precision": 10, "@scale": 2 } }], + "@discriminatorValue": "Coupon", + children: [{ "field.decimal": { name: "couponAmount", "@precision": 10, "@scale": 2 } }], }, }, ], @@ -70,8 +70,8 @@ beforeEach(async () => { const driver = inMemoryDriver({ seed: { auths: [ - { id: 1, type: "Bridge", reference: "REF-1", quantity: 5, copay_amount: null }, - { id: 2, type: "Copay", reference: "REF-2", quantity: null, copay_amount: "12.50" }, + { id: 1, type: "Bridge", reference: "REF-1", quantity: 5, coupon_amount: null }, + { id: 2, type: "Coupon", reference: "REF-2", quantity: null, coupon_amount: "12.50" }, ], }, pkFields: { auths: ["id"] }, @@ -91,13 +91,13 @@ describe("ObjectManager TPH — subtype field/identity/source resolution (effect test("base entity reads polymorphically (all rows, tagged by discriminator)", async () => { const rows = await om.findMany("Auth", undefined, { orderBy: [["id", "asc"]] }); - expect(rows.map((r) => r.type)).toEqual(["Bridge", "Copay"]); + expect(rows.map((r) => r.type)).toEqual(["Bridge", "Coupon"]); }); }); describe("ObjectManager TPH — discriminator scoping", () => { test("findById is scoped to the subtype — a different-subtype row is invisible (null)", async () => { - // id 2 is a Copay; addressing it through BridgeAuth must NOT return it. + // id 2 is a Coupon; addressing it through BridgeAuth must NOT return it. expect(await om.findById("BridgeAuth", 2)).toBeNull(); }); @@ -108,7 +108,7 @@ describe("ObjectManager TPH — discriminator scoping", () => { test("count on a subtype counts only that subtype's rows", async () => { expect(await om.count("BridgeAuth")).toBe(1); - expect(await om.count("CopayAuth")).toBe(1); + expect(await om.count("CouponAuth")).toBe(1); }); }); @@ -124,9 +124,9 @@ describe("ObjectManager TPH — create injects the discriminator", () => { test("a cross-subtype-only column is rejected (not a field of this subtype)", async () => { // Identity matters: create() has many other reachable throws (validation, // unsafe-name, identity resolution) — the rejection must be about THIS column. - const attempt = om.create("BridgeAuth", { reference: "X", quantity: 1, copayAmount: "1.00" }); + const attempt = om.create("BridgeAuth", { reference: "X", quantity: 1, couponAmount: "1.00" }); await expect(attempt).rejects.toThrow(MetadataError); - await expect(attempt).rejects.toThrow(/Unknown field 'copayAmount' on entity 'BridgeAuth'/); + await expect(attempt).rejects.toThrow(/Unknown field 'couponAmount' on entity 'BridgeAuth'/); }); }); @@ -139,7 +139,7 @@ describe("ObjectManager TPH — update/delete are subtype-scoped + discriminator }); test("update is scoped — patching a different subtype's row is not found", async () => { - // id 2 is a Copay; through BridgeAuth it's invisible → not found (default + // id 2 is a Coupon; through BridgeAuth it's invisible → not found (default // ifMissing="throw"), exactly like updating a non-existent id. await expect(om.update("BridgeAuth", 2, { quantity: 99 })).rejects.toThrow(NotFoundError); // With ifMissing="ignore" the scoped-out row resolves to null, not the row. @@ -147,18 +147,18 @@ describe("ObjectManager TPH — update/delete are subtype-scoped + discriminator }); test("update cannot change the discriminator (stripped from the patch)", async () => { - const updated = await om.update("BridgeAuth", 1, { type: "Copay", quantity: 7 } as Record); + const updated = await om.update("BridgeAuth", 1, { type: "Coupon", quantity: 7 } as Record); expect(updated).not.toBeNull(); expect(updated!.type).toBe("Bridge"); expect(updated!.quantity).toBe(7); }); test("delete is scoped — deleting a different subtype's row is not found", async () => { - // id 2 is a Copay; through BridgeAuth it's invisible → not found. + // id 2 is a Coupon; through BridgeAuth it's invisible → not found. await expect(om.delete("BridgeAuth", 2)).rejects.toThrow(NotFoundError); expect(await om.delete("BridgeAuth", 2, { ifMissing: "ignore" })).toBe(false); - // the Copay row is still there - expect(await om.findById("CopayAuth", 2)).not.toBeNull(); + // the Coupon row is still there + expect(await om.findById("CouponAuth", 2)).not.toBeNull(); }); test("delete removes the subtype's own row", async () => { diff --git a/server/typescript/packages/test-generators/src/generators/routes.ts b/server/typescript/packages/test-generators/src/generators/routes.ts index a1c2cf0197..2f10b888e2 100644 --- a/server/typescript/packages/test-generators/src/generators/routes.ts +++ b/server/typescript/packages/test-generators/src/generators/routes.ts @@ -659,7 +659,7 @@ function renderTphRoutes( // // The base mounts its own set separately, at its own path. The overlap is deliberate // and not redundant: `/auths/1/tags` accepts any row of the table, while - // `/auths/bridge/1/tags` answers [] for a Copay id — the segment is a type + // `/auths/bridge/1/tags` answers [] for a Coupon id — the segment is a type // assertion, which is exactly what sourceDiscriminator enforces below. const subM2m = renderM2mMounts(m2mEntriesOf(ctx, sub.name), base, ctx, fastifyRef, { pathSuffix: `/${segment}`, From ccc29be0ad94a3c67539215e2d10c64beb0c018e Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 20:56:21 -0500 Subject: [PATCH 217/267] chore(fixtures): neutral domains for every remaining adopter-shaped model The case-history, patient/consent/HIPAA-gate, diagnosis, caregiver, physician, benefit-type and clinic models in tests, conformance fixtures, spec examples, docs and old CHANGELOG lines become consignments, players and contracts with a league gate, analyses, coaches, pilots, service levels and depots, meaning kept. The entity-derived gate fixture and its test are renamed with every reference. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 +-- docs/CONFORMANCE.md | 4 +- docs/features/entities.md | 12 +- docs/features/relationships.md | 22 +-- docs/features/requirements.md | 4 +- .../plans/2026-05-22-field-object-storage.md | 20 +-- .../2026-05-23-csharp-field-object-storage.md | 4 +- ...ross-port-package-binding-config-design.md | 8 +- .../expected.json | 74 ++++----- .../input/meta.contract.json} | 74 ++++----- .../providers.json | 0 .../input/meta.checks.json | 4 +- .../input/meta.views.json | 4 +- .../input/meta.views.json | 30 ++-- .../expected-errors.json | 6 +- .../{meta.care.json => meta.league.json} | 34 ++--- .../input/meta.views.json | 30 ++-- .../expected-errors.json | 2 +- ...meta.diagnosis.json => meta.analysis.json} | 4 +- .../input/meta.plans.json | 4 +- .../expected.json | 4 +- .../input/meta.demo.json | 4 +- .../object-collection-name/expected.json | 40 ++--- ...meta.cases.json => meta.consignments.json} | 40 ++--- .../expected.json | 30 ++-- .../input/meta.analysis.json | 23 +++ .../input/meta.diagnosis.json | 23 --- .../expected.json | 16 +- .../input/meta.views.json | 16 +- .../expected.json | 34 ++--- .../input/meta.views.json | 34 ++--- .../expected.json | 36 ++--- .../input/meta.care.json | 42 ----- .../input/meta.league.json | 42 +++++ .../expected.json | 4 +- .../input/meta.plans.json | 4 +- .../validator-db-check/expected.json | 8 +- .../validator-db-check/input/meta.checks.json | 4 +- .../metamodel-docs/expected/types/object.md | 8 +- .../collection-segments.json | 2 +- .../expected-registry.json | 8 +- .../VerifyAppNamingStrategyTests.cs | 4 +- .../CSharpNamingTests.cs | 58 +++---- .../PackageBindingResolverTests.cs | 38 ++--- .../MetaObjects.Codegen/CSharpNaming.cs | 6 +- .../Generators/EntityGenerator.cs | 2 +- .../DbSetNameVocabularyTests.cs | 6 +- .../EfModelGapsTests.cs | 30 ++-- .../MetaObjects/Loader/ValidationPasses.cs | 2 +- .../Meta/EffectiveProjectionFilter.cs | 2 +- .../MetaObjects/Meta/ReverseReferenceHops.cs | 2 +- .../MetaObjects/SpecMetamodel/object.json | 8 +- .../generator/kotlin/PortScopedAttrKtTest.kt | 10 +- .../loader/PortScopedAttrTest.java | 10 +- .../metaobjects/spec_metamodel/object.json | 8 +- .../codegen/test_cli_import_time_naming.py | 6 +- .../tests/loader/test_port_scoped_attr.py | 10 +- .../cli/test/naming-strategies-config.test.ts | 4 +- .../cli/test/unit/gen-migrate-advice.test.ts | 6 +- .../test/docs-resolved-column.test.ts | 6 +- .../test/drizzle-enum-db-check.test.ts | 2 +- .../test/naming/collection-name.test.ts | 54 +++---- .../test/projection/first-multihop.test.ts | 38 ++--- .../hipaa-gate-entity-derived.test.ts | 143 ------------------ .../league-gate-entity-derived.test.ts | 143 ++++++++++++++++++ ...ection-extends-filtered-projection.test.ts | 20 +-- .../projection/reverse-reference-hop.test.ts | 58 +++---- .../test/projection/tier2-vocabulary.test.ts | 72 ++++----- .../test/projection/tph-scope.test.ts | 22 +-- .../test/projection/view-cast.test.ts | 16 +- .../object/effective-projection-filter.ts | 2 +- .../core/object/object-definition.embedded.ts | 8 +- .../src/core/relationship/filter-path.ts | 2 +- .../src/core/relationship/find-reference.ts | 4 +- .../metadata/src/loader/validation-passes.ts | 4 +- .../metadata/test/port-scoped-attr.test.ts | 10 +- ...pected-schema-field-object-storage.test.ts | 8 +- ...ected-schema-fk-refcolumn-override.test.ts | 12 +- .../sqlite-rebuild-down-reverses.test.ts | 2 +- site-reference/types/object.html | 8 +- spec/metamodel/object.json | 8 +- 81 files changed, 819 insertions(+), 819 deletions(-) rename fixtures/conformance/{entity-derived-hipaa-gate => entity-derived-league-gate}/expected.json (81%) rename fixtures/conformance/{entity-derived-hipaa-gate/input/meta.consent.json => entity-derived-league-gate/input/meta.contract.json} (78%) rename fixtures/conformance/{entity-derived-hipaa-gate => entity-derived-league-gate}/providers.json (100%) rename fixtures/conformance/error-origin-reverse-hop-ambiguous/input/{meta.care.json => meta.league.json} (73%) rename fixtures/conformance/error-port-scoped-attr-wrong-type/input/{meta.diagnosis.json => meta.analysis.json} (58%) rename fixtures/conformance/object-collection-name/input/{meta.cases.json => meta.consignments.json} (71%) create mode 100644 fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.analysis.json delete mode 100644 fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.diagnosis.json delete mode 100644 fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json create mode 100644 fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json delete mode 100644 server/typescript/packages/codegen-ts/test/projection/hipaa-gate-entity-derived.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c5d15e6fd..80afa8716d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -149,7 +149,7 @@ vocabulary; upgrade every port together. string attr, as the other ports did). `meta types` marks such an attr `[csharp-only]` and its JSON carries `ports`. The first one is `@dbSetName`: the EF Core DbSet property name the generated C# context gives an `object.entity`, `object.projection` or `object.report` (`"@dbSetName": - "Diagnosis"`), in place of the derived plural; the routes, the reverse finders and the api + "Analysis"`), in place of the derived plural; the routes, the reverse finders and the api reference read the property name through it. - **C#: `expression-indexes` generator.** The `@expr` indexes EF Core cannot model, written as one SQL file (`CREATE [UNIQUE] INDEX IF NOT EXISTS`, in the source's `@schema`, with `@using` and @@ -857,8 +857,8 @@ vocabulary; upgrade every port together. `skipRedundant`, a string-stored enum with a `validator.length`, and a `@constraintName` validator under `skipRedundant`. - **An extender keeps its base projection's `@filter`** (rc.19 fix round, C1). Codegen read only - the extender's own `@filter`, so a projection extending a gated projection (a consent or HIPAA - gate on an abstract base) emitted an ungated view, with no error. A projection's effective + the extender's own `@filter`, so a projection extending a gated projection (an access or + eligibility gate on an abstract base) emitted an ungated view, with no error. A projection's effective `@filter` is now every level of its `extends` chain, root-most first, ANDed — it composes, it never overrides — and that is what the view's `WHERE` applies and what both loaders check (against the extender's effective fields, so an extender may filter on an inherited @@ -936,7 +936,7 @@ vocabulary; upgrade every port together. SQL that compares with `CURRENT_DATE` or `CURRENT_TIMESTAMP` reads the session zone instead, so near midnight the two disagree by a day: in a session at UTC−5, from 19:00 local time the view's "today" is already tomorrow's date. A hand-written function you replace with a - `now` filter (a consent or eligibility window, say) can include or exclude a row for those + `now` filter (a contract or eligibility window, say) can include or exclude a row for those hours that it did not before. Keep the session zone UTC, or compare a `timestamptz` instant, if the two must agree. - *correlated-filter*: `{ field: "" }` operands in an origin `@filter`, with the @@ -944,7 +944,7 @@ vocabulary; upgrade every port together. - *computed-over-joined*: `origin.computed` refs name the projection's own fields first. - *case*: searched and simple `case` expression nodes. C# entity classes never carry a derived field. Pinned by the fixtures - `entity-derived-hipaa-gate`, `origin-computed-case-over-joined`, + `entity-derived-league-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`. - **`@collectionName`, and a pluggable pluralizer** (rc.19 Phase 6, ruling R57; C# and @@ -974,8 +974,8 @@ vocabulary; upgrade every port together. a value object have no EF mapping; C# warns and configures none. Pinned by `fixtures/conformance/reference-flattened-member`. - **An origin's `@via` walks the reverse of a reference** (rc.19 Phase 5, bug R-walk). A hop - named by the referencing entity's collection name (`Patient.consents` for - `Consent.patient`) walks that identity.reference backwards, to-many, with no relationship + named by the referencing entity's collection name (`Player.contracts` for + `Contract.player`) walks that identity.reference backwards, to-many, with no relationship declared; the loader refused it ("no such relationship or reference") in TypeScript and C#, and TypeScript view codegen silently dropped the join. A declared relationship or reference of the same name wins; two references onto the parent make the hop `ERR_AMBIGUOUS_PATH`. Pinned @@ -1164,11 +1164,11 @@ vocabulary; upgrade every port together. as their first parameter's type, so a project that renamed its context got finders that did not compile. -- **C#: a "-sis" entity name pluralizes to "-ses" in DbSet and finder names.** `Diagnosis` gave - `DbSet Diagnosises` and `FindDiagnosisesByPatient`; it now gives `Diagnoses` and - `FindDiagnosesByPatient` (`Analysis` → `Analyses`, `Basis` → `Bases`). The `-tion`, `-y` and +- **C#: a "-sis" entity name pluralizes to "-ses" in DbSet and finder names.** `Analysis` gave + `DbSet Analysises` and `FindAnalysisesByPlayer`; it now gives `Analyses` and + `FindAnalysesByPlayer` (`Basis` → `Bases`, `Thesis` → `Theses`). The `-tion`, `-y` and `-s` endings were already right and are now pinned by tests. The REST collection segment is a - cross-port wire contract and keeps the shared rule (`/api/diagnosises`) until every port + cross-port wire contract and keeps the shared rule (`/api/analysises`) until every port changes together. An adopter that aliased the old DbSet name can drop the alias. - **Postgres introspection reads a composite foreign key's columns once each, in order.** It joined diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 4bd5a72251..e725f624df 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 463 | ✓ | ✓ but the rc.19 fixtures — the two reverse-hop fixtures (`origin-reverse-reference-hop`, `error-origin-reverse-hop-ambiguous`; bug R-walk), `origin-passthrough-flattened-member` and `reference-flattened-member` (bug G6), `projection-filter-unprojected-base-field`, `projection-filter-joined-path` and `error-projection-filter-path-to-many` (bug G7), `projection-extends-abstract-projection`, `projection-extends-filtered-projection` and `error-projection-extends-filter-sql-body` (bug G13; the last two from the fix round's C1), `object-collection-name` (R57), `report-dimension-required-by-model` (R62; its `expected-report-required.json` holds the model-derived `required` every port's report shape must give — Java, Kotlin and Python still derive it from the INNER-join rule), and the Tier 2 view vocabulary (R58: `entity-derived-hipaa-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `origin-filter-relative-now`, `projection-filter-relative-now`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`) — not run in this port; expected red until [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | inherits via `metadata-ktx` (the same) | ✓ | ✓ but the same, #544–#549 | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 463 | ✓ | ✓ but the rc.19 fixtures — the two reverse-hop fixtures (`origin-reverse-reference-hop`, `error-origin-reverse-hop-ambiguous`; bug R-walk), `origin-passthrough-flattened-member` and `reference-flattened-member` (bug G6), `projection-filter-unprojected-base-field`, `projection-filter-joined-path` and `error-projection-filter-path-to-many` (bug G7), `projection-extends-abstract-projection`, `projection-extends-filtered-projection` and `error-projection-extends-filter-sql-body` (bug G13; the last two from the fix round's C1), `object-collection-name` (R57), `report-dimension-required-by-model` (R62; its `expected-report-required.json` holds the model-derived `required` every port's report shape must give — Java, Kotlin and Python still derive it from the INNER-join rule), and the Tier 2 view vocabulary (R58: `entity-derived-league-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `origin-filter-relative-now`, `projection-filter-relative-now`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`) — not run in this port; expected red until [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | inherits via `metadata-ktx` (the same) | ✓ | ✓ but the same, #544–#549 | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -173,7 +173,7 @@ canonical (`fixtures/registry-conformance/expected-registry.json`). pluralizer (`naming.collections`). *TODO, Java, Kotlin and Python:* register the attr (the manifest is spec-driven; Python's spec copy is synced) and derive their collection names (REST segment, finders) from it; the loader fixture `object-collection-name` names its - reverse hop `Case.caseHistory` by it, so it is red in those ports until they do (#544–#549). + reverse hop `Consignment.consignmentHistory` by it, so it is red in those ports until they do (#544–#549). - *Implemented in Java only* (`implementedIn: ["java"]`): `object.* @object` (ADR-0001), the native class an object binds to. Java's runtime acts on it; Java's own behaviour is unchanged. - *Loads strictly, per port:* diff --git a/docs/features/entities.md b/docs/features/entities.md index c26fb1324d..cdcb25a216 100644 --- a/docs/features/entities.md +++ b/docs/features/entities.md @@ -130,16 +130,16 @@ upstream fails loudly instead of silently becoming a new, disconnected object ## Collection names (`@collectionName`) An object's **collection name** is what a port calls "the set of these": the C# `DbSet` -property, the REST collection segment (snake_cased: `CaseHistory` → `/case_history`), the -TypeScript collection exports (`listCaseHistory`, `findCaseHistoryByCase`, the Drizzle -collection variable `caseHistory`) and the reverse `@via` hop another object walks to reach its -rows (`Case.caseHistory`). Declare it in the object's own casing; it need not be a grammatical +property, the REST collection segment (snake_cased: `ConsignmentHistory` → `/consignment_history`), the +TypeScript collection exports (`listConsignmentHistory`, `findConsignmentHistoryByConsignment`, the Drizzle +collection variable `consignmentHistory`) and the reverse `@via` hop another object walks to reach its +rows (`Consignment.consignmentHistory`). Declare it in the object's own casing; it need not be a grammatical plural: ```yaml - object.entity: - name: CaseHistory - "@collectionName": CaseHistory + name: ConsignmentHistory + "@collectionName": ConsignmentHistory ``` Absent, the project's **pluralizer** derives it from the object's name. One setting, diff --git a/docs/features/relationships.md b/docs/features/relationships.md index d347aeabb5..33bf7e44e6 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -177,17 +177,17 @@ is valid in a `passthrough` and rejected in an `aggregate`. The same reference can be walked **backwards**, parent → many children, with no relationship declared for it: the hop is named by the referencing entity's collection name, lowerFirst -(`consents` for `Consent`; its `@collectionName`, else the project's pluralizer — see +(`contracts` for `Contract`; its `@collectionName`, else the project's pluralizer — see [entities](entities.md#collection-names-collectionname)), and it is to-many, so it is valid in an `aggregate` or `first` and rejected in a `passthrough`: ```yaml -# Consent has `identity.reference: { name: patient, references: Patient }`; Patient declares nothing: -- origin.aggregate: { agg: count, of: "Consent.id", via: "Patient.consents" } +# Contract has `identity.reference: { name: player, references: Player }`; Player declares nothing: +- origin.aggregate: { agg: count, of: "Contract.id", via: "Player.contracts" } ``` -A relationship or reference of that name on the parent wins. Two references from `Consent` -to `Patient` make `Patient.consents` ambiguous, and the loader refuses it naming both +A relationship or reference of that name on the parent wins. Two references from `Contract` +to `Player` make `Player.contracts` ambiguous, and the loader refuses it naming both (`ERR_AMBIGUOUS_PATH`); declare a relationship for the hop instead. Explicit `@via` resolves every kind; single-hop-unique inference stays relationship-only. @@ -204,7 +204,7 @@ walks) and filters on the column. A to-many hop would multiply the base rows and (`ERR_BAD_ATTR_FILTER`). ```yaml -"@filter": { "caseId.status": open } # JOIN cases c … WHERE c.status = 'open' +"@filter": { "orderId.status": open } # JOIN orders o … WHERE o.status = 'open' ``` **A derived field declared once on an entity** (entity-derived). An entity may declare an @@ -238,11 +238,11 @@ field; never an aggregate, and a cycle is refused. A `case` node is searched (`{ case: [ { when: , then: } ], else: }`) or, with `operand`, simple (each `when` a value compared with it); every result has one type. -The HIPAA-gate shape uses all of them at once: a `segment.filter` on `Consent` with `now`, a -boolean on `Patient` declared as `origin.first { @via: Patient.consents, @segment: … }`, and -`@filter: { "caseId.patientId.hasActiveHipaaConsent": true }` on every gated projection. -`fixtures/conformance/entity-derived-hipaa-gate` pins the metadata; -`codegen-ts/test/projection/hipaa-gate-entity-derived.test.ts` pins the view and runs it. +The league-gate shape uses all of them at once: a `segment.filter` on `Contract` with `now`, a +boolean on `Player` declared as `origin.first { @via: Player.contracts, @segment: … }`, and +`@filter: { "campId.playerId.hasActiveLeagueContract": true }` on every gated projection. +`fixtures/conformance/entity-derived-league-gate` pins the metadata; +`codegen-ts/test/projection/league-gate-entity-derived.test.ts` pins the view and runs it. ### rc.21: the rest of what a view needs diff --git a/docs/features/requirements.md b/docs/features/requirements.md index 721c2ed79e..711e62fa9a 100644 --- a/docs/features/requirements.md +++ b/docs/features/requirements.md @@ -186,8 +186,8 @@ inherited rather than re-invented per project: ``` L1 Security (an ISO/IEC 25010 characteristic) └ L2 Confidentiality (its sub-characteristic — or a control - │ catalogue's own category, e.g. a HIPAA - │ safeguard class, when one applies) + │ catalogue's own category, e.g. a SOC 2 + │ trust-services criterion, when one applies) └ L4 invoiceTotalsAreEncryptedAtRest (the claim, bound to the model) ``` diff --git a/docs/superpowers/plans/2026-05-22-field-object-storage.md b/docs/superpowers/plans/2026-05-22-field-object-storage.md index 6f53557716..8384faaaca 100644 --- a/docs/superpowers/plans/2026-05-22-field-object-storage.md +++ b/docs/superpowers/plans/2026-05-22-field-object-storage.md @@ -299,8 +299,8 @@ describe("@storage cross-attribute validation", () => { { "object.value": { name: "ContactInfo", children: [ { "field.string": { name: "email" } }, ]}}, - { "object.entity": { name: "Patient", children: [ - { "source.dbTable": { "@name": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.dbTable": { "@name": "players" } }, { "field.object": { name: "contactInfos", isArray: true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "field.long": { name: "id" } }, { "identity.primary": { "@fields": "id" } }, @@ -439,8 +439,8 @@ describe("buildExpectedSchema — field.object @storage", () => { { "object.value": { name: "ContactInfo", children: [ { "field.string": { name: "email" } }, ]}}, - { "object.entity": { name: "Patient", children: [ - { "source.dbTable": { "@name": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.dbTable": { "@name": "players" } }, { "field.long": { name: "id" } }, { "field.object": { name: "contactInfos", isArray: true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "@fields": "id" } }, @@ -449,8 +449,8 @@ describe("buildExpectedSchema — field.object @storage", () => { }, }); const snap = buildExpectedSchema(root, { dialect: "postgres" }); - const patients = snap.tables.find((t) => t.name === "patients")!; - const contactInfos = patients.columns.find((c) => c.name === "contact_infos"); + const players = snap.tables.find((t) => t.name === "players")!; + const contactInfos = players.columns.find((c) => c.name === "contact_infos"); expect(contactInfos?.sqlType.kind).toBe("json"); }); @@ -883,9 +883,9 @@ Expected: PASS. Adjust expected if needed. }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.dbTable": { "@name": "patients" } }, + { "source.dbTable": { "@name": "players" } }, { "field.long": { "name": "id" } }, { "field.object": { "name": "contactInfos", "isArray": true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "@fields": "id" } } @@ -918,9 +918,9 @@ Expected: PASS. Adjust expected if needed. }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.dbTable": { "@name": "patients" } }, + { "source.dbTable": { "@name": "players" } }, { "field.long": { "name": "id" } }, { "field.object": { "name": "contactInfos", "isArray": true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "@fields": ["id"] } } diff --git a/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md b/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md index 2315caa5ca..4f78d07b4f 100644 --- a/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md +++ b/docs/superpowers/plans/2026-05-23-csharp-field-object-storage.md @@ -306,9 +306,9 @@ public class FieldObjectStorageValidationTests ]}}, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.dbTable": { "@name": "patients" } }, + { "source.dbTable": { "@name": "players" } }, { "field.object": { "name": "contactInfos", "isArray": true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "@fields": "id" } } diff --git a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md index 7f0b3400f7..202d41f579 100644 --- a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md +++ b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md @@ -118,7 +118,7 @@ csharp: # Most acme::lookups types land in .Entities.Lookups via the convention, # but Currency is a top-level concept owned elsewhere in the codebase. "acme::lookups::Currency": "Acme.Domain.Shared" - # Authorization's value-objects live in the Dto namespace by P3 convention, + # Authorization's value-objects live in the Dto namespace by the adopter's convention, # while the entities live in the Entities namespace. "acme::authorizations::InsuranceParameters": "Acme.Domain.Dto" ``` @@ -155,7 +155,7 @@ Resolution order on either path: 4. (port-level legacy fallback, e.g. FR-019's `providedEnumNamespace` single-string) 5. `unmappedStrategy` -Adopters whose `@provided` enums are FLAT in a single namespace (no per-package sub-tree) skip `providedEnumPrepend` entirely and use the FR-019 single-string `providedEnumNamespace` fallback + `typeOverrides` for sub-namespace exceptions. This is exactly what the P3 C# adopter does (see worked example below). +Adopters whose `@provided` enums are FLAT in a single namespace (no per-package sub-tree) skip `providedEnumPrepend` entirely and use the FR-019 single-string `providedEnumNamespace` fallback + `typeOverrides` for sub-namespace exceptions. This is exactly what the the adopter C# adopter does (see worked example below). **Why not a general rule/predicate engine.** We explicitly chose NOT to add `perKindOverrides`, `rules: when {}`, or a `NamedKind` enum. Reasons: - `NamedKind` would be a closed set of values the framework knows about today; metadata kinds grow over time and the enum would need amendments + a new release every time a new kind appears. @@ -177,7 +177,7 @@ Adopters whose `@provided` enums are FLAT in a single namespace (no per-package ### Worked examples -**P3 C# adopter** (the driving case — `@provided` enums live FLAT in `DataEnums`, with 12 sub-namespace exceptions): +**The driving C# adopter** (the driving case — `@provided` enums live FLAT in `DataEnums`, with 12 sub-namespace exceptions): ```yaml csharp: namespace: @@ -210,7 +210,7 @@ Resolves: - `acme::cases` → convention → `Acme.Domain.Entities.Cases` - `acme::users-access` → convention → `Acme.Domain.Entities.UsersAccess` - `acme::reporting` → override → `Acme.Domain.Entities.ReportEntities` -- `acme::patients::Gender` (provided enum) → `providedEnumNamespace` → `Acme.Domain.DataEnums.Gender` +- `acme::players::Gender` (provided enum) → `providedEnumNamespace` → `Acme.Domain.DataEnums.Gender` - `acme::authorizations::AuthorizationType` (provided enum) → `typeOverrides` → `Acme.Domain.DataEnums.Authorizations.AuthorizationType` ~18 entries instead of ~80 — convention covers 13 entity packages, 3 entity overrides, the `providedEnumNamespace` single-string fallback covers ~51 flat enums, and 12 `typeOverrides` pin the sub-namespace exceptions. diff --git a/fixtures/conformance/entity-derived-hipaa-gate/expected.json b/fixtures/conformance/entity-derived-league-gate/expected.json similarity index 81% rename from fixtures/conformance/entity-derived-hipaa-gate/expected.json rename to fixtures/conformance/entity-derived-league-gate/expected.json index c89193a18e..432c8e5c2c 100644 --- a/fixtures/conformance/entity-derived-hipaa-gate/expected.json +++ b/fixtures/conformance/entity-derived-league-gate/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { @@ -18,16 +18,16 @@ }, { "field.boolean": { - "name": "hasActiveHipaaConsent", + "name": "hasActiveLeagueContract", "children": [ { "origin.first": { - "@of": "acme::Consent.consentIsOnFile", + "@of": "acme::Contract.contractIsOnFile", "@orderBy": [ "id:desc" ], - "@segment": "hipaaDecisive", - "@via": "acme::Patient.consents" + "@segment": "leagueDecisive", + "@via": "acme::Player.contracts" } } ] @@ -46,11 +46,11 @@ }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ { "source.rdb": { - "@table": "consents" + "@table": "contracts" } }, { @@ -60,23 +60,23 @@ }, { "field.long": { - "name": "patientId", + "name": "playerId", "@required": true } }, { "field.int": { - "name": "consentTypeId" + "name": "contractTypeId" } }, { "field.boolean": { - "name": "consentIsOnFile" + "name": "contractIsOnFile" } }, { "field.boolean": { - "name": "patientConsent" + "name": "playerContract" } }, { @@ -99,42 +99,42 @@ }, { "identity.reference": { - "name": "patientId", + "name": "playerId", "@fields": [ - "patientId" + "playerId" ], - "@references": "acme::Patient" + "@references": "acme::Player" } }, { "segment.filter": { - "name": "hipaaDecisive", + "name": "leagueDecisive", "@filter": { - "consentTypeId": { + "contractTypeId": { "eq": 1 }, "or": [ { - "consentIsOnFile": { + "contractIsOnFile": { "eq": false } }, { "and": [ { - "consentIsOnFile": { + "contractIsOnFile": { "eq": true } }, { "or": [ { - "patientConsent": { + "playerContract": { "isNull": true } }, { - "patientConsent": { + "playerContract": { "eq": true } } @@ -174,11 +174,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Camp", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "camps" } }, { @@ -188,7 +188,7 @@ }, { "field.long": { - "name": "patientId", + "name": "playerId", "@required": true } }, @@ -202,11 +202,11 @@ }, { "identity.reference": { - "name": "patientId", + "name": "playerId", "@fields": [ - "patientId" + "playerId" ], - "@references": "acme::Patient" + "@references": "acme::Player" } } ] @@ -228,7 +228,7 @@ }, { "field.long": { - "name": "caseId", + "name": "campId", "@required": true } }, @@ -247,11 +247,11 @@ }, { "identity.reference": { - "name": "caseId", + "name": "campId", "@fields": [ - "caseId" + "campId" ], - "@references": "acme::Case" + "@references": "acme::Camp" } } ] @@ -261,7 +261,7 @@ "object.projection": { "name": "AuthorizationExtract", "@filter": { - "caseId.patientId.hasActiveHipaaConsent": { + "campId.playerId.hasActiveLeagueContract": { "eq": true } }, @@ -295,9 +295,9 @@ }, { "object.projection": { - "name": "PatientExtract", + "name": "PlayerExtract", "@filter": { - "hasActiveHipaaConsent": { + "hasActiveLeagueContract": { "eq": true } }, @@ -305,19 +305,19 @@ { "source.rdb": { "@kind": "view", - "@view": "v_patient_extract" + "@view": "v_player_extract" } }, { "field.long": { "name": "id", - "extends": "acme::Patient.id" + "extends": "acme::Player.id" } }, { "identity.primary": { "name": "id", - "extends": "acme::Patient.id" + "extends": "acme::Player.id" } } ] diff --git a/fixtures/conformance/entity-derived-hipaa-gate/input/meta.consent.json b/fixtures/conformance/entity-derived-league-gate/input/meta.contract.json similarity index 78% rename from fixtures/conformance/entity-derived-hipaa-gate/input/meta.consent.json rename to fixtures/conformance/entity-derived-league-gate/input/meta.contract.json index e3463e39a8..daaf8395d5 100644 --- a/fixtures/conformance/entity-derived-hipaa-gate/input/meta.consent.json +++ b/fixtures/conformance/entity-derived-league-gate/input/meta.contract.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { @@ -18,16 +18,16 @@ }, { "field.boolean": { - "name": "hasActiveHipaaConsent", + "name": "hasActiveLeagueContract", "children": [ { "origin.first": { - "@via": "acme::Patient.consents", - "@of": "acme::Consent.consentIsOnFile", + "@via": "acme::Player.contracts", + "@of": "acme::Contract.contractIsOnFile", "@orderBy": [ "id:desc" ], - "@segment": "hipaaDecisive" + "@segment": "leagueDecisive" } } ] @@ -44,11 +44,11 @@ }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ { "source.rdb": { - "@table": "consents" + "@table": "contracts" } }, { @@ -58,23 +58,23 @@ }, { "field.long": { - "name": "patientId", + "name": "playerId", "@required": true } }, { "field.int": { - "name": "consentTypeId" + "name": "contractTypeId" } }, { "field.boolean": { - "name": "consentIsOnFile" + "name": "contractIsOnFile" } }, { "field.boolean": { - "name": "patientConsent" + "name": "playerContract" } }, { @@ -95,32 +95,32 @@ }, { "identity.reference": { - "name": "patientId", - "@fields": "patientId", - "@references": "acme::Patient" + "name": "playerId", + "@fields": "playerId", + "@references": "acme::Player" } }, { "segment.filter": { - "name": "hipaaDecisive", + "name": "leagueDecisive", "@filter": { - "consentTypeId": 1, + "contractTypeId": 1, "or": [ { - "consentIsOnFile": false + "contractIsOnFile": false }, { "and": [ { - "consentIsOnFile": true + "contractIsOnFile": true }, { "or": [ { - "patientConsent": null + "playerContract": null }, { - "patientConsent": true + "playerContract": true } ] }, @@ -156,11 +156,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Camp", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "camps" } }, { @@ -170,7 +170,7 @@ }, { "field.long": { - "name": "patientId", + "name": "playerId", "@required": true } }, @@ -182,9 +182,9 @@ }, { "identity.reference": { - "name": "patientId", - "@fields": "patientId", - "@references": "acme::Patient" + "name": "playerId", + "@fields": "playerId", + "@references": "acme::Player" } } ] @@ -206,7 +206,7 @@ }, { "field.long": { - "name": "caseId", + "name": "campId", "@required": true } }, @@ -223,9 +223,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::Case" + "name": "campId", + "@fields": "campId", + "@references": "acme::Camp" } } ] @@ -235,7 +235,7 @@ "object.projection": { "name": "AuthorizationExtract", "@filter": { - "caseId.patientId.hasActiveHipaaConsent": true + "campId.playerId.hasActiveLeagueContract": true }, "children": [ { @@ -267,27 +267,27 @@ }, { "object.projection": { - "name": "PatientExtract", + "name": "PlayerExtract", "@filter": { - "hasActiveHipaaConsent": true + "hasActiveLeagueContract": true }, "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_patient_extract" + "@view": "v_player_extract" } }, { "field.long": { "name": "id", - "extends": "acme::Patient.id" + "extends": "acme::Player.id" } }, { "identity.primary": { "name": "id", - "extends": "acme::Patient.id" + "extends": "acme::Player.id" } } ] diff --git a/fixtures/conformance/entity-derived-hipaa-gate/providers.json b/fixtures/conformance/entity-derived-league-gate/providers.json similarity index 100% rename from fixtures/conformance/entity-derived-hipaa-gate/providers.json rename to fixtures/conformance/entity-derived-league-gate/providers.json diff --git a/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json b/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json index 1c2125b14a..342bed122e 100644 --- a/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json +++ b/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json @@ -15,8 +15,8 @@ { "field.timestamp": { "name": "endsAt" } }, { "identity.primary": { "name": "pk", "@fields": "id" } }, { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": false } }, - { "validator.requiredWhen": { "name": "clinicEmail", "@field": "email", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, - { "validator.presentIff": { "name": "clinicStart", "@field": "startsAt", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, + { "validator.requiredWhen": { "name": "depotEmail", "@field": "email", "@when": "kind", "@equals": "depot", "@dbCheck": false } }, + { "validator.presentIff": { "name": "depotStart", "@field": "startsAt", "@when": "kind", "@equals": "depot", "@dbCheck": false } }, { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": false, "@constraintName": "visits_contact_ok" } } ] } diff --git a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json index 54d52403ec..48ec4ce7a6 100644 --- a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json +++ b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { diff --git a/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json b/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json index a0b9f911a2..203fc192f9 100644 --- a/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json +++ b/fixtures/conformance/error-origin-correlated-operand-unknown/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,12 +87,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -102,7 +102,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -129,9 +129,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::views::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::views::Consignment" } }, { @@ -158,7 +158,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -168,8 +168,8 @@ { "origin.aggregate": { "@agg": "min", - "@of": "acme::views::CaseHistory.createdDate", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.createdDate", + "@via": "acme::views::Consignment.consignmentHistory", "@filter": { "statusId": { "eq": { @@ -185,7 +185,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json b/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json index 213b9028b8..cb1c2f0ac8 100644 --- a/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json +++ b/fixtures/conformance/error-origin-reverse-hop-ambiguous/expected-errors.json @@ -5,11 +5,11 @@ "source": { "format": "resolved", "files": [ - "meta.care.json" + "meta.league.json" ], "jsonPath": "$['metadata.root'].children[2]['object.projection'].children[2]['field.int'].children[0]['origin.aggregate']", - "referrer": "PatientConsentSummary::consentCount", - "target": "acme::care::Patient.consents" + "referrer": "PlayerContractSummary::contractCount", + "target": "acme::league::Player.contracts" } } ], diff --git a/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.care.json b/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.league.json similarity index 73% rename from fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.care.json rename to fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.league.json index aac28e4a2b..6a9baaf0c7 100644 --- a/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.care.json +++ b/fixtures/conformance/error-origin-reverse-hop-ambiguous/input/meta.league.json @@ -1,14 +1,14 @@ { "metadata.root": { - "package": "acme::care", + "package": "acme::league", "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { @@ -27,11 +27,11 @@ }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ { "source.rdb": { - "@table": "consents" + "@table": "contracts" } }, { @@ -41,7 +41,7 @@ }, { "field.long": { - "name": "patientId" + "name": "playerId" } }, { @@ -62,16 +62,16 @@ }, { "identity.reference": { - "name": "patient", - "@fields": "patientId", - "@references": "acme::care::Patient" + "name": "player", + "@fields": "playerId", + "@references": "acme::league::Player" } }, { "identity.reference": { "name": "witness", "@fields": "witnessId", - "@references": "acme::care::Patient" + "@references": "acme::league::Player" } } ] @@ -79,29 +79,29 @@ }, { "object.projection": { - "name": "PatientConsentSummary", + "name": "PlayerContractSummary", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_patient_consent_summary" + "@view": "v_player_contract_summary" } }, { "field.long": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } }, { "field.int": { - "name": "consentCount", + "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", - "@of": "acme::care::Consent.id", - "@via": "acme::care::Patient.consents" + "@of": "acme::league::Contract.id", + "@via": "acme::league::Player.contracts" } } ] @@ -110,7 +110,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } } ] diff --git a/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json b/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json index dd80eac514..0c3a333306 100644 --- a/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json +++ b/fixtures/conformance/error-origin-segment-unresolved/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,12 +87,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -102,7 +102,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -129,9 +129,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::views::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::views::Consignment" } }, { @@ -158,7 +158,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -168,8 +168,8 @@ { "origin.aggregate": { "@agg": "count", - "@of": "acme::views::CaseHistory.id", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.id", + "@via": "acme::views::Consignment.consignmentHistory", "@segment": "dead" } } @@ -179,7 +179,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json b/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json index 51720f937f..61655bf31b 100644 --- a/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json +++ b/fixtures/conformance/error-port-scoped-attr-wrong-type/expected-errors.json @@ -2,7 +2,7 @@ "errors": [ { "code": "ERR_BAD_ATTR_VALUE", - "source": { "format": "json", "files": [ "meta.diagnosis.json" ], "jsonPath": "$['metadata.root'].children[0]['object.entity']" } + "source": { "format": "json", "files": [ "meta.analysis.json" ], "jsonPath": "$['metadata.root'].children[0]['object.entity']" } } ], "warnings": [] diff --git a/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.diagnosis.json b/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.analysis.json similarity index 58% rename from fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.diagnosis.json rename to fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.analysis.json index 5a7b506c8a..e7f44e881e 100644 --- a/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.diagnosis.json +++ b/fixtures/conformance/error-port-scoped-attr-wrong-type/input/meta.analysis.json @@ -1,8 +1,8 @@ { "metadata.root": { - "package": "acme::clinical", + "package": "acme::lab", "children": [ - { "object.entity": { "name": "Diagnosis", "@dbSetName": ["Diagnosis"], "children": [ + { "object.entity": { "name": "Analysis", "@dbSetName": ["Analysis"], "children": [ { "field.long": { "name": "id" } }, { "identity.primary": { "name": "pk", "@fields": ["id"] } } ] } } diff --git a/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json b/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json index 673b59dbf9..f607bf0fec 100644 --- a/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json +++ b/fixtures/conformance/error-projection-extends-filter-sql-body/input/meta.plans.json @@ -8,7 +8,7 @@ "children": [ { "source.rdb": { "@table": "plans" } }, { "field.long": { "name": "id" } }, - { "field.boolean": { "name": "consented" } }, + { "field.boolean": { "name": "contracted" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } @@ -17,7 +17,7 @@ "object.projection": { "name": "GatedPlans", "abstract": true, - "@filter": { "consented": true }, + "@filter": { "contracted": true }, "children": [ { "field.long": { "name": "planId", "extends": "Plan.id" } }, { "identity.primary": { "name": "id", "extends": "Plan.id" } } diff --git a/fixtures/conformance/field-object-storage-jsonb-array/expected.json b/fixtures/conformance/field-object-storage-jsonb-array/expected.json index 3b4489673e..e5d94bf969 100644 --- a/fixtures/conformance/field-object-storage-jsonb-array/expected.json +++ b/fixtures/conformance/field-object-storage-jsonb-array/expected.json @@ -26,11 +26,11 @@ }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { diff --git a/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json b/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json index d9c44f43e7..fcd8174c5d 100644 --- a/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json +++ b/fixtures/conformance/field-object-storage-jsonb-array/input/meta.demo.json @@ -26,11 +26,11 @@ }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { diff --git a/fixtures/conformance/object-collection-name/expected.json b/fixtures/conformance/object-collection-name/expected.json index c9946a7d44..1474a24dc3 100644 --- a/fixtures/conformance/object-collection-name/expected.json +++ b/fixtures/conformance/object-collection-name/expected.json @@ -1,14 +1,14 @@ { "metadata.root": { - "package": "acme::cases", + "package": "acme::consignments", "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -29,12 +29,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -44,7 +44,7 @@ }, { "field.long": { - "name": "caseId" + "name": "consignmentId" } }, { @@ -67,17 +67,17 @@ }, { "identity.reference": { - "name": "caseId", + "name": "consignmentId", "@fields": [ - "caseId" + "consignmentId" ], - "@references": "acme::cases::Case" + "@references": "acme::consignments::Consignment" } }, { "dimension.attribute": { "name": "status", - "@of": "acme::cases::CaseHistory.status" + "@of": "acme::consignments::ConsignmentHistory.status" } }, { @@ -85,7 +85,7 @@ "name": "entries", "@agg": "count", "@of": [ - "acme::cases::CaseHistory.id" + "acme::consignments::ConsignmentHistory.id" ] } } @@ -94,19 +94,19 @@ }, { "object.projection": { - "name": "CaseActivity", - "@collectionName": "CaseActivity", + "name": "ConsignmentActivity", + "@collectionName": "ConsignmentActivity", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_case_activity" + "@view": "v_consignment_activity" } }, { "field.long": { "name": "id", - "extends": "acme::cases::Case.id" + "extends": "acme::consignments::Consignment.id" } }, { @@ -116,8 +116,8 @@ { "origin.aggregate": { "@agg": "count", - "@of": "acme::cases::CaseHistory.id", - "@via": "acme::cases::Case.caseHistory" + "@of": "acme::consignments::ConsignmentHistory.id", + "@via": "acme::consignments::Consignment.consignmentHistory" } } ] @@ -126,7 +126,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::cases::Case.id" + "extends": "acme::consignments::Consignment.id" } } ] @@ -139,7 +139,7 @@ "@dimensions": [ "status" ], - "@from": "acme::cases::CaseHistory", + "@from": "acme::consignments::ConsignmentHistory", "@measures": [ "entries" ], diff --git a/fixtures/conformance/object-collection-name/input/meta.cases.json b/fixtures/conformance/object-collection-name/input/meta.consignments.json similarity index 71% rename from fixtures/conformance/object-collection-name/input/meta.cases.json rename to fixtures/conformance/object-collection-name/input/meta.consignments.json index dd54b0f2ec..d1063f5c8b 100644 --- a/fixtures/conformance/object-collection-name/input/meta.cases.json +++ b/fixtures/conformance/object-collection-name/input/meta.consignments.json @@ -1,14 +1,14 @@ { "metadata.root": { - "package": "acme::cases", + "package": "acme::consignments", "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -27,12 +27,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -42,7 +42,7 @@ }, { "field.long": { - "name": "caseId" + "name": "consignmentId" } }, { @@ -63,22 +63,22 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::cases::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::consignments::Consignment" } }, { "dimension.attribute": { "name": "status", - "@of": "acme::cases::CaseHistory.status" + "@of": "acme::consignments::ConsignmentHistory.status" } }, { "measure.aggregate": { "name": "entries", "@agg": "count", - "@of": "acme::cases::CaseHistory.id" + "@of": "acme::consignments::ConsignmentHistory.id" } } ] @@ -86,19 +86,19 @@ }, { "object.projection": { - "name": "CaseActivity", - "@collectionName": "CaseActivity", + "name": "ConsignmentActivity", + "@collectionName": "ConsignmentActivity", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_case_activity" + "@view": "v_consignment_activity" } }, { "field.long": { "name": "id", - "extends": "acme::cases::Case.id" + "extends": "acme::consignments::Consignment.id" } }, { @@ -108,8 +108,8 @@ { "origin.aggregate": { "@agg": "count", - "@of": "acme::cases::CaseHistory.id", - "@via": "acme::cases::Case.caseHistory" + "@of": "acme::consignments::ConsignmentHistory.id", + "@via": "acme::consignments::Consignment.consignmentHistory" } } ] @@ -118,7 +118,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::cases::Case.id" + "extends": "acme::consignments::Consignment.id" } } ] @@ -128,7 +128,7 @@ "object.report": { "name": "HistoryCounts", "@collectionName": "HistoryCounts", - "@from": "acme::cases::CaseHistory", + "@from": "acme::consignments::ConsignmentHistory", "@dimensions": [ "status" ], diff --git a/fixtures/conformance/object-port-scoped-attr-dbsetname/expected.json b/fixtures/conformance/object-port-scoped-attr-dbsetname/expected.json index 0454a28d5e..9e903eed89 100644 --- a/fixtures/conformance/object-port-scoped-attr-dbsetname/expected.json +++ b/fixtures/conformance/object-port-scoped-attr-dbsetname/expected.json @@ -1,15 +1,15 @@ { "metadata.root": { - "package": "acme::clinical", + "package": "acme::lab", "children": [ { "object.entity": { - "name": "Diagnosis", - "@dbSetName": "Diagnosis", + "name": "Analysis", + "@dbSetName": "Analysis", "children": [ { "source.rdb": { - "@table": "diagnoses" + "@table": "analyses" } }, { @@ -33,15 +33,15 @@ { "dimension.attribute": { "name": "code", - "@of": "acme::clinical::Diagnosis.code" + "@of": "acme::lab::Analysis.code" } }, { "measure.aggregate": { - "name": "diagnoses", + "name": "analyses", "@agg": "count", "@of": [ - "acme::clinical::Diagnosis.id" + "acme::lab::Analysis.id" ] } } @@ -50,13 +50,13 @@ }, { "object.projection": { - "name": "DiagnosisSummary", - "@dbSetName": "DiagnosisSummary", + "name": "AnalysisSummary", + "@dbSetName": "AnalysisSummary", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_diagnosis_summary" + "@view": "v_analysis_summary" } }, { @@ -69,20 +69,20 @@ }, { "object.report": { - "name": "DiagnosisCounts", - "@dbSetName": "DiagnosisCounts", + "name": "AnalysisCounts", + "@dbSetName": "AnalysisCounts", "@dimensions": [ "code" ], - "@from": "acme::clinical::Diagnosis", + "@from": "acme::lab::Analysis", "@measures": [ - "diagnoses" + "analyses" ], "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_diagnosis_counts" + "@view": "v_analysis_counts" } } ] diff --git a/fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.analysis.json b/fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.analysis.json new file mode 100644 index 0000000000..acb3f011d1 --- /dev/null +++ b/fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.analysis.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme::lab", + "children": [ + { "object.entity": { "name": "Analysis", "@dbSetName": "Analysis", "children": [ + { "source.rdb": { "@table": "analyses" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "code" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "code", "@of": "Analysis.code" } }, + { "measure.aggregate": { "name": "analyses", "@agg": "count", "@of": "Analysis.id" } } + ] } }, + { "object.projection": { "name": "AnalysisSummary", "@dbSetName": "AnalysisSummary", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_analysis_summary" } }, + { "field.string": { "name": "code" } } + ] } }, + { "object.report": { "name": "AnalysisCounts", "@dbSetName": "AnalysisCounts", "@from": "Analysis", + "@dimensions": ["code"], "@measures": ["analyses"], "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_analysis_counts" } } + ] } } + ] + } +} diff --git a/fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.diagnosis.json b/fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.diagnosis.json deleted file mode 100644 index f0e736fca8..0000000000 --- a/fixtures/conformance/object-port-scoped-attr-dbsetname/input/meta.diagnosis.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "metadata.root": { - "package": "acme::clinical", - "children": [ - { "object.entity": { "name": "Diagnosis", "@dbSetName": "Diagnosis", "children": [ - { "source.rdb": { "@table": "diagnoses" } }, - { "field.long": { "name": "id" } }, - { "field.string": { "name": "code" } }, - { "identity.primary": { "name": "pk", "@fields": ["id"] } }, - { "dimension.attribute": { "name": "code", "@of": "Diagnosis.code" } }, - { "measure.aggregate": { "name": "diagnoses", "@agg": "count", "@of": "Diagnosis.id" } } - ] } }, - { "object.projection": { "name": "DiagnosisSummary", "@dbSetName": "DiagnosisSummary", "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_diagnosis_summary" } }, - { "field.string": { "name": "code" } } - ] } }, - { "object.report": { "name": "DiagnosisCounts", "@dbSetName": "DiagnosisCounts", "@from": "Diagnosis", - "@dimensions": ["code"], "@measures": ["diagnoses"], "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_diagnosis_counts" } } - ] } } - ] - } -} diff --git a/fixtures/conformance/origin-computed-case-over-joined/expected.json b/fixtures/conformance/origin-computed-case-over-joined/expected.json index 5758a08ac8..d411f39af1 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/expected.json +++ b/fixtures/conformance/origin-computed-case-over-joined/expected.json @@ -58,12 +58,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -172,7 +172,7 @@ "when": { "op": "eq", "left": { - "field": "cumulativeStatus" + "field": "rollupStatus" }, "right": { "value": 0 @@ -184,7 +184,7 @@ } ], "else": { - "field": "cumulativeStatus" + "field": "rollupStatus" } } } @@ -194,13 +194,13 @@ }, { "field.string": { - "name": "benefitTypeName", + "name": "serviceLevelName", "children": [ { "origin.computed": { "@expr": { "operand": { - "field": "priorType" + "field": "serviceLevel" }, "case": [ { @@ -208,7 +208,7 @@ "value": 1 }, "then": { - "value": "Medical" + "value": "Standard" } }, { @@ -216,7 +216,7 @@ "value": 2 }, "then": { - "value": "Pharmacy" + "value": "Express" } } ] diff --git a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json index bf214bb6c9..a4ff072c5b 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json +++ b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json @@ -56,12 +56,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -166,7 +166,7 @@ "when": { "op": "eq", "left": { - "field": "cumulativeStatus" + "field": "rollupStatus" }, "right": { "value": 0 @@ -178,7 +178,7 @@ } ], "else": { - "field": "cumulativeStatus" + "field": "rollupStatus" } } } @@ -188,13 +188,13 @@ }, { "field.string": { - "name": "benefitTypeName", + "name": "serviceLevelName", "children": [ { "origin.computed": { "@expr": { "operand": { - "field": "priorType" + "field": "serviceLevel" }, "case": [ { @@ -202,7 +202,7 @@ "value": 1 }, "then": { - "value": "Medical" + "value": "Standard" } }, { @@ -210,7 +210,7 @@ "value": 2 }, "then": { - "value": "Pharmacy" + "value": "Express" } } ] diff --git a/fixtures/conformance/origin-correlated-filter-and-segment/expected.json b/fixtures/conformance/origin-correlated-filter-and-segment/expected.json index cb50ec0209..76e546a3c6 100644 --- a/fixtures/conformance/origin-correlated-filter-and-segment/expected.json +++ b/fixtures/conformance/origin-correlated-filter-and-segment/expected.json @@ -34,11 +34,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -53,12 +53,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -93,12 +93,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -108,7 +108,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -137,11 +137,11 @@ }, { "identity.reference": { - "name": "caseId", + "name": "consignmentId", "@fields": [ - "caseId" + "consignmentId" ], - "@references": "acme::views::Case" + "@references": "acme::views::Consignment" } }, { @@ -170,7 +170,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -187,9 +187,9 @@ } } }, - "@of": "acme::views::CaseHistory.createdDate", + "@of": "acme::views::ConsignmentHistory.createdDate", "@segment": "live", - "@via": "acme::views::Case.caseHistory" + "@via": "acme::views::Consignment.consignmentHistory" } } ] @@ -208,12 +208,12 @@ } } }, - "@of": "acme::views::CaseHistory.statusId", + "@of": "acme::views::ConsignmentHistory.statusId", "@orderBy": [ "statusId" ], "@segment": "live", - "@via": "acme::views::Case.caseHistory" + "@via": "acme::views::Consignment.consignmentHistory" } } ] @@ -222,7 +222,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json b/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json index dfbf1198a4..1dc70e4857 100644 --- a/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json +++ b/fixtures/conformance/origin-correlated-filter-and-segment/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -51,12 +51,12 @@ }, { "field.int": { - "name": "priorType" + "name": "serviceLevel" } }, { "field.int": { - "name": "cumulativeStatus" + "name": "rollupStatus" } }, { @@ -87,12 +87,12 @@ }, { "object.entity": { - "name": "CaseHistory", - "@collectionName": "CaseHistory", + "name": "ConsignmentHistory", + "@collectionName": "ConsignmentHistory", "children": [ { "source.rdb": { - "@table": "case_history" + "@table": "consignment_history" } }, { @@ -102,7 +102,7 @@ }, { "field.long": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, @@ -129,9 +129,9 @@ }, { "identity.reference": { - "name": "caseId", - "@fields": "caseId", - "@references": "acme::views::Case" + "name": "consignmentId", + "@fields": "consignmentId", + "@references": "acme::views::Consignment" } }, { @@ -158,7 +158,7 @@ { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -168,8 +168,8 @@ { "origin.aggregate": { "@agg": "min", - "@of": "acme::views::CaseHistory.createdDate", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.createdDate", + "@via": "acme::views::Consignment.consignmentHistory", "@segment": "live", "@filter": { "statusId": { @@ -189,8 +189,8 @@ "children": [ { "origin.first": { - "@of": "acme::views::CaseHistory.statusId", - "@via": "acme::views::Case.caseHistory", + "@of": "acme::views::ConsignmentHistory.statusId", + "@via": "acme::views::Consignment.consignmentHistory", "@orderBy": [ "statusId" ], @@ -210,7 +210,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-reverse-reference-hop/expected.json b/fixtures/conformance/origin-reverse-reference-hop/expected.json index 41988191ee..48f18e3da0 100644 --- a/fixtures/conformance/origin-reverse-reference-hop/expected.json +++ b/fixtures/conformance/origin-reverse-reference-hop/expected.json @@ -1,14 +1,14 @@ { "metadata.root": { - "package": "acme::care", + "package": "acme::league", "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "source.rdb": { - "@table": "patients" + "@table": "players" } }, { @@ -29,11 +29,11 @@ }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ { "source.rdb": { - "@table": "consents" + "@table": "contracts" } }, { @@ -43,7 +43,7 @@ }, { "field.long": { - "name": "patientId" + "name": "playerId" } }, { @@ -61,11 +61,11 @@ }, { "identity.reference": { - "name": "patient", + "name": "player", "@fields": [ - "patientId" + "playerId" ], - "@references": "acme::care::Patient" + "@references": "acme::league::Player" } } ] @@ -73,29 +73,29 @@ }, { "object.projection": { - "name": "PatientConsentSummary", + "name": "PlayerContractSummary", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_patient_consent_summary" + "@view": "v_player_contract_summary" } }, { "field.long": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } }, { "field.int": { - "name": "consentCount", + "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", - "@of": "acme::care::Consent.id", - "@via": "acme::care::Patient.consents" + "@of": "acme::league::Contract.id", + "@via": "acme::league::Player.contracts" } } ] @@ -107,11 +107,11 @@ "children": [ { "origin.first": { - "@of": "acme::care::Consent.onFile", + "@of": "acme::league::Contract.onFile", "@orderBy": [ "id:desc" ], - "@via": "acme::care::Patient.consents" + "@via": "acme::league::Player.contracts" } } ] @@ -120,7 +120,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::care::Patient.id" + "extends": "acme::league::Player.id" } } ] diff --git a/fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json b/fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json deleted file mode 100644 index a14ed58011..0000000000 --- a/fixtures/conformance/origin-reverse-reference-hop/input/meta.care.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "metadata.root": { - "package": "acme::care", - "children": [ - { - "object.entity": { - "name": "Patient", - "children": [ - { "source.rdb": { "@table": "patients" } }, - { "field.long": { "name": "id" } }, - { "identity.primary": { "name": "id", "@fields": "id" } } - ] - } - }, - { - "object.entity": { - "name": "Consent", - "children": [ - { "source.rdb": { "@table": "consents" } }, - { "field.long": { "name": "id" } }, - { "field.long": { "name": "patientId" } }, - { "field.boolean": { "name": "onFile" } }, - { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "patient", "@fields": "patientId", "@references": "acme::care::Patient" } } - ] - } - }, - { - "object.projection": { - "name": "PatientConsentSummary", - "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_patient_consent_summary" } }, - { "field.long": { "name": "id", "extends": "acme::care::Patient.id" } }, - { "field.int": { "name": "consentCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::care::Consent.id", "@via": "acme::care::Patient.consents" } } ] } }, - { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::care::Consent.onFile", "@via": "acme::care::Patient.consents", "@orderBy": ["id:desc"] } } ] } }, - { "identity.primary": { "name": "id", "extends": "acme::care::Patient.id" } } - ] - } - } - ] - } -} diff --git a/fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json b/fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json new file mode 100644 index 0000000000..f3cb1f7b1f --- /dev/null +++ b/fixtures/conformance/origin-reverse-reference-hop/input/meta.league.json @@ -0,0 +1,42 @@ +{ + "metadata.root": { + "package": "acme::league", + "children": [ + { + "object.entity": { + "name": "Player", + "children": [ + { "source.rdb": { "@table": "players" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + }, + { + "object.entity": { + "name": "Contract", + "children": [ + { "source.rdb": { "@table": "contracts" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "playerId" } }, + { "field.boolean": { "name": "onFile" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "player", "@fields": "playerId", "@references": "acme::league::Player" } } + ] + } + }, + { + "object.projection": { + "name": "PlayerContractSummary", + "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_player_contract_summary" } }, + { "field.long": { "name": "id", "extends": "acme::league::Player.id" } }, + { "field.int": { "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::league::Contract.id", "@via": "acme::league::Player.contracts" } } ] } }, + { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::league::Contract.onFile", "@via": "acme::league::Player.contracts", "@orderBy": ["id:desc"] } } ] } }, + { "identity.primary": { "name": "id", "extends": "acme::league::Player.id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/projection-extends-filtered-projection/expected.json b/fixtures/conformance/projection-extends-filtered-projection/expected.json index 340e890c8f..dddb9c62ee 100644 --- a/fixtures/conformance/projection-extends-filtered-projection/expected.json +++ b/fixtures/conformance/projection-extends-filtered-projection/expected.json @@ -28,7 +28,7 @@ }, { "field.boolean": { - "name": "consented" + "name": "contracted" } }, { @@ -52,7 +52,7 @@ "name": "GatedPlans", "abstract": true, "@filter": { - "consented": { + "contracted": { "eq": true } }, diff --git a/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json b/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json index 3e2b1d8326..96652606f9 100644 --- a/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json +++ b/fixtures/conformance/projection-extends-filtered-projection/input/meta.plans.json @@ -10,7 +10,7 @@ { "field.long": { "name": "id" } }, { "field.string": { "name": "name" } }, { "field.string": { "name": "code" } }, - { "field.boolean": { "name": "consented" } }, + { "field.boolean": { "name": "contracted" } }, { "field.boolean": { "name": "deleted" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] @@ -20,7 +20,7 @@ "object.projection": { "name": "GatedPlans", "abstract": true, - "@filter": { "consented": true }, + "@filter": { "contracted": true }, "children": [ { "field.long": { "name": "planId", "extends": "Plan.id" } }, { "field.string": { "name": "label", "children": [ { "origin.passthrough": { "@from": "Plan.name" } } ] } }, diff --git a/fixtures/conformance/validator-db-check/expected.json b/fixtures/conformance/validator-db-check/expected.json index c7dcd836f2..9508ab239c 100644 --- a/fixtures/conformance/validator-db-check/expected.json +++ b/fixtures/conformance/validator-db-check/expected.json @@ -107,18 +107,18 @@ }, { "validator.requiredWhen": { - "name": "clinicEmail", + "name": "depotEmail", "@dbCheck": true, - "@equals": "clinic", + "@equals": "depot", "@field": "email", "@when": "kind" } }, { "validator.presentIff": { - "name": "clinicStart", + "name": "depotStart", "@dbCheck": true, - "@equals": "clinic", + "@equals": "depot", "@field": "startsAt", "@when": "kind" } diff --git a/fixtures/conformance/validator-db-check/input/meta.checks.json b/fixtures/conformance/validator-db-check/input/meta.checks.json index 87707ea740..3f514d35e4 100644 --- a/fixtures/conformance/validator-db-check/input/meta.checks.json +++ b/fixtures/conformance/validator-db-check/input/meta.checks.json @@ -21,8 +21,8 @@ { "field.timestamp": { "name": "endsAt" } }, { "identity.primary": { "name": "pk", "@fields": "id" } }, { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": true } }, - { "validator.requiredWhen": { "name": "clinicEmail", "@field": "email", "@when": "kind", "@equals": "clinic", "@dbCheck": true } }, - { "validator.presentIff": { "name": "clinicStart", "@field": "startsAt", "@when": "kind", "@equals": "clinic", "@dbCheck": true } }, + { "validator.requiredWhen": { "name": "depotEmail", "@field": "email", "@when": "kind", "@equals": "depot", "@dbCheck": true } }, + { "validator.presentIff": { "name": "depotStart", "@field": "startsAt", "@when": "kind", "@equals": "depot", "@dbCheck": true } }, { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": true } } ] } diff --git a/fixtures/metamodel-docs/expected/types/object.md b/fixtures/metamodel-docs/expected/types/object.md index 72f141b682..51bc5139f0 100644 --- a/fixtures/metamodel-docs/expected/types/object.md +++ b/fixtures/metamodel-docs/expected/types/object.md @@ -46,7 +46,7 @@ An object that owns its data: own identity, writable sources, and lifecycle. The | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | +| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | | `@dbSetName` | string | no | | | metaobjects-core-types | DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it. | | `@discriminator` | string | no | | | metaobjects-core-types | FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string). | | `@discriminatorValue` | string | no | | | metaobjects-core-types | FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity. | @@ -81,9 +81,9 @@ A derived read-only representation of entities. Its fields are extends-bound / o | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | +| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | | `@dbSetName` | string | no | | | metaobjects-core-types | DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it. | -| `@filter` | filter | no | | | metaobjects-core-types | Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19). | +| `@filter` | filter | no | | | metaobjects-core-types | Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19). | | `@grain` | string | no | | | metaobjects-core-types | rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection. | | `@grainOrdinal` | string | no | | | metaobjects-core-types | rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array. | | `@object` | string | no | | | metaobjects-core-types | The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet. | @@ -112,7 +112,7 @@ A declared report (FR-044): a fixed combination of dimensions and measures of ON | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | -| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | +| `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | | `@dbSetName` | string | no | | | metaobjects-core-types | DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it. | | `@dimensions` | string[] | no | | | metaobjects-core-types | Dimension names of @from; a time dimension is written 'name:grain'. Absent means one global row. | | `@filter` | filter | no | | | metaobjects-core-types | Optional row scope over @from's fields; may use relative-date values. | diff --git a/fixtures/naming-conformance/collection-segments.json b/fixtures/naming-conformance/collection-segments.json index 89307275a5..7c24edf585 100644 --- a/fixtures/naming-conformance/collection-segments.json +++ b/fixtures/naming-conformance/collection-segments.json @@ -12,7 +12,7 @@ { "name": "SSN", "segment": "ssns" }, { "name": "PA", "segment": "pas" }, { "name": "URLHost", "segment": "url_hosts" }, - { "name": "CaseHistory", "collectionName": "CaseHistory", "segment": "case_history" }, + { "name": "ConsignmentHistory", "collectionName": "ConsignmentHistory", "segment": "consignment_history" }, { "name": "Faq", "collectionName": "FAQs", "segment": "faqs" }, { "name": "TaxId", "collectionName": "TaxIDs", "segment": "tax_ids" }, { "name": "Box", "collectionName": "PDFBoxes", "segment": "pdf_boxes" }, diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index df87c06bb5..49199b3db4 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -3451,7 +3451,7 @@ "csharp", "typescript" ], - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "name": "dbSetName", @@ -3595,7 +3595,7 @@ "csharp", "typescript" ], - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "name": "dbSetName", @@ -3612,7 +3612,7 @@ "valueType": "filter", "isArray": false, "required": false, - "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." + "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "name": "grain", @@ -3724,7 +3724,7 @@ "csharp", "typescript" ], - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "name": "dbSetName", diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs index 8e206b7f75..4371a2560c 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs @@ -20,8 +20,8 @@ public sealed class VerifyAppNamingStrategyTests : IDisposable private const string Model = """ { "metadata.root": { "package": "acme", "children": [ - { "object.entity": { "name": "Patient", "children": [ - { "source.rdb": { "@table": "patients" } }, + { "object.entity": { "name": "Player", "children": [ + { "source.rdb": { "@table": "players" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "firstName" } }, { "identity.primary": { "@fields": "id" } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs index d1b56cf2b5..ba661f87c1 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CSharpNamingTests.cs @@ -114,12 +114,12 @@ public void Pluralize_keeps_existing_behavior_for_s_u_i_a_plus_s_endings(string Assert.Equal(expected, CSharpNaming.Pluralize(input)); } - // A Greek "-sis" noun takes "-ses" (Diagnosis -> Diagnoses), not the sibilant "+es" that - // produced "Diagnosises" in every DbSet and finder name. The other common endings are pinned + // A Greek "-sis" noun takes "-ses" (Analysis -> Analyses), not the sibilant "+es" that + // produced "Analysises" in every DbSet and finder name. The other common endings are pinned // beside it so the new rule cannot widen past "-sis". [Theory] - [InlineData("Diagnosis", "Diagnoses")] [InlineData("Analysis", "Analyses")] + [InlineData("Thesis", "Theses")] [InlineData("Basis", "Bases")] [InlineData("OrderAnalysis", "OrderAnalyses")] [InlineData("Notification", "Notifications")] @@ -137,8 +137,8 @@ public void Pluralize_handles_sis_tion_y_and_s_endings(string input, string expe [Fact] public void DbSetName_and_reverse_finder_name_use_the_sis_plural() { - Assert.Equal("Diagnoses", CSharpNaming.DbSetName(Entity("Diagnosis"))); - Assert.Equal("FindDiagnosesByPatient", CSharpNaming.ReverseFinderName(Entity("Diagnosis"), "patientId")); + Assert.Equal("Analyses", CSharpNaming.DbSetName(Entity("Analysis"))); + Assert.Equal("FindAnalysesByPlayer", CSharpNaming.ReverseFinderName(Entity("Analysis"), "playerId")); } [Fact] @@ -147,7 +147,7 @@ public void RoutePath_keeps_the_cross_port_rule_for_a_sis_noun() // The REST collection segment is a wire contract every port spells the same way // (fixtures/naming-conformance); the "-sis" rule is a C# identifier fix only, so the // route does not move until every port moves with it. - Assert.Equal("diagnosises", CSharpNaming.RoutePath(Entity("Diagnosis"))); + Assert.Equal("analysises", CSharpNaming.RoutePath(Entity("Analysis"))); } [Fact] @@ -456,17 +456,17 @@ public void The_REST_segment_is_the_cross_port_one(SegmentCase c) private const string HistoryModel = """ { "metadata.root": { "package": "core", "children": [ - { "object.entity": { "name": "Case", "children": [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { "name": "Consignment", "children": [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "@fields": "id" } } ] } }, - { "object.entity": { "name": "CaseHistory", ATTRS "children": [ - { "source.rdb": { "@table": "case_history" } }, + { "object.entity": { "name": "ConsignmentHistory", ATTRS "children": [ + { "source.rdb": { "@table": "consignment_history" } }, { "field.long": { "name": "id" } }, - { "field.long": { "name": "caseId" } }, + { "field.long": { "name": "consignmentId" } }, { "identity.primary": { "@fields": "id" } }, - { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "Case" } } + { "identity.reference": { "name": "consignmentId", "@fields": "consignmentId", "@references": "Consignment" } } ] } } ] } } """; @@ -485,37 +485,37 @@ private static MetaRoot History(string attrs, string? pluralizer = null) Config = new GenConfig { OutDir = "/unused", Namespace = "Acme.Generated" }, }; - private static MetaObject HistoryOf(MetaRoot root) => root.Objects().Single(o => o.Name == "CaseHistory"); + private static MetaObject HistoryOf(MetaRoot root) => root.Objects().Single(o => o.Name == "ConsignmentHistory"); [Fact] public void CollectionName_names_the_DbSet_the_route_the_finder_and_the_reverse_hop() { - var root = History("\"@collectionName\": \"CaseHistory\","); + var root = History("\"@collectionName\": \"ConsignmentHistory\","); var history = HistoryOf(root); - Assert.Equal("CaseHistory", CSharpNaming.DbSetName(history)); - Assert.Equal("case_history", CSharpNaming.RoutePath(history)); - Assert.Equal("FindCaseHistoryByCase", CSharpNaming.ReverseFinderName(history, "caseId")); - Assert.Equal("caseHistory", MetaObjects.Meta.ReverseReferenceHops.HopName(history)); + Assert.Equal("ConsignmentHistory", CSharpNaming.DbSetName(history)); + Assert.Equal("consignment_history", CSharpNaming.RoutePath(history)); + Assert.Equal("FindConsignmentHistoryByConsignment", CSharpNaming.ReverseFinderName(history, "consignmentId")); + Assert.Equal("consignmentHistory", MetaObjects.Meta.ReverseReferenceHops.HopName(history)); var warnings = new List(); var context = Assert.Single(new DbContextGenerator().Generate(CtxWarn(root, warnings))).Content; - Assert.Contains("DbSet CaseHistory { get; set; }", context); + Assert.Contains("DbSet ConsignmentHistory { get; set; }", context); Assert.DoesNotContain(warnings, w => w.Contains("deprecated")); } [Fact] public void DbSetName_is_a_deprecated_alias_that_warns() { - var root = History("\"@dbSetName\": \"CaseHistory\","); - Assert.Equal("case_history", CSharpNaming.RoutePath(HistoryOf(root))); + var root = History("\"@dbSetName\": \"ConsignmentHistory\","); + Assert.Equal("consignment_history", CSharpNaming.RoutePath(HistoryOf(root))); var warnings = new List(); - Assert.Contains("DbSet CaseHistory { get; set; }", Assert.Single(new DbContextGenerator().Generate(CtxWarn(root, warnings))).Content); + Assert.Contains("DbSet ConsignmentHistory { get; set; }", Assert.Single(new DbContextGenerator().Generate(CtxWarn(root, warnings))).Content); Assert.Contains(warnings, w => w.Contains("@dbSetName is deprecated") && w.Contains("@collectionName")); } [Fact] public void Declaring_both_is_refused() { - var root = History("\"@collectionName\": \"CaseHistory\", \"@dbSetName\": \"Histories\","); + var root = History("\"@collectionName\": \"ConsignmentHistory\", \"@dbSetName\": \"Histories\","); var ex = Assert.Throws(() => CSharpNaming.DbSetName(HistoryOf(root))); Assert.Contains("declares both @collectionName and @dbSetName", ex.Message); } @@ -524,13 +524,13 @@ public void Declaring_both_is_refused() public void Absent_the_configured_pluralizer_names_the_collection_and_unconfigured_output_is_unchanged() { var unconfigured = HistoryOf(History("")); - Assert.Equal("CaseHistories", CSharpNaming.DbSetName(unconfigured)); - Assert.Equal("case_histories", CSharpNaming.RoutePath(unconfigured)); + Assert.Equal("ConsignmentHistories", CSharpNaming.DbSetName(unconfigured)); + Assert.Equal("consignment_histories", CSharpNaming.RoutePath(unconfigured)); var none = HistoryOf(History("", pluralizer: "none")); - Assert.Equal("CaseHistory", CSharpNaming.DbSetName(none)); - Assert.Equal("case_history", CSharpNaming.RoutePath(none)); - Assert.Equal("caseHistory", MetaObjects.Meta.ReverseReferenceHops.HopName(none)); + Assert.Equal("ConsignmentHistory", CSharpNaming.DbSetName(none)); + Assert.Equal("consignment_history", CSharpNaming.RoutePath(none)); + Assert.Equal("consignmentHistory", MetaObjects.Meta.ReverseReferenceHops.HopName(none)); } [Fact] @@ -539,7 +539,7 @@ public void An_application_registers_its_own_pluralizer_and_an_unknown_name_fail // The registry is process-wide and other test classes register strategies in it, so this // one is left registered (registering a name again replaces it) rather than reset. MetaObjects.Meta.NamingStrategies.RegisterPluralizer("cs-test-latin", n => n.EndsWith("History") ? n[..^1] + "ies" : n + "s"); - Assert.Equal("CaseHistories", CSharpNaming.DbSetName(HistoryOf(History("", pluralizer: "cs-test-latin")))); + Assert.Equal("ConsignmentHistories", CSharpNaming.DbSetName(HistoryOf(History("", pluralizer: "cs-test-latin")))); Assert.Throws(() => MetaObjects.Meta.NamingStrategies.RegisterPluralizer("standard", n => n)); var ex = Assert.Throws(() => MetaObjects.Meta.NamingStrategies.Pluralizer("klingon")); Assert.Contains("\"naming.collections\" names \"klingon\"", ex.Message); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs index 90d2972544..eeb51a6ea1 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs @@ -25,7 +25,7 @@ public class PackageBindingResolverTests public void Default_config_maps_a_package_to_its_own_namespace_and_no_package_to_Namespace() { var cfg = CfgWithDefaults(); - Assert.Equal("Acme.Cases", PackageBindingResolver.Resolve(cfg, "acme::cases", "Case")); + Assert.Equal("Acme.Orders", PackageBindingResolver.Resolve(cfg, "acme::orders", "Order")); Assert.Equal("Acme.UsersAccess", PackageBindingResolver.Resolve(cfg, "acme::users-access", "User")); Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, null)); Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "")); @@ -44,16 +44,16 @@ public void Type_override_wins_over_package_override_and_convention() }, PackageNamespaces = new Dictionary { - ["acme::cases"] = "Acme.Entities.CaseSpecialOverride", + ["acme::orders"] = "Acme.Entities.OrderSpecialOverride", }, TypeOverrides = new Dictionary { - ["acme::cases::Currency"] = "Acme.Shared.Money", + ["acme::orders::Currency"] = "Acme.Shared.Money", }, }; - Assert.Equal("Acme.Shared.Money", PackageBindingResolver.Resolve(cfg, "acme::cases", "Currency")); - Assert.Equal("Acme.Entities.CaseSpecialOverride", PackageBindingResolver.Resolve(cfg, "acme::cases", "OtherType")); + Assert.Equal("Acme.Shared.Money", PackageBindingResolver.Resolve(cfg, "acme::orders", "Currency")); + Assert.Equal("Acme.Entities.OrderSpecialOverride", PackageBindingResolver.Resolve(cfg, "acme::orders", "OtherType")); } [Fact] @@ -70,12 +70,12 @@ public void Convention_rule_strips_prefix_pascalcases_segments_joins_by_separato }, }; - Assert.Equal("Acme.Domain.Entities.Cases", - PackageBindingResolver.Resolve(cfg, "acme::cases", "Case")); + Assert.Equal("Acme.Domain.Entities.Orders", + PackageBindingResolver.Resolve(cfg, "acme::orders", "Order")); Assert.Equal("Acme.Domain.Entities.UsersAccess", PackageBindingResolver.Resolve(cfg, "acme::users-access", "User")); - Assert.Equal("Acme.Domain.Entities.Cases.CustomProperties", - PackageBindingResolver.Resolve(cfg, "acme::cases::custom-properties", "CustomProperty")); + Assert.Equal("Acme.Domain.Entities.Orders.CustomProperties", + PackageBindingResolver.Resolve(cfg, "acme::orders::custom-properties", "CustomProperty")); } [Fact] @@ -92,7 +92,7 @@ public void Convention_falls_through_when_package_does_not_start_with_strip() }; // Falls back to Flatten (Acme.Generated) since the package doesn't match strip. - Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "other::cases", "Case")); + Assert.Equal("Acme.Generated", PackageBindingResolver.Resolve(cfg, "other::orders", "Order")); } [Fact] @@ -167,19 +167,19 @@ public void An_override_that_is_not_an_identifier_path_stops_generation(string t { var typeOverride = CfgWithDefaults() with { - TypeOverrides = new Dictionary { ["acme::cases::Case"] = target }, + TypeOverrides = new Dictionary { ["acme::orders::Order"] = target }, }; var packageOverride = CfgWithDefaults() with { - PackageNamespaces = new Dictionary { ["acme::cases"] = target }, + PackageNamespaces = new Dictionary { ["acme::orders"] = target }, }; foreach (var cfg in new[] { typeOverride, packageOverride }) { - var ex = Assert.Throws(() => PackageBindingResolver.Resolve(cfg, "acme::cases", "Case")); + var ex = Assert.Throws(() => PackageBindingResolver.Resolve(cfg, "acme::orders", "Order")); Assert.Contains($"\"{badSegment}\" is not an identifier", ex.Message); - Assert.Contains("metadata package \"acme::cases\"", ex.Message); - Assert.Throws(() => PackageBindingResolver.TryResolve(cfg, "acme::cases", "Case")); + Assert.Contains("metadata package \"acme::orders\"", ex.Message); + Assert.Throws(() => PackageBindingResolver.TryResolve(cfg, "acme::orders", "Order")); } } @@ -280,14 +280,14 @@ public void Real_P3_config_resolves_all_18_domains_correctly() }, }; - // Convention rule: 13 of the 19 P3 domains fall through here. - Assert.Equal("Acme.Domain.Entities.Cases", PackageBindingResolver.Resolve(cfg, "acme::cases")); + // Convention rule: most of the domains fall through here. + Assert.Equal("Acme.Domain.Entities.Orders", PackageBindingResolver.Resolve(cfg, "acme::orders")); Assert.Equal("Acme.Domain.Entities.Workflow", PackageBindingResolver.Resolve(cfg, "acme::workflow")); - Assert.Equal("Acme.Domain.Entities.Patients", PackageBindingResolver.Resolve(cfg, "acme::patients")); + Assert.Equal("Acme.Domain.Entities.Players", PackageBindingResolver.Resolve(cfg, "acme::players")); Assert.Equal("Acme.Domain.Entities.UsersAccess", PackageBindingResolver.Resolve(cfg, "acme::users-access")); Assert.Equal("Acme.Domain.Entities.Authorizations", PackageBindingResolver.Resolve(cfg, "acme::authorizations")); - // Overrides win for the 6 P3-specific names. + // Overrides win for the adopter-specific names. Assert.Equal("Acme.Domain.Entities.ReportEntities", PackageBindingResolver.Resolve(cfg, "acme::reporting")); Assert.Equal("Acme.Domain.DataEnums", PackageBindingResolver.Resolve(cfg, "acme::domain::dataEnums")); Assert.Equal("Acme.Domain.DataEnums.Authorizations", PackageBindingResolver.Resolve(cfg, "acme::domain::dataEnums::authorizations")); diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 83219e1b24..9acccf0d29 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -1166,9 +1166,9 @@ private static string PluralizeLegacySuffixOnly(string name) /// detection () on top of the historical suffix rule /// (). /// - /// A Greek -sis noun takes -ses (Diagnosis -> Diagnoses, - /// Analysis -> Analyses) instead of the sibilant +es rule's - /// Diagnosises. Every name this spells is a C# identifier (DbSet properties, reverse + /// A Greek -sis noun takes -ses (Analysis -> Analyses, + /// Basis -> Bases) instead of the sibilant +es rule's + /// Analysises. Every name this spells is a C# identifier (DbSet properties, reverse /// finders); the REST collection segment, which IS a cross-port wire contract, keeps /// until every port adopts the rule together. /// diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index b847ff86d9..5ec33b0c6a 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -825,7 +825,7 @@ private static string AbstractShapeBaseClause(MetaObject entity, GenContext ctx) // The directly-extended entity to emit as a C# base class for a NON-TPH entity (mapped // entity or abstract shape). The metadata `extends` chain becomes the C# inheritance - // chain: `class Physician : BaseAuditableEntity`, `abstract class BaseAuditableEntity : + // chain: `class Pilot : BaseAuditableEntity`, `abstract class BaseAuditableEntity : // BaseEntity`. Returns the immediate `extends` target when it is an emitted entity — an // abstract base (only when EmitAbstractShapes is on, since the base must exist as a type) // or a concrete parent. Null when there is no such parent: the entity then flattens its diff --git a/server/csharp/MetaObjects.Conformance.Tests/DbSetNameVocabularyTests.cs b/server/csharp/MetaObjects.Conformance.Tests/DbSetNameVocabularyTests.cs index 20c081342e..e36eefa56a 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/DbSetNameVocabularyTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/DbSetNameVocabularyTests.cs @@ -13,8 +13,8 @@ public sealed class DbSetNameVocabularyTests { private const string Model = """ { "metadata.root": { "package": "acme", "children": [ - { "object.entity": { "name": "Diagnosis", "@dbSetName": "Diagnosis", "children": [ - { "source.rdb": { "@table": "diagnoses" } }, + { "object.entity": { "name": "Analysis", "@dbSetName": "Analysis", "children": [ + { "source.rdb": { "@table": "analyses" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "@fields": "id" } } ] } } @@ -27,7 +27,7 @@ public void A_strict_load_accepts_dbSetName_on_an_entity() var result = new MetaDataLoader(Provider.ComposeRegistry(CoreTypes.LibraryProviders), strict: true) .Load([new InMemoryStringSource(Model, id: "meta.json")]); Assert.Empty(result.Errors.Select(e => e.Code + ": " + e.Message)); - Assert.Equal("Diagnosis", result.Root.Objects().Single().OwnAttr("dbSetName")); + Assert.Equal("Analysis", result.Root.Objects().Single().OwnAttr("dbSetName")); } [Fact] diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index 2b4d3d9155..e437687a61 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -134,26 +134,26 @@ private static IForeignKey ForeignKey(IEntityType t, params string[] props) => private const string EntityDerivedModel = """ { "metadata.root": { "package": "acme", "children": [ - { "object.entity": { "name": "Patient", "children": [ - { "source.rdb": { "@table": "patients" } }, + { "object.entity": { "name": "Player", "children": [ + { "source.rdb": { "@table": "players" } }, { "field.long": { "name": "id" } }, - { "field.boolean": { "name": "hasConsent", "children": [ - { "origin.first": { "@via": "Patient.consents", "@of": "Consent.onFile", "@orderBy": ["id:desc"] } } + { "field.boolean": { "name": "hasContract", "children": [ + { "origin.first": { "@via": "Player.contracts", "@of": "Contract.onFile", "@orderBy": ["id:desc"] } } ]}}, { "identity.primary": { "name": "id", "@fields": "id" } } ]}}, - { "object.entity": { "name": "Consent", "children": [ - { "source.rdb": { "@table": "consents" } }, + { "object.entity": { "name": "Contract", "children": [ + { "source.rdb": { "@table": "contracts" } }, { "field.long": { "name": "id" } }, - { "field.long": { "name": "patientId", "@required": true } }, + { "field.long": { "name": "playerId", "@required": true } }, { "field.boolean": { "name": "onFile" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "patientId", "@fields": "patientId", "@references": "Patient" } } + { "identity.reference": { "name": "playerId", "@fields": "playerId", "@references": "Player" } } ]}}, - { "object.projection": { "name": "ConsentedPatients", "@filter": { "hasConsent": true }, "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_consented_patients" } }, - { "field.long": { "name": "id", "extends": "acme::Patient.id" } }, - { "identity.primary": { "name": "id", "extends": "acme::Patient.id" } } + { "object.projection": { "name": "ContractedPlayers", "@filter": { "hasContract": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_contracted_players" } }, + { "field.long": { "name": "id", "extends": "acme::Player.id" } }, + { "identity.primary": { "name": "id", "extends": "acme::Player.id" } } ]}} ]}} """; @@ -164,9 +164,9 @@ public void An_entity_derived_field_is_no_column_of_the_entity() // The field has no column: the view a projection reaching it is built from inlines it. var gen = GeneratedEfModel.Compile(EntityDerivedModel, "Acme.EntityDerived"); using var db = gen.ModelOnlyContext(); - var patient = EntityType(db, "Patient"); - Assert.Null(patient.FindProperty("HasConsent")); - Assert.Null(patient.ClrType.GetProperty("HasConsent")); + var player = EntityType(db, "Player"); + Assert.Null(player.FindProperty("HasContract")); + Assert.Null(player.ClrType.GetProperty("HasContract")); } // ── rc.21: @stringValueMap — a member's stored string ──────────────────────────────────── diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 33a7c8cdae..cd32d4ffb0 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1198,7 +1198,7 @@ private static bool IsReferenceHop(MetaData hop) { // R-walk: a hop may walk an identity.reference BACKWARDS, from the entity it targets // to the entity that declares it, named by that entity's collection name - // (`Patient.consents` for Consent.patient). A declared relationship or reference wins. + // (`Player.contracts` for Contract.player). A declared relationship or reference wins. var reversed = currentObj is MetaObject walkedFrom && root is MetaRoot metaRoot ? ReverseReferenceHops.Find(walkedFrom, relName, metaRoot.Objects()) : []; diff --git a/server/csharp/MetaObjects/Meta/EffectiveProjectionFilter.cs b/server/csharp/MetaObjects/Meta/EffectiveProjectionFilter.cs index 0db83f69bb..c863f2de58 100644 --- a/server/csharp/MetaObjects/Meta/EffectiveProjectionFilter.cs +++ b/server/csharp/MetaObjects/Meta/EffectiveProjectionFilter.cs @@ -1,6 +1,6 @@ // rc.19 (C1) — a projection's EFFECTIVE row scope. `@filter` composes down an `extends` chain // rather than overriding: a projection that extends a filtered projection keeps the base's row -// scope (a consent gate on an abstract base must survive in every extender). Every level's own +// scope (a contract gate on an abstract base must survive in every extender). Every level's own // `@filter`, root-most first, ANDed. Ported from // typescript/packages/metadata/src/core/object/effective-projection-filter.ts. diff --git a/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs b/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs index 2c5f20875c..d2b884c05e 100644 --- a/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs +++ b/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs @@ -15,7 +15,7 @@ public static class ReverseReferenceHops { ///

    /// The name a reverse hop takes: the holder's collection name (its @collectionName, else the project's pluralizer), lowerFirst — - /// consents for Consent. The pluralization is the one every port shares + /// contracts for Contract. The pluralization is the one every port shares /// (already-plural names stay; else the suffix rule), as fixtures/naming-conformance pins it. /// public static string HopName(MetaObject holder) diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index 7dbadfcd07..fbae6bec09 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -31,7 +31,7 @@ { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] }, @@ -54,12 +54,12 @@ "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] }, @@ -76,7 +76,7 @@ { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] } diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/PortScopedAttrKtTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/PortScopedAttrKtTest.kt index d1e7295cfb..402cca7838 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/PortScopedAttrKtTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/PortScopedAttrKtTest.kt @@ -16,8 +16,8 @@ import kotlin.test.assertTrue class PortScopedAttrKtTest { private fun model(attr: String) = """ { "metadata.root": { "package": "acme", "children": [ - { "object.entity": { "name": "Diagnosis", $attr "children": [ - { "source.rdb": { "@table": "diagnoses" } }, + { "object.entity": { "name": "Analysis", $attr "children": [ + { "source.rdb": { "@table": "analyses" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "@fields": "id" } } ] } } @@ -35,9 +35,9 @@ class PortScopedAttrKtTest { ObjectClassRegistry.resetGlobal() } - @Test fun `a csharp-only attribute loads`() = assertEquals(emptyList(), errors("\"@dbSetName\": \"Diagnosis\",")) + @Test fun `a csharp-only attribute loads`() = assertEquals(emptyList(), errors("\"@dbSetName\": \"Analysis\",")) - @Test fun `it is type-checked`() = assertTrue(errors("\"@dbSetName\": [\"Diagnosis\"],").isNotEmpty()) + @Test fun `it is type-checked`() = assertTrue(errors("\"@dbSetName\": [\"Analysis\"],").isNotEmpty()) - @Test fun `an unregistered attribute still fails`() = assertTrue(errors("\"@dbSetNameX\": \"Diagnosis\",").isNotEmpty()) + @Test fun `an unregistered attribute still fails`() = assertTrue(errors("\"@dbSetNameX\": \"Analysis\",").isNotEmpty()) } diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/PortScopedAttrTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/PortScopedAttrTest.java index ce6fd38536..e0de78c524 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/loader/PortScopedAttrTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/loader/PortScopedAttrTest.java @@ -24,8 +24,8 @@ public void reset() { private static String model(String attr) { return "{ \"metadata.root\": { \"package\": \"acme\", \"children\": [\n" - + " { \"object.entity\": { \"name\": \"Diagnosis\", " + attr + " \"children\": [\n" - + " { \"source.rdb\": { \"@table\": \"diagnoses\" } },\n" + + " { \"object.entity\": { \"name\": \"Analysis\", " + attr + " \"children\": [\n" + + " { \"source.rdb\": { \"@table\": \"analyses\" } },\n" + " { \"field.long\": { \"name\": \"id\" } },\n" + " { \"identity.primary\": { \"@fields\": \"id\" } }\n" + " ] } }\n] } }"; @@ -45,16 +45,16 @@ private static boolean loads(String attr) { @Test public void aCsharpOnlyAttributeLoadsStrictly() { - assertTrue(loads("\"@dbSetName\": \"Diagnosis\",")); + assertTrue(loads("\"@dbSetName\": \"Analysis\",")); } @Test public void itIsTypeChecked() { - assertFalse(loads("\"@dbSetName\": [\"Diagnosis\"],")); + assertFalse(loads("\"@dbSetName\": [\"Analysis\"],")); } @Test public void anAttributeTheRegistryDoesNotCarryStillFails() { - assertFalse(loads("\"@dbSetNameX\": \"Diagnosis\",")); + assertFalse(loads("\"@dbSetNameX\": \"Analysis\",")); } } diff --git a/server/python/src/metaobjects/spec_metamodel/object.json b/server/python/src/metaobjects/spec_metamodel/object.json index 7dbadfcd07..fbae6bec09 100644 --- a/server/python/src/metaobjects/spec_metamodel/object.json +++ b/server/python/src/metaobjects/spec_metamodel/object.json @@ -31,7 +31,7 @@ { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] }, @@ -54,12 +54,12 @@ "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] }, @@ -76,7 +76,7 @@ { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] } diff --git a/server/python/tests/codegen/test_cli_import_time_naming.py b/server/python/tests/codegen/test_cli_import_time_naming.py index ba4d43ebe1..eb985771c9 100644 --- a/server/python/tests/codegen/test_cli_import_time_naming.py +++ b/server/python/tests/codegen/test_cli_import_time_naming.py @@ -23,13 +23,13 @@ META = { "metadata.root": { - "package": "acme::clinic", + "package": "acme::depot", "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - {"source.rdb": {"name": "src", "@table": "patients"}}, + {"source.rdb": {"name": "src", "@table": "players"}}, {"field.long": {"name": "id"}}, {"field.string": {"name": "firstName"}}, {"identity.primary": {"name": "pk", "@fields": ["id"], "@generation": "increment"}}, diff --git a/server/python/tests/loader/test_port_scoped_attr.py b/server/python/tests/loader/test_port_scoped_attr.py index d027c17981..ef7ae7d257 100644 --- a/server/python/tests/loader/test_port_scoped_attr.py +++ b/server/python/tests/loader/test_port_scoped_attr.py @@ -13,8 +13,8 @@ def _model(attr: dict) -> str: return json.dumps({"metadata.root": {"package": "acme", "children": [{"object.entity": { - "name": "Diagnosis", **attr, "children": [ - {"source.rdb": {"@table": "diagnoses"}}, + "name": "Analysis", **attr, "children": [ + {"source.rdb": {"@table": "analyses"}}, {"field.long": {"name": "id"}}, {"identity.primary": {"@fields": "id"}}, ]}}]}}) @@ -25,12 +25,12 @@ def _codes(attr: dict) -> list[str]: def test_a_csharp_only_attribute_loads_strictly() -> None: - assert _codes({"@dbSetName": "Diagnosis"}) == [] + assert _codes({"@dbSetName": "Analysis"}) == [] def test_it_is_type_checked() -> None: - assert _codes({"@dbSetName": ["Diagnosis"]}) != [] + assert _codes({"@dbSetName": ["Analysis"]}) != [] def test_an_attribute_the_registry_does_not_carry_still_fails() -> None: - assert any("UNKNOWN_ATTR" in c for c in _codes({"@dbSetNameX": "Diagnosis"})) + assert any("UNKNOWN_ATTR" in c for c in _codes({"@dbSetNameX": "Analysis"})) diff --git a/server/typescript/packages/cli/test/naming-strategies-config.test.ts b/server/typescript/packages/cli/test/naming-strategies-config.test.ts index 09e29ac8fd..10e96734ae 100644 --- a/server/typescript/packages/cli/test/naming-strategies-config.test.ts +++ b/server/typescript/packages/cli/test/naming-strategies-config.test.ts @@ -17,7 +17,7 @@ afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, forc const MODEL = JSON.stringify({ "metadata.root": { - package: "acme::clinic", + package: "acme::depot", children: [ { "object.entity": { name: "Provider", children: [ { "source.rdb": { name: "src", "@table": "providers" } }, @@ -47,7 +47,7 @@ async function project(columns: string, withTsConfig: boolean, tsConfig = TS_CON const root = await mkdtemp(join(tmpdir(), "naming-strategies-")); dirs.push(root); await mkdir(join(root, "metaobjects"), { recursive: true }); - await writeFile(join(root, "metaobjects", "meta.clinic.json"), MODEL, "utf8"); + await writeFile(join(root, "metaobjects", "meta.depot.json"), MODEL, "utf8"); await mkdir(join(root, ".metaobjects", "migrations"), { recursive: true }); await writeFile(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, naming: { columns }, migrate: { dialect: "sqlite" } }), "utf8"); diff --git a/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts b/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts index 375b4be8af..f503bea400 100644 --- a/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts +++ b/server/typescript/packages/cli/test/unit/gen-migrate-advice.test.ts @@ -36,7 +36,7 @@ const PAYLOAD = { async function load(children: unknown[]): Promise { const r = await new MetaDataLoader().load([ - new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "clinic", children } })), + new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "depot", children } })), ]); expect(r.errors).toEqual([]); return r.root; @@ -157,7 +157,7 @@ describe("genMigrateAdvice", () => { const root = project(); writeFileSync( join(root, "wrangler.toml"), - `name = "app"\n\n[[d1_databases]]\nbinding = "DB"\ndatabase_name = "clinic-db"\ndatabase_id = "x"\n`, + `name = "app"\n\n[[d1_databases]]\nbinding = "DB"\ndatabase_name = "depot-db"\ndatabase_id = "x"\n`, ); return root; }; @@ -166,7 +166,7 @@ describe("genMigrateAdvice", () => { const metadata = await load([PET, PAYLOAD]); const advice = await genMigrateAdvice(input({ metadata, projectRoot: d1Project() })); expect(advice).toContain("meta migrate --dialect d1 --d1 DB --slug "); - expect(advice).toContain("wrangler d1 migrations apply clinic-db --local"); + expect(advice).toContain("wrangler d1 migrations apply depot-db --local"); expect(advice).not.toContain("--dialect sqlite"); }); diff --git a/server/typescript/packages/codegen-ts/test/docs-resolved-column.test.ts b/server/typescript/packages/codegen-ts/test/docs-resolved-column.test.ts index 3602f738b5..3899b9954f 100644 --- a/server/typescript/packages/codegen-ts/test/docs-resolved-column.test.ts +++ b/server/typescript/packages/codegen-ts/test/docs-resolved-column.test.ts @@ -18,9 +18,9 @@ const MODEL = JSON.stringify({ children: [ { "object.entity": { - name: "Patient", + name: "Player", children: [ - { "source.rdb": { "@table": "patients" } }, + { "source.rdb": { "@table": "players" } }, { "field.long": { name: "id" } }, { "field.string": { name: "firstName", "@maxLength": 40 } }, { "field.string": { name: "npi", "@column": "NPI", "@maxLength": 10 } }, @@ -38,7 +38,7 @@ const MODEL = JSON.stringify({ }, }); -async function page(strategy: ColumnNamingStrategy, name = "Patient"): Promise { +async function page(strategy: ColumnNamingStrategy, name = "Player"): Promise { const res = await new MetaDataLoader().load([new InMemoryStringSource(MODEL, { id: "m.json", format: "json" })]); expect(res.errors).toEqual([]); const root = res.root; diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts index ebe14ff663..8144528335 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts @@ -16,7 +16,7 @@ async function load() { { "source.rdb": { name: "src", "@table": "providers" } }, { "field.long": { name: "id" } }, { "field.enum": { name: "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, - { "field.enum": { name: "kind", "@values": ["CLINIC", "LAB"] } }, + { "field.enum": { name: "kind", "@values": ["DEPOT", "LAB"] } }, { "field.enum": { name: "tier", "@values": ["GOLD", "SILVER"], "@constraintName": "CK_Providers_Tier" } }, { "identity.primary": { name: "pk", "@fields": ["id"] } }, ] } }, diff --git a/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts b/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts index 5e19c47c1c..ed51fde562 100644 --- a/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts +++ b/server/typescript/packages/codegen-ts/test/naming/collection-name.test.ts @@ -24,17 +24,17 @@ const model = (historyAttrs: Json): Json => ({ "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Case", children: [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { name: "Consignment", children: [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { name: "id" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } }, ] } }, - { "object.entity": { name: "CaseHistory", ...historyAttrs, children: [ - { "source.rdb": { "@table": "case_history" } }, + { "object.entity": { name: "ConsignmentHistory", ...historyAttrs, children: [ + { "source.rdb": { "@table": "consignment_history" } }, { "field.long": { name: "id" } }, - { "field.long": { name: "caseId" } }, + { "field.long": { name: "consignmentId" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } }, - { "identity.reference": { name: "caseId", "@fields": "caseId", "@references": "Case" } }, + { "identity.reference": { name: "consignmentId", "@fields": "consignmentId", "@references": "Consignment" } }, ] } }, ], }, @@ -69,39 +69,39 @@ async function gen(root: MetaRoot): Promise<{ files: Map; warnin } } -const history = (root: MetaRoot) => root.objects().find((o) => o.name === "CaseHistory")!; +const history = (root: MetaRoot) => root.objects().find((o) => o.name === "ConsignmentHistory")!; afterEach(() => resetNamingStrategiesForTesting()); describe("@collectionName", () => { test("absent, the standard pluralizer derives it", async () => { const root = await load(); - expect(collectionNameOf(history(root))).toBe("CaseHistories"); - expect(reverseHopName(history(root))).toBe("caseHistories"); + expect(collectionNameOf(history(root))).toBe("ConsignmentHistories"); + expect(reverseHopName(history(root))).toBe("consignmentHistories"); }); test("names the REST segment, the list and finder exports, the collection variable and the reverse hop", async () => { - const root = await load({ "@collectionName": "CaseHistory" }); - expect(reverseHopName(history(root))).toBe("caseHistory"); + const root = await load({ "@collectionName": "ConsignmentHistory" }); + expect(reverseHopName(history(root))).toBe("consignmentHistory"); const { files, warnings } = await gen(root); - const queries = files.get("CaseHistory.queries.ts")!; - expect(queries).toContain("export async function listCaseHistory("); - expect(queries).toContain("export async function findCaseHistoryByCase("); - expect(queries).toContain(".from(caseHistory)"); - expect(files.get("CaseHistory.ts")!).toContain("export const caseHistory = "); - expect([...files.values()].join("\n")).toContain('"/case_history"'); + const queries = files.get("ConsignmentHistory.queries.ts")!; + expect(queries).toContain("export async function listConsignmentHistory("); + expect(queries).toContain("export async function findConsignmentHistoryByConsignment("); + expect(queries).toContain(".from(consignmentHistory)"); + expect(files.get("ConsignmentHistory.ts")!).toContain("export const consignmentHistory = "); + expect([...files.values()].join("\n")).toContain('"/consignment_history"'); expect(warnings.filter((w) => w.includes("deprecated"))).toEqual([]); }); test("@dbSetName is its deprecated alias: the same names, and a warning", async () => { - const root = await load({ "@dbSetName": "CaseHistory" }); + const root = await load({ "@dbSetName": "ConsignmentHistory" }); const { files, warnings } = await gen(root); - expect(files.get("CaseHistory.queries.ts")!).toContain("export async function listCaseHistory("); + expect(files.get("ConsignmentHistory.queries.ts")!).toContain("export async function listConsignmentHistory("); expect(warnings.some((w) => w.includes("@dbSetName is deprecated") && w.includes("@collectionName"))).toBe(true); }); test("declaring both is refused", async () => { - const root = await load({ "@collectionName": "CaseHistory", "@dbSetName": "Histories" }); + const root = await load({ "@collectionName": "ConsignmentHistory", "@dbSetName": "Histories" }); expect(() => collectionNameOf(history(root))).toThrow(/declares both @collectionName and @dbSetName/); }); }); @@ -156,22 +156,22 @@ describe("the pluggable pluralizer (naming.collections)", () => { test("the project's pluralizer names every object without @collectionName", async () => { const root = await load(); Object.assign(root, { physicalNaming: { ...root.physicalNaming, collections: "none" } }); - expect(collectionNameOf(history(root))).toBe("CaseHistory"); + expect(collectionNameOf(history(root))).toBe("ConsignmentHistory"); const { files } = await gen(root); - expect(files.get("Case.queries.ts")!).toContain("export async function listCase("); + expect(files.get("Consignment.queries.ts")!).toContain("export async function listConsignment("); }); test("an application registers its own, and every artifact follows it", async () => { - // Distinguishable from `standard` (CaseHistories) on purpose: a test whose pluralizer agrees + // Distinguishable from `standard` (ConsignmentHistories) on purpose: a test whose pluralizer agrees // with the default cannot tell the two apart. registerPluralizer("latin", (n) => (n.endsWith("History") ? n.slice(0, -1) + "ae" : n + "a")); const root = await load(); Object.assign(root, { physicalNaming: { ...root.physicalNaming, collections: "latin" } }); - expect(collectionNameOf(history(root))).toBe("CaseHistorae"); - expect(reverseHopName(history(root))).toBe("caseHistorae"); + expect(collectionNameOf(history(root))).toBe("ConsignmentHistorae"); + expect(reverseHopName(history(root))).toBe("consignmentHistorae"); const { files } = await gen(root); - expect(files.get("CaseHistory.queries.ts")!).toContain("export async function listCaseHistorae("); - expect([...files.values()].join("\n")).toContain('"/case_historae"'); + expect(files.get("ConsignmentHistory.queries.ts")!).toContain("export async function listConsignmentHistorae("); + expect([...files.values()].join("\n")).toContain('"/consignment_historae"'); }); test("an unknown name fails loudly, naming the built-ins", () => { diff --git a/server/typescript/packages/codegen-ts/test/projection/first-multihop.test.ts b/server/typescript/packages/codegen-ts/test/projection/first-multihop.test.ts index f2c7228a1c..cb7612a569 100644 --- a/server/typescript/packages/codegen-ts/test/projection/first-multihop.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/first-multihop.test.ts @@ -10,34 +10,34 @@ const MODEL = { "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Patient", children: [ - { "source.rdb": { "@table": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.rdb": { "@table": "players" } }, { "field.long": { name: "id" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, - { "object.entity": { name: "Case", children: [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { name: "Camp", children: [ + { "source.rdb": { "@table": "camps" } }, { "field.long": { name: "id" } }, - { "field.long": { name: "patientId" } }, - { "field.long": { name: "programId" } }, + { "field.long": { name: "playerId" } }, + { "field.long": { name: "seasonId" } }, { "field.boolean": { name: "active" } }, { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "patient", "@fields": "patientId", "@references": "Patient" } }, + { "identity.reference": { name: "player", "@fields": "playerId", "@references": "Player" } }, ] } }, - { "object.entity": { name: "Caregiver", children: [ - { "source.rdb": { "@table": "caregivers" } }, + { "object.entity": { name: "Coach", children: [ + { "source.rdb": { "@table": "coaches" } }, { "field.long": { name: "id" } }, - { "field.long": { name: "patientId" } }, + { "field.long": { name: "playerId" } }, { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "patient", "@fields": "patientId", "@references": "Patient" } }, + { "identity.reference": { name: "player", "@fields": "playerId", "@references": "Player" } }, ] } }, - { "object.projection": { name: "CaregiverExtract", children: [ - { "source.rdb": { "@kind": "view", "@table": "v_caregiver_extract" } }, - { "field.long": { name: "id", extends: "Caregiver.id" } }, - { "field.long": { name: "programId", children: [{ "origin.first": { - "@of": "Case.programId", "@via": "Caregiver.patient.cases", "@orderBy": ["id:desc"], "@filter": { active: true }, + { "object.projection": { name: "CoachExtract", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_coach_extract" } }, + { "field.long": { name: "id", extends: "Coach.id" } }, + { "field.long": { name: "seasonId", children: [{ "origin.first": { + "@of": "Camp.seasonId", "@via": "Coach.player.camps", "@orderBy": ["id:desc"], "@filter": { active: true }, } }] } }, - { "identity.primary": { name: "id", extends: "Caregiver.id" } }, + { "identity.primary": { name: "id", extends: "Coach.id" } }, ] } }, ], }, @@ -49,8 +49,8 @@ describe("first-multihop — origin.first follows a multi-hop @via", () => { expect(errors).toEqual([]); const [v] = buildProjectionViews(root, { dialect: "postgres" }); expect(v!.sql).toMatch( - /\(SELECT (\w+)\.program_id FROM public\.patients (\w+) INNER JOIN public\.cases \1 ON \1\.patient_id = \2\.id WHERE \2\.id = c\.patient_id AND \1\.active = TRUE ORDER BY \1\.id DESC NULLS LAST, \1\.id ASC LIMIT 1\) AS program_id/, + /\(SELECT (\w+)\.season_id FROM public\.players (\w+) INNER JOIN public\.camps \1 ON \1\.player_id = \2\.id WHERE \2\.id = c\.player_id AND \1\.active = TRUE ORDER BY \1\.id DESC NULLS LAST, \1\.id ASC LIMIT 1\) AS season_id/, ); - expect([...v!.dependsOn].sort()).toEqual(["caregivers", "cases", "patients"]); + expect([...v!.dependsOn].sort()).toEqual(["camps", "coaches", "players"]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/hipaa-gate-entity-derived.test.ts b/server/typescript/packages/codegen-ts/test/projection/hipaa-gate-entity-derived.test.ts deleted file mode 100644 index b9719fb488..0000000000 --- a/server/typescript/packages/codegen-ts/test/projection/hipaa-gate-entity-derived.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -// rc.19 Phase 6 — the HIPAA-gate shape end to end: a segment.filter on Consent that uses `now` -// (rc.19 `now`), a derived boolean declared ONCE on Patient as origin.first over that segment -// (origin-segment) along the reverse of Consent.patientId (R-walk), and other projections that -// filter on it without outputting it — through a to-one path (entity-derived + G7 joined) or on -// their base. The SQL is built, then run on SQLite against rows that exercise the reset point. - -import { describe, test, expect } from "bun:test"; -import { Database } from "bun:sqlite"; -import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; -import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; - -const MODEL = { - "metadata.root": { - package: "acme", - children: [ - { "object.entity": { name: "Patient", children: [ - { "source.rdb": { "@table": "patients" } }, - { "field.long": { name: "id" } }, - { "field.boolean": { name: "hasActiveHipaaConsent", children: [ - { "origin.first": { - "@via": "Patient.consents", "@of": "Consent.consentIsOnFile", - "@orderBy": ["id:desc"], "@segment": "hipaaDecisive", - } }, - ] } }, - { "identity.primary": { name: "id", "@fields": "id" } }, - ] } }, - { "object.entity": { name: "Consent", children: [ - { "source.rdb": { "@table": "consents" } }, - { "field.long": { name: "id" } }, - { "field.long": { name: "patientId", "@required": true } }, - { "field.int": { name: "consentTypeId" } }, - { "field.boolean": { name: "consentIsOnFile" } }, - { "field.boolean": { name: "patientConsent" } }, - { "field.date": { name: "dateReceived" } }, - { "field.date": { name: "effectiveEndDate" } }, - { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "patientId", "@fields": "patientId", "@references": "Patient" } }, - { "segment.filter": { name: "hipaaDecisive", "@filter": { - consentTypeId: 1, - or: [ - { consentIsOnFile: false }, - { and: [ - { consentIsOnFile: true }, - { or: [{ patientConsent: null }, { patientConsent: true }] }, - { dateReceived: { lte: { now: "P0D" } } }, - { or: [{ effectiveEndDate: null }, { effectiveEndDate: { gte: { now: "P0D" } } }] }, - ] }, - ], - } } }, - ] } }, - { "object.entity": { name: "Case", children: [ - { "source.rdb": { "@table": "cases" } }, - { "field.long": { name: "id" } }, - { "field.long": { name: "patientId", "@required": true } }, - { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "patientId", "@fields": "patientId", "@references": "Patient" } }, - ] } }, - { "object.entity": { name: "Authorization", children: [ - { "source.rdb": { "@table": "authorizations" } }, - { "field.long": { name: "id" } }, - { "field.long": { name: "caseId", "@required": true } }, - { "field.string": { name: "code" } }, - { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "caseId", "@fields": "caseId", "@references": "Case" } }, - ] } }, - { "object.projection": { name: "AuthorizationExtract", "@filter": { "caseId.patientId.hasActiveHipaaConsent": true }, children: [ - { "source.rdb": { "@kind": "view", "@table": "v_authorization_extract" } }, - { "field.long": { name: "id", extends: "Authorization.id" } }, - { "field.string": { name: "code", extends: "Authorization.code" } }, - { "identity.primary": { name: "id", extends: "Authorization.id" } }, - ] } }, - { "object.projection": { name: "PatientExtract", "@filter": { hasActiveHipaaConsent: true }, children: [ - { "source.rdb": { "@kind": "view", "@table": "v_patient_extract" } }, - { "field.long": { name: "id", extends: "Patient.id" } }, - { "identity.primary": { name: "id", extends: "Patient.id" } }, - ] } }, - ], - }, -}; - -async function load() { - const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); - expect(result.errors).toEqual([]); - return result.root; -} - -describe("the HIPAA gate: an entity-derived boolean over a segment, used in other projections' @filter", () => { - test("loads: Patient needs no read source for a derived field projections reach", async () => { - await load(); - }); - - test("the path filter inlines the patient's correlated subquery on the joined patient", async () => { - const views = buildProjectionViews(await load(), { dialect: "postgres" }); - const auth = views.find((v) => v.name === "v_authorization_extract")!; - expect(auth.sql).toContain("LEFT OUTER JOIN public.cases c ON c.id = a.case_id"); - expect(auth.sql).toContain("LEFT OUTER JOIN public.patients p ON p.id = c.patient_id"); - // The segment's predicate (with `now` of the date kind) scopes the subquery; it is ordered id:desc. - expect(auth.sql).toMatch(/WHERE \(\(SELECT (\w+)\.consent_is_on_file FROM public\.consents \1 WHERE \1\.patient_id = p\.id AND \(\1\.consent_type_id = 1 AND/); - expect(auth.sql).toContain(".date_received <= CAST(((now() AT TIME ZONE 'UTC') + INTERVAL 'P0D') AS DATE)"); - expect(auth.sql).toMatch(/ORDER BY \w+\.id DESC NULLS LAST, \w+\.id ASC LIMIT 1\)\) = TRUE/); - expect(auth.sql).not.toContain("has_active_hipaa_consent"); - expect(auth.dependsOn).toEqual(expect.arrayContaining(["authorizations", "cases", "patients", "consents"])); - }); - - test("on the base row, the same predicate filters the patients", async () => { - const views = buildProjectionViews(await load(), { dialect: "postgres" }); - const pat = views.find((v) => v.name === "v_patient_extract")!; - expect(pat.sql).toMatch(/WHERE \(\(SELECT \w+\.consent_is_on_file FROM public\.consents \w+ WHERE \w+\.patient_id = p\.id/); - }); - - test("runs: the latest decisive row decides, an opt-out resets, future and expired rows do not count", async () => { - const views = buildProjectionViews(await load(), { dialect: "sqlite" }); - const db = new Database(":memory:"); - db.exec(` - CREATE TABLE patients (id INTEGER PRIMARY KEY); - CREATE TABLE consents (id INTEGER PRIMARY KEY, patient_id INTEGER, consent_type_id INTEGER, consent_is_on_file INTEGER, - patient_consent INTEGER, date_received TEXT, effective_end_date TEXT); - CREATE TABLE cases (id INTEGER PRIMARY KEY, patient_id INTEGER); - CREATE TABLE authorizations (id INTEGER PRIMARY KEY, case_id INTEGER, code TEXT); - `); - for (const v of views) db.exec(`CREATE VIEW ${v.name} AS ${v.sql}`); - // 1: live consent. 2: consent, then an opt-out after it. 3: opt-out, then a consent after it. - // 4: only a future-dated consent. 5: only an expired consent. 6: a live non-HIPAA consent. - // 7: live consent with patientConsent = false (refused). - db.exec(` - INSERT INTO patients (id) VALUES (1), (2), (3), (4), (5), (6), (7); - INSERT INTO consents VALUES - (10, 1, 1, 1, NULL, '2020-01-01', NULL), - (20, 2, 1, 1, 1, '2020-01-01', NULL), (21, 2, 1, 0, NULL, NULL, NULL), - (30, 3, 1, 0, NULL, NULL, NULL), (31, 3, 1, 1, 1, '2020-01-01', '2999-01-01'), - (40, 4, 1, 1, 1, '2999-01-01', NULL), - (50, 5, 1, 1, 1, '2020-01-01', '2020-06-01'), - (60, 6, 2, 1, 1, '2020-01-01', NULL), - (70, 7, 1, 1, 0, '2020-01-01', NULL); - INSERT INTO cases (id, patient_id) VALUES (100, 1), (200, 2), (300, 3), (400, 4), (500, 5), (600, 6), (700, 7); - INSERT INTO authorizations (id, case_id, code) VALUES (1000, 100, 'a'), (2000, 200, 'b'), (3000, 300, 'c'), - (4000, 400, 'd'), (5000, 500, 'e'), (6000, 600, 'f'), (7000, 700, 'g'); - `); - const ids = (sql: string) => (db.query(sql).all() as { id: number }[]).map((r) => r.id); - expect(ids("SELECT id FROM v_patient_extract ORDER BY id")).toEqual([1, 3]); - expect(ids("SELECT id FROM v_authorization_extract ORDER BY id")).toEqual([1000, 3000]); - }); -}); diff --git a/server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts b/server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts new file mode 100644 index 0000000000..ebf597554d --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/league-gate-entity-derived.test.ts @@ -0,0 +1,143 @@ +// rc.19 Phase 6 — the league-gate shape end to end: a segment.filter on Contract that uses `now` +// (rc.19 `now`), a derived boolean declared ONCE on Player as origin.first over that segment +// (origin-segment) along the reverse of Contract.playerId (R-walk), and other projections that +// filter on it without outputting it — through a to-one path (entity-derived + G7 joined) or on +// their base. The SQL is built, then run on SQLite against rows that exercise the reset point. + +import { describe, test, expect } from "bun:test"; +import { Database } from "bun:sqlite"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +const MODEL = { + "metadata.root": { + package: "acme", + children: [ + { "object.entity": { name: "Player", children: [ + { "source.rdb": { "@table": "players" } }, + { "field.long": { name: "id" } }, + { "field.boolean": { name: "hasActiveLeagueContract", children: [ + { "origin.first": { + "@via": "Player.contracts", "@of": "Contract.contractIsOnFile", + "@orderBy": ["id:desc"], "@segment": "leagueDecisive", + } }, + ] } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.entity": { name: "Contract", children: [ + { "source.rdb": { "@table": "contracts" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "playerId", "@required": true } }, + { "field.int": { name: "contractTypeId" } }, + { "field.boolean": { name: "contractIsOnFile" } }, + { "field.boolean": { name: "playerContract" } }, + { "field.date": { name: "dateReceived" } }, + { "field.date": { name: "effectiveEndDate" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "playerId", "@fields": "playerId", "@references": "Player" } }, + { "segment.filter": { name: "leagueDecisive", "@filter": { + contractTypeId: 1, + or: [ + { contractIsOnFile: false }, + { and: [ + { contractIsOnFile: true }, + { or: [{ playerContract: null }, { playerContract: true }] }, + { dateReceived: { lte: { now: "P0D" } } }, + { or: [{ effectiveEndDate: null }, { effectiveEndDate: { gte: { now: "P0D" } } }] }, + ] }, + ], + } } }, + ] } }, + { "object.entity": { name: "Camp", children: [ + { "source.rdb": { "@table": "camps" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "playerId", "@required": true } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "playerId", "@fields": "playerId", "@references": "Player" } }, + ] } }, + { "object.entity": { name: "Authorization", children: [ + { "source.rdb": { "@table": "authorizations" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "campId", "@required": true } }, + { "field.string": { name: "code" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "campId", "@fields": "campId", "@references": "Camp" } }, + ] } }, + { "object.projection": { name: "AuthorizationExtract", "@filter": { "campId.playerId.hasActiveLeagueContract": true }, children: [ + { "source.rdb": { "@kind": "view", "@table": "v_authorization_extract" } }, + { "field.long": { name: "id", extends: "Authorization.id" } }, + { "field.string": { name: "code", extends: "Authorization.code" } }, + { "identity.primary": { name: "id", extends: "Authorization.id" } }, + ] } }, + { "object.projection": { name: "PlayerExtract", "@filter": { hasActiveLeagueContract: true }, children: [ + { "source.rdb": { "@kind": "view", "@table": "v_player_extract" } }, + { "field.long": { name: "id", extends: "Player.id" } }, + { "identity.primary": { name: "id", extends: "Player.id" } }, + ] } }, + ], + }, +}; + +async function load() { + const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(result.errors).toEqual([]); + return result.root; +} + +describe("the league gate: an entity-derived boolean over a segment, used in other projections' @filter", () => { + test("loads: Player needs no read source for a derived field projections reach", async () => { + await load(); + }); + + test("the path filter inlines the player's correlated subquery on the joined player", async () => { + const views = buildProjectionViews(await load(), { dialect: "postgres" }); + const auth = views.find((v) => v.name === "v_authorization_extract")!; + expect(auth.sql).toContain("LEFT OUTER JOIN public.camps c ON c.id = a.camp_id"); + expect(auth.sql).toContain("LEFT OUTER JOIN public.players p ON p.id = c.player_id"); + // The segment's predicate (with `now` of the date kind) scopes the subquery; it is ordered id:desc. + expect(auth.sql).toMatch(/WHERE \(\(SELECT (\w+)\.contract_is_on_file FROM public\.contracts \1 WHERE \1\.player_id = p\.id AND \(\1\.contract_type_id = 1 AND/); + expect(auth.sql).toContain(".date_received <= CAST(((now() AT TIME ZONE 'UTC') + INTERVAL 'P0D') AS DATE)"); + expect(auth.sql).toMatch(/ORDER BY \w+\.id DESC NULLS LAST, \w+\.id ASC LIMIT 1\)\) = TRUE/); + expect(auth.sql).not.toContain("has_active_league_contract"); + expect(auth.dependsOn).toEqual(expect.arrayContaining(["authorizations", "camps", "players", "contracts"])); + }); + + test("on the base row, the same predicate filters the players", async () => { + const views = buildProjectionViews(await load(), { dialect: "postgres" }); + const pat = views.find((v) => v.name === "v_player_extract")!; + expect(pat.sql).toMatch(/WHERE \(\(SELECT \w+\.contract_is_on_file FROM public\.contracts \w+ WHERE \w+\.player_id = p\.id/); + }); + + test("runs: the latest decisive row decides, an opt-out resets, future and expired rows do not count", async () => { + const views = buildProjectionViews(await load(), { dialect: "sqlite" }); + const db = new Database(":memory:"); + db.exec(` + CREATE TABLE players (id INTEGER PRIMARY KEY); + CREATE TABLE contracts (id INTEGER PRIMARY KEY, player_id INTEGER, contract_type_id INTEGER, contract_is_on_file INTEGER, + player_contract INTEGER, date_received TEXT, effective_end_date TEXT); + CREATE TABLE camps (id INTEGER PRIMARY KEY, player_id INTEGER); + CREATE TABLE authorizations (id INTEGER PRIMARY KEY, camp_id INTEGER, code TEXT); + `); + for (const v of views) db.exec(`CREATE VIEW ${v.name} AS ${v.sql}`); + // 1: live contract. 2: contract, then an opt-out after it. 3: opt-out, then a contract after it. + // 4: only a future-dated contract. 5: only an expired contract. 6: a live non-league contract. + // 7: live contract with playerContract = false (refused). + db.exec(` + INSERT INTO players (id) VALUES (1), (2), (3), (4), (5), (6), (7); + INSERT INTO contracts VALUES + (10, 1, 1, 1, NULL, '2020-01-01', NULL), + (20, 2, 1, 1, 1, '2020-01-01', NULL), (21, 2, 1, 0, NULL, NULL, NULL), + (30, 3, 1, 0, NULL, NULL, NULL), (31, 3, 1, 1, 1, '2020-01-01', '2999-01-01'), + (40, 4, 1, 1, 1, '2999-01-01', NULL), + (50, 5, 1, 1, 1, '2020-01-01', '2020-06-01'), + (60, 6, 2, 1, 1, '2020-01-01', NULL), + (70, 7, 1, 1, 0, '2020-01-01', NULL); + INSERT INTO camps (id, player_id) VALUES (100, 1), (200, 2), (300, 3), (400, 4), (500, 5), (600, 6), (700, 7); + INSERT INTO authorizations (id, camp_id, code) VALUES (1000, 100, 'a'), (2000, 200, 'b'), (3000, 300, 'c'), + (4000, 400, 'd'), (5000, 500, 'e'), (6000, 600, 'f'), (7000, 700, 'g'); + `); + const ids = (sql: string) => (db.query(sql).all() as { id: number }[]).map((r) => r.id); + expect(ids("SELECT id FROM v_player_extract ORDER BY id")).toEqual([1, 3]); + expect(ids("SELECT id FROM v_authorization_extract ORDER BY id")).toEqual([1000, 3000]); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/projection-extends-filtered-projection.test.ts b/server/typescript/packages/codegen-ts/test/projection/projection-extends-filtered-projection.test.ts index 748979a137..ecebbbdd9c 100644 --- a/server/typescript/packages/codegen-ts/test/projection/projection-extends-filtered-projection.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/projection-extends-filtered-projection.test.ts @@ -1,5 +1,5 @@ // rc.19 fix round, C1: a projection that extends a FILTERED projection keeps the base's row scope. -// Codegen read only the extender's own @filter, so a gated base (a consent or HIPAA gate) became +// Codegen read only the extender's own @filter, so a gated base (an access gate) became // an ungated view in the extender, with no error. The effective filter is every level's @filter, // supers first, ANDed — through any depth of inheritance. @@ -12,7 +12,7 @@ const plan = { "object.entity": { name: "Plan", children: [ { "field.long": { name: "id" } }, { "field.string": { name: "name" } }, { "field.string": { name: "code" } }, - { "field.boolean": { name: "consented" } }, + { "field.boolean": { name: "contracted" } }, { "field.boolean": { name: "deleted" } }, { "field.int": { name: "tier" } }, { "identity.primary": { name: "id", "@fields": "id" } }, @@ -45,23 +45,23 @@ async function sqlOf(projections: unknown[]) { describe("C1 — an extender keeps its base projection's @filter", () => { test("a gated base keeps its gate in an extender that declares no filter", async () => { - const sql = await sqlOf([gated({ consented: true }), leaf("GatedPlans", undefined)]); - expect(sql).toContain("WHERE p.consented = TRUE"); + const sql = await sqlOf([gated({ contracted: true }), leaf("GatedPlans", undefined)]); + expect(sql).toContain("WHERE p.contracted = TRUE"); }); test("the extender's own filter is ANDed with the base's, base first", async () => { - const sql = await sqlOf([gated({ consented: true }), leaf("GatedPlans", { deleted: false })]); - expect(sql).toMatch(/WHERE \(p\.consented = TRUE AND p\.deleted = FALSE\)/); + const sql = await sqlOf([gated({ contracted: true }), leaf("GatedPlans", { deleted: false })]); + expect(sql).toMatch(/WHERE \(p\.contracted = TRUE AND p\.deleted = FALSE\)/); }); test("every level of a deeper chain contributes, root-most first", async () => { - const sql = await sqlOf([gated({ consented: true }), middle({ deleted: false }), leaf("LivePlans", { tier: { gte: 2 } })]); - expect(sql).toMatch(/WHERE \(p\.consented = TRUE AND p\.deleted = FALSE AND p\.tier >= 2\)/); + const sql = await sqlOf([gated({ contracted: true }), middle({ deleted: false }), leaf("LivePlans", { tier: { gte: 2 } })]); + expect(sql).toMatch(/WHERE \(p\.contracted = TRUE AND p\.deleted = FALSE AND p\.tier >= 2\)/); }); test("a gate two levels up survives an unfiltered middle level", async () => { - const sql = await sqlOf([gated({ consented: true }), middle(undefined), leaf("LivePlans", undefined)]); - expect(sql).toContain("WHERE p.consented = TRUE"); + const sql = await sqlOf([gated({ contracted: true }), middle(undefined), leaf("LivePlans", undefined)]); + expect(sql).toContain("WHERE p.contracted = TRUE"); }); test("an extender of an unfiltered base emits no WHERE (unchanged)", async () => { diff --git a/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts b/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts index dbb3804827..56477d37c3 100644 --- a/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts @@ -1,7 +1,7 @@ // Phase 5, bug R-walk: an origin's @via may walk the REVERSE of an identity.reference the // far entity declares, with no relationship declared for it. The hop is named after the -// referencing entity's collection name (lowerFirst(pluralize()), `Patient.consents` -// for Consent.patient). The loader used to refuse it ("no such relationship or reference"), +// referencing entity's collection name (lowerFirst(pluralize()), `Player.contracts` +// for Contract.player). The loader used to refuse it ("no such relationship or reference"), // though codegen's correlations walk references both ways. import { describe, test, expect } from "bun:test"; @@ -10,13 +10,13 @@ import { buildProjectionViews } from "../../src/projection/build-projection-view const MODEL = { "metadata.root": { - "package": "acme::care", + "package": "acme::league", "children": [ { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ - { "source.rdb": { "@table": "patients" } }, + { "source.rdb": { "@table": "players" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] @@ -24,26 +24,26 @@ const MODEL = { }, { "object.entity": { - "name": "Consent", + "name": "Contract", "children": [ - { "source.rdb": { "@table": "consents" } }, + { "source.rdb": { "@table": "contracts" } }, { "field.long": { "name": "id" } }, - { "field.long": { "name": "patientId" } }, + { "field.long": { "name": "playerId" } }, { "field.boolean": { "name": "onFile" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "patient", "@fields": "patientId", "@references": "acme::care::Patient" } } + { "identity.reference": { "name": "player", "@fields": "playerId", "@references": "acme::league::Player" } } ] } }, { "object.projection": { - "name": "PatientConsentSummary", + "name": "PlayerContractSummary", "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_patient_consent_summary" } }, - { "field.long": { "name": "id", "extends": "acme::care::Patient.id" } }, - { "field.int": { "name": "consentCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::care::Consent.id", "@via": "acme::care::Patient.consents" } } ] } }, - { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::care::Consent.onFile", "@via": "acme::care::Patient.consents", "@orderBy": ["id:desc"] } } ] } }, - { "identity.primary": { "name": "id", "extends": "acme::care::Patient.id" } } + { "source.rdb": { "@kind": "view", "@view": "v_player_contract_summary" } }, + { "field.long": { "name": "id", "extends": "acme::league::Player.id" } }, + { "field.int": { "name": "contractCount", "children": [ { "origin.aggregate": { "@agg": "count", "@of": "acme::league::Contract.id", "@via": "acme::league::Player.contracts" } } ] } }, + { "field.boolean": { "name": "latestOnFile", "children": [ { "origin.first": { "@of": "acme::league::Contract.onFile", "@via": "acme::league::Player.contracts", "@orderBy": ["id:desc"] } } ] } }, + { "identity.primary": { "name": "id", "extends": "acme::league::Player.id" } } ] } } @@ -55,12 +55,12 @@ async function load(model: unknown) { return new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); } -/** The model with a second reference from Consent to Patient: the reverse hop is ambiguous. */ +/** The model with a second reference from Contract to Player: the reverse hop is ambiguous. */ function twoReferences(): unknown { const m = JSON.parse(JSON.stringify(MODEL)); - const consent = m["metadata.root"].children[1]["object.entity"].children; - consent.push({ "field.long": { name: "witnessId" } }); - consent.push({ "identity.reference": { name: "witness", "@fields": "witnessId", "@references": "acme::care::Patient" } }); + const contract = m["metadata.root"].children[1]["object.entity"].children; + contract.push({ "field.long": { name: "witnessId" } }); + contract.push({ "identity.reference": { name: "witness", "@fields": "witnessId", "@references": "acme::league::Player" } }); return m; } @@ -74,16 +74,16 @@ describe("R-walk — a @via hop over the reverse of an identity.reference", () = const { root, errors } = await load(MODEL); expect(errors).toEqual([]); const [v] = buildProjectionViews(root, { dialect: "postgres" }); - expect(v!.sql).toContain("COUNT(DISTINCT c.id) AS consent_count"); - expect(v!.sql).toContain("LEFT OUTER JOIN public.consents c ON c.patient_id = p.id"); - expect(v!.sql).toMatch(/\(SELECT c0\.on_file FROM public\.consents c0 WHERE c0\.patient_id = p\.id ORDER BY c0\.id DESC NULLS LAST, c0\.id ASC LIMIT 1\) AS latest_on_file/); + expect(v!.sql).toContain("COUNT(DISTINCT c.id) AS contract_count"); + expect(v!.sql).toContain("LEFT OUTER JOIN public.contracts c ON c.player_id = p.id"); + expect(v!.sql).toMatch(/\(SELECT c0\.on_file FROM public\.contracts c0 WHERE c0\.player_id = p\.id ORDER BY c0\.id DESC NULLS LAST, c0\.id ASC LIMIT 1\) AS latest_on_file/); }); test("two references from the holder make the reverse hop ambiguous, named", async () => { const { errors } = await load(twoReferences()); expect(errors.length).toBeGreaterThan(0); expect((errors[0] as { code?: string }).code).toBe("ERR_AMBIGUOUS_PATH"); - expect(String(errors[0]!.message)).toContain('"patient", "witness"'); + expect(String(errors[0]!.message)).toContain('"player", "witness"'); }); }); @@ -92,17 +92,17 @@ describe("R-walk — a @via hop over the reverse of an identity.reference", () = // lacked was the name the rule gives. The refusal now lists the reverse hops onto the entity. describe("a reverse hop under a guessed name", () => { test("the refusal names the reverse hops onto the entity", async () => { - const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::care::Patient.consents", "acme::care::Patient.patient")); + const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::league::Player.contracts", "acme::league::Player.player")); const { errors } = await load(m); const msg = errors.map((e) => String(e.message)).join("\n"); - expect(msg).toContain(`no such relationship or reference "patient" on Patient`); - expect(msg).toContain(`The reverse hops from Patient are: "consents" (walks Consent.patient backwards)`); + expect(msg).toContain(`no such relationship or reference "player" on Player`); + expect(msg).toContain(`The reverse hops from Player are: "contracts" (walks Contract.player backwards)`); }); test("a @collectionName renames the hop, and the refusal says so", async () => { - const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::care::Patient.consents", "acme::care::Patient.consents2")); - m["metadata.root"].children[1]["object.entity"]["@collectionName"] = "ConsentLog"; + const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::league::Player.contracts", "acme::league::Player.contracts2")); + m["metadata.root"].children[1]["object.entity"]["@collectionName"] = "ContractLog"; const { errors } = await load(m); - expect(errors.map((e) => String(e.message)).join("\n")).toContain(`"consentLog" (walks Consent.patient backwards)`); + expect(errors.map((e) => String(e.message)).join("\n")).toContain(`"contractLog" (walks Contract.player backwards)`); }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts index 5a5e89b377..584a1bde31 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts @@ -1,6 +1,6 @@ // rc.19 Phase 6 Tier 2 view vocabulary (R58), one block per item: computed-over-joined, case, // now (as an expression leaf and in a projection @filter), correlated-filter and origin-segment -// on an aggregate. entity-derived is pinned end to end in hipaa-gate-entity-derived.test.ts. +// on an aggregate. entity-derived is pinned end to end in league-gate-entity-derived.test.ts. import { describe, test, expect } from "bun:test"; import { Database } from "bun:sqlite"; @@ -15,26 +15,26 @@ const ENTITIES = [ { "field.string": { name: "displayName" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, - { "object.entity": { name: "Case", children: [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { name: "Consignment", children: [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { name: "id" } }, { "field.long": { name: "statusId" } }, - { "field.int": { name: "priorType" } }, - { "field.int": { name: "cumulativeStatus" } }, + { "field.int": { name: "serviceLevel" } }, + { "field.int": { name: "rollupStatus" } }, { "field.int": { name: "status" } }, { "field.date": { name: "effectiveFrom" } }, { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "statusId", "@fields": "statusId", "@references": "Status" } }, ] } }, - { "object.entity": { name: "CaseHistory", "@collectionName": "CaseHistory", children: [ - { "source.rdb": { "@table": "case_history" } }, + { "object.entity": { name: "ConsignmentHistory", "@collectionName": "ConsignmentHistory", children: [ + { "source.rdb": { "@table": "consignment_history" } }, { "field.long": { name: "id" } }, - { "field.long": { name: "caseId", "@required": true } }, + { "field.long": { name: "consignmentId", "@required": true } }, { "field.long": { name: "statusId" } }, { "field.timestamp": { name: "createdDate" } }, { "field.boolean": { name: "active" } }, { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "caseId", "@fields": "caseId", "@references": "Case" } }, + { "identity.reference": { name: "consignmentId", "@fields": "consignmentId", "@references": "Consignment" } }, { "segment.filter": { name: "live", "@filter": { active: true } } }, ] } }, ]; @@ -42,9 +42,9 @@ const ENTITIES = [ const view = (name: string, fields: unknown[], extra: Record = {}) => ({ "object.projection": { name, ...extra, children: [ { "source.rdb": { "@kind": "view", "@table": `v_${name.toLowerCase()}` } }, - { "field.long": { name: "id", extends: "Case.id" } }, + { "field.long": { name: "id", extends: "Consignment.id" } }, ...fields, - { "identity.primary": { name: "id", extends: "Case.id" } }, + { "identity.primary": { name: "id", extends: "Consignment.id" } }, ] }, }); @@ -61,8 +61,8 @@ async function errorsOf(projection: unknown): Promise { return errors.map((e) => `${(e as { code?: string }).code}: ${(e as Error).message}`); } -const joinedName = { "field.string": { name: "statusName", children: [{ "origin.passthrough": { "@from": "Status.name", "@via": "Case.statusId" } }] } }; -const joinedDisplay = { "field.string": { name: "statusDisplay", children: [{ "origin.passthrough": { "@from": "Status.displayName", "@via": "Case.statusId" } }] } }; +const joinedName = { "field.string": { name: "statusName", children: [{ "origin.passthrough": { "@from": "Status.name", "@via": "Consignment.statusId" } }] } }; +const joinedDisplay = { "field.string": { name: "statusDisplay", children: [{ "origin.passthrough": { "@from": "Status.displayName", "@via": "Consignment.statusId" } }] } }; describe("computed-over-joined — an expression reads other projection fields", () => { test("COALESCE over two joined passthroughs", async () => { @@ -83,12 +83,12 @@ describe("computed-over-joined — an expression reads other projection fields", // rc.21 part B (U13): a scalar aggregate is readable (on the grouped row); a collect is not. test("a scalar aggregate is readable from an expression; a collect is not", async () => { const sql = await sqlOf(view("Agg", [ - { "field.long": { name: "entries", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CaseHistory.id", "@via": "Case.caseHistory" } }] } }, + { "field.long": { name: "entries", children: [{ "origin.aggregate": { "@agg": "count", "@of": "ConsignmentHistory.id", "@via": "Consignment.consignmentHistory" } }] } }, { "field.boolean": { name: "busy", children: [{ "origin.computed": { "@expr": { op: "gt", left: { field: "entries" }, right: { value: 3 } } } }] } }, ])); expect(sql).toContain("COUNT(DISTINCT c0.id) > 3 AS busy"); const errors = await errorsOf(view("Collect", [ - { "field.long": { name: "ids", isArray: true, children: [{ "origin.aggregate": { "@agg": "collect", "@of": "CaseHistory.id", "@via": "Case.caseHistory" } }] } }, + { "field.long": { name: "ids", isArray: true, children: [{ "origin.aggregate": { "@agg": "collect", "@of": "ConsignmentHistory.id", "@via": "Consignment.consignmentHistory" } }] } }, { "field.boolean": { name: "busy", children: [{ "origin.computed": { "@expr": { op: "isNull", arg: { field: "ids" } } } }] } }, ])); expect(errors.some((e) => e.includes("ids"))).toBe(true); @@ -96,29 +96,29 @@ describe("computed-over-joined — an expression reads other projection fields", }); describe("case — searched and simple CASE in an expression", () => { - test("searched: CASE WHEN cumulativeStatus = 0 THEN status ELSE cumulativeStatus END", async () => { + test("searched: CASE WHEN rollupStatus = 0 THEN status ELSE rollupStatus END", async () => { const sql = await sqlOf(view("Outcome", [ { "field.int": { name: "outcome", children: [{ "origin.computed": { "@expr": { - case: [{ when: { op: "eq", left: { field: "cumulativeStatus" }, right: { value: 0 } }, then: { field: "status" } }], - else: { field: "cumulativeStatus" }, + case: [{ when: { op: "eq", left: { field: "rollupStatus" }, right: { value: 0 } }, then: { field: "status" } }], + else: { field: "rollupStatus" }, } } }] } }, ])); - expect(sql).toContain("(CASE WHEN c.cumulative_status = 0 THEN c.status ELSE c.cumulative_status END) AS outcome"); + expect(sql).toContain("(CASE WHEN c.rollup_status = 0 THEN c.status ELSE c.rollup_status END) AS outcome"); }); - test("simple: CASE priorType WHEN 1 THEN 'Medical' WHEN 2 THEN 'Pharmacy' END, and it runs", async () => { - const projection = view("Benefit", [ - { "field.string": { name: "benefitTypeName", children: [{ "origin.computed": { "@expr": { - operand: { field: "priorType" }, - case: [{ when: { value: 1 }, then: { value: "Medical" } }, { when: { value: 2 }, then: { value: "Pharmacy" } }], + test("simple: CASE serviceLevel WHEN 1 THEN 'Standard' WHEN 2 THEN 'Express' END, and it runs", async () => { + const projection = view("ServiceLevel", [ + { "field.string": { name: "serviceLevelName", children: [{ "origin.computed": { "@expr": { + operand: { field: "serviceLevel" }, + case: [{ when: { value: 1 }, then: { value: "Standard" } }, { when: { value: 2 }, then: { value: "Express" } }], } } }] } }, ]); - expect(await sqlOf(projection)).toContain("(CASE c.prior_type WHEN 1 THEN 'Medical' WHEN 2 THEN 'Pharmacy' END) AS benefit_type_name"); + expect(await sqlOf(projection)).toContain("(CASE c.service_level WHEN 1 THEN 'Standard' WHEN 2 THEN 'Express' END) AS service_level_name"); const db = new Database(":memory:"); - db.exec("CREATE TABLE cases (id INTEGER PRIMARY KEY, prior_type INTEGER); INSERT INTO cases VALUES (1, 1), (2, 2), (3, 0);"); + db.exec("CREATE TABLE consignments (id INTEGER PRIMARY KEY, service_level INTEGER); INSERT INTO consignments VALUES (1, 1), (2, 2), (3, 0);"); db.exec(`CREATE VIEW v AS ${await sqlOf(projection, "sqlite")}`); - expect(db.query("SELECT id, benefit_type_name AS t FROM v ORDER BY id").all()).toEqual([ - { id: 1, t: "Medical" }, { id: 2, t: "Pharmacy" }, { id: 3, t: null }, + expect(db.query("SELECT id, service_level_name AS t FROM v ORDER BY id").all()).toEqual([ + { id: 1, t: "Standard" }, { id: 2, t: "Express" }, { id: 3, t: null }, ]); }); @@ -152,7 +152,7 @@ describe("correlated-filter — an origin @filter compares with the base row", ( test("MIN(createdDate) of the histories in the case's own status", async () => { const sql = await sqlOf(view("Placed", [ { "field.timestamp": { name: "statusPlaced", children: [{ "origin.aggregate": { - "@agg": "min", "@of": "CaseHistory.createdDate", "@via": "Case.caseHistory", + "@agg": "min", "@of": "ConsignmentHistory.createdDate", "@via": "Consignment.consignmentHistory", "@filter": { statusId: { eq: { field: "statusId" } } }, } }] } }, ])); @@ -162,14 +162,14 @@ describe("correlated-filter — an origin @filter compares with the base row", ( test("the null-safe comparison, in an origin.first subquery", async () => { const sql = await sqlOf(view("Other", [ { "field.long": { name: "otherStatus", children: [{ "origin.first": { - "@of": "CaseHistory.statusId", "@via": "Case.caseHistory", "@orderBy": ["statusId"], + "@of": "ConsignmentHistory.statusId", "@via": "Consignment.consignmentHistory", "@orderBy": ["statusId"], "@filter": { statusId: { isDistinctFrom: { field: "statusId" } } }, } }] } }, ])); - expect(sql).toMatch(/WHERE (\w+)\.case_id = c\.id AND \1\.status_id IS DISTINCT FROM c\.status_id ORDER BY/); + expect(sql).toMatch(/WHERE (\w+)\.consignment_id = c\.id AND \1\.status_id IS DISTINCT FROM c\.status_id ORDER BY/); expect(await sqlOf(view("Other2", [ { "field.long": { name: "otherStatus", children: [{ "origin.first": { - "@of": "CaseHistory.statusId", "@via": "Case.caseHistory", "@orderBy": ["statusId"], + "@of": "ConsignmentHistory.statusId", "@via": "Consignment.consignmentHistory", "@orderBy": ["statusId"], "@filter": { statusId: { isDistinctFrom: { field: "statusId" } } }, } }] } }, ]), "sqlite")).toMatch(/\.status_id IS NOT c\.status_id/); @@ -178,11 +178,11 @@ describe("correlated-filter — an origin @filter compares with the base row", ( test("a base field the base row lacks, and a null-safe op without a field, are refused", async () => { const bad = await errorsOf(view("Bad", [ { "field.timestamp": { name: "x", children: [{ "origin.aggregate": { - "@agg": "min", "@of": "CaseHistory.createdDate", "@via": "Case.caseHistory", + "@agg": "min", "@of": "ConsignmentHistory.createdDate", "@via": "Consignment.consignmentHistory", "@filter": { statusId: { eq: { field: "nope" } } }, } }] } }, { "field.timestamp": { name: "y", children: [{ "origin.aggregate": { - "@agg": "min", "@of": "CaseHistory.createdDate", "@via": "Case.caseHistory", + "@agg": "min", "@of": "ConsignmentHistory.createdDate", "@via": "Consignment.consignmentHistory", "@filter": { statusId: { isDistinctFrom: 3 } }, } }] } }, ])); @@ -194,7 +194,7 @@ describe("origin-segment — @segment on origin.aggregate and origin.first", () test("the related entity's segment scopes the aggregate, ANDed with @filter", async () => { const sql = await sqlOf(view("LiveCount", [ { "field.long": { name: "live", children: [{ "origin.aggregate": { - "@agg": "count", "@of": "CaseHistory.id", "@via": "Case.caseHistory", "@segment": "live", + "@agg": "count", "@of": "ConsignmentHistory.id", "@via": "Consignment.consignmentHistory", "@segment": "live", "@filter": { statusId: { eq: { field: "statusId" } } }, } }] } }, ])); @@ -204,7 +204,7 @@ describe("origin-segment — @segment on origin.aggregate and origin.first", () test("a segment the related entity does not declare is refused", async () => { const errors = await errorsOf(view("NoSeg", [ { "field.long": { name: "live", children: [{ "origin.aggregate": { - "@agg": "count", "@of": "CaseHistory.id", "@via": "Case.caseHistory", "@segment": "dead", + "@agg": "count", "@of": "ConsignmentHistory.id", "@via": "Consignment.consignmentHistory", "@segment": "dead", } }] } }, ])); expect(errors.some((e) => e.startsWith("ERR_INVALID_ORIGIN") && e.includes('@segment "dead"'))).toBe(true); diff --git a/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts b/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts index 24f6eee3cd..9ed099bb33 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tph-scope.test.ts @@ -15,7 +15,7 @@ const ENTITIES = [ { "object.entity": { name: "Authorization", "@discriminator": "type", children: [ { "source.rdb": { "@table": "authorizations" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "type", "@required": true, "@values": ["Coupon", "Prior", "Medical", "Pharmacy"], "@intValueMap": { Coupon: 1, Prior: 2, Medical: 3, Pharmacy: 4 } } }, + { "field.enum": { name: "type", "@required": true, "@values": ["Coupon", "Permit", "Ground", "Air"], "@intValueMap": { Coupon: 1, Permit: 2, Ground: 3, Air: 4 } } }, { "field.string": { name: "code" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, @@ -24,11 +24,11 @@ const ENTITIES = [ { "identity.reference": { name: "couponCard", "@fields": "couponCardId", "@references": "CouponCard" } }, ] } }, // An abstract level between the base and two concrete subtypes: its rows are both subtypes'. - { "object.entity": { name: "BenefitAuthorization", extends: "Authorization", abstract: true, children: [ - { "field.string": { name: "payer" } }, + { "object.entity": { name: "CarrierAuthorization", extends: "Authorization", abstract: true, children: [ + { "field.string": { name: "carrier" } }, ] } }, - { "object.entity": { name: "MedicalAuthorization", extends: "BenefitAuthorization", "@discriminatorValue": "Medical", children: [] } }, - { "object.entity": { name: "PharmacyAuthorization", extends: "BenefitAuthorization", "@discriminatorValue": "Pharmacy", children: [] } }, + { "object.entity": { name: "GroundAuthorization", extends: "CarrierAuthorization", "@discriminatorValue": "Ground", children: [] } }, + { "object.entity": { name: "AirAuthorization", extends: "CarrierAuthorization", "@discriminatorValue": "Air", children: [] } }, ]; const model = (projections: unknown[]) => ({ "metadata.root": { package: "acme", children: [...ENTITIES, ...projections] } }); @@ -65,12 +65,12 @@ describe("TPH-scope — a view over a TPH subtype carries its discriminator", () }); test("an abstract intermediate level reads every concrete subtype beneath it", async () => { - const sql = await viewSql([{ "object.projection": { name: "BenefitAuthView", children: [ - { "source.rdb": { "@kind": "view", "@table": "v_benefit_auth" } }, - { "field.long": { name: "id", extends: "BenefitAuthorization.id" } }, - { "field.string": { name: "payer", extends: "BenefitAuthorization.payer" } }, - { "identity.primary": { name: "id", extends: "BenefitAuthorization.id" } }, + const sql = await viewSql([{ "object.projection": { name: "CarrierAuthView", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_carrier_auth" } }, + { "field.long": { name: "id", extends: "CarrierAuthorization.id" } }, + { "field.string": { name: "carrier", extends: "CarrierAuthorization.carrier" } }, + { "identity.primary": { name: "id", extends: "CarrierAuthorization.id" } }, ] } }]); - expect(sql).toContain("WHERE b.type IN (3, 4)"); + expect(sql).toContain("WHERE c.type IN (3, 4)"); }); }); diff --git a/server/typescript/packages/codegen-ts/test/projection/view-cast.test.ts b/server/typescript/packages/codegen-ts/test/projection/view-cast.test.ts index c9e93da094..a1241a87cb 100644 --- a/server/typescript/packages/codegen-ts/test/projection/view-cast.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/view-cast.test.ts @@ -12,22 +12,22 @@ const MODEL = { "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Physician", children: [ - { "source.rdb": { "@table": "physicians" } }, + { "object.entity": { name: "Pilot", children: [ + { "source.rdb": { "@table": "pilots" } }, { "field.long": { name: "id" } }, { "field.string": { name: "externalReferenceId", "@maxLength": 100 } }, { "field.int": { name: "rank" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, - { "object.projection": { name: "PhysicianExtract", children: [ - { "source.rdb": { "@kind": "view", "@table": "v_physician_extract" } }, - { "field.long": { name: "id", extends: "Physician.id" } }, + { "object.projection": { name: "PilotExtract", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_pilot_extract" } }, + { "field.long": { name: "id", extends: "Pilot.id" } }, { "field.int": { name: "locationType", children: [{ "origin.computed": { "@expr": { value: null } } }] } }, { "field.string": { name: "territoryName", children: [{ "origin.computed": { "@expr": { value: null } } }] } }, { "field.timestamp": { name: "removedAt", children: [{ "origin.computed": { "@expr": { value: null } } }] } }, - { "field.string": { name: "externalRef", children: [{ "origin.passthrough": { "@from": "Physician.externalReferenceId", "@convert": true } }] } }, - { "field.long": { name: "rankWide", children: [{ "origin.passthrough": { "@from": "Physician.rank", "@convert": true } }] } }, - { "identity.primary": { name: "id", extends: "Physician.id" } }, + { "field.string": { name: "externalRef", children: [{ "origin.passthrough": { "@from": "Pilot.externalReferenceId", "@convert": true } }] } }, + { "field.long": { name: "rankWide", children: [{ "origin.passthrough": { "@from": "Pilot.rank", "@convert": true } }] } }, + { "identity.primary": { name: "id", extends: "Pilot.id" } }, ] } }, ], }, diff --git a/server/typescript/packages/metadata/src/core/object/effective-projection-filter.ts b/server/typescript/packages/metadata/src/core/object/effective-projection-filter.ts index 7399392ec1..f5157c13a6 100644 --- a/server/typescript/packages/metadata/src/core/object/effective-projection-filter.ts +++ b/server/typescript/packages/metadata/src/core/object/effective-projection-filter.ts @@ -1,6 +1,6 @@ // rc.19 (C1) — a projection's EFFECTIVE row scope. `@filter` composes down an `extends` chain // rather than overriding: a projection that extends a filtered projection keeps the base's row -// scope (a consent or HIPAA gate on an abstract base must survive in every extender). Every +// scope (an access gate on an abstract base must survive in every extender). Every // level's own `@filter`, root-most first, ANDed. One reader for the loaders and the view lowering. import type { MetaData } from "../../shared/meta-data.js"; diff --git a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts index 50c0974f30..a19dd8969c 100644 --- a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts @@ -150,7 +150,7 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "csharp", "typescript" ], - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", @@ -196,7 +196,7 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "name": "filter", "min": 0, "max": 1, - "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." + "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", @@ -241,7 +241,7 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "csharp", "typescript" ], - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", @@ -323,7 +323,7 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "csharp", "typescript" ], - "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." + "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", diff --git a/server/typescript/packages/metadata/src/core/relationship/filter-path.ts b/server/typescript/packages/metadata/src/core/relationship/filter-path.ts index d2f3f76117..beacf66eab 100644 --- a/server/typescript/packages/metadata/src/core/relationship/filter-path.ts +++ b/server/typescript/packages/metadata/src/core/relationship/filter-path.ts @@ -1,6 +1,6 @@ // G7 (joined half) and entity-derived — a projection @filter key may be a PATH: to-one hops // from the base entity, then a field of the entity they reach (`caseId.status`, -// `caseId.patientId.hasActiveHipaaConsent`). A hop is an identity.reference (a forward FK) or +// `orderId.customerId.hasActiveMembership`). A hop is an identity.reference (a forward FK) or // a relationship with @cardinality one, named as an origin @via names its hops. A to-many hop // would multiply the base rows, so it is refused. One resolver for the loaders and the view // lowering. diff --git a/server/typescript/packages/metadata/src/core/relationship/find-reference.ts b/server/typescript/packages/metadata/src/core/relationship/find-reference.ts index 5db51a715c..03c781916f 100644 --- a/server/typescript/packages/metadata/src/core/relationship/find-reference.ts +++ b/server/typescript/packages/metadata/src/core/relationship/find-reference.ts @@ -72,8 +72,8 @@ export function findReferenceBetween( /** * Phase 5 bug R-walk — the name a `@via` hop takes when it walks the REVERSE of an * identity.reference, from the referenced entity back to the one that declares it: - * the holder's collection name, lowerFirst() — its @collectionName, else the project's pluralizer — `consents` for - * `Consent`, so `Patient.consents` walks Consent.patient backwards. One rule for every port. + * the holder's collection name, lowerFirst() — its @collectionName, else the project's pluralizer — `contracts` for + * `Contract`, so `Player.contracts` walks Contract.player backwards. One rule for every port. */ export function reverseHopName(holder: MetaObject): string { // rc.19 (R57): the holder's collection name — its @collectionName, else the project's pluralizer. diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index a317779277..c3bbb3d41c 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -787,8 +787,8 @@ function _validateViaPath( const rel = _findRelationship(currentObj, relName) ?? _findReference(currentObj, relName); if (!rel) { // R-walk: a hop may walk an identity.reference BACKWARDS, from the entity it targets to the - // entity that declares it, named by that entity's collection name (`Patient.consents` for - // Consent.patient). A declared relationship or reference of the same name wins (above). + // entity that declares it, named by that entity's collection name (`Player.contracts` for + // Contract.player). A declared relationship or reference of the same name wins (above). const reversed = findReverseReferenceHops(currentObj as MetaObject, relName, isMetaRoot(root) ? root.objects() : []); if (reversed.length === 1) { validSegments.push(relName); diff --git a/server/typescript/packages/metadata/test/port-scoped-attr.test.ts b/server/typescript/packages/metadata/test/port-scoped-attr.test.ts index 6a1398337d..0122f5620c 100644 --- a/server/typescript/packages/metadata/test/port-scoped-attr.test.ts +++ b/server/typescript/packages/metadata/test/port-scoped-attr.test.ts @@ -10,8 +10,8 @@ import { buildVocabularyCatalog } from "../src/vocabulary-catalog.js"; function model(attr: string): string { return JSON.stringify(JSON.parse(`{ "metadata.root": { "package": "acme", "children": [ - { "object.entity": { "name": "Diagnosis", ${attr} "children": [ - { "source.rdb": { "@table": "diagnoses" } }, + { "object.entity": { "name": "Analysis", ${attr} "children": [ + { "source.rdb": { "@table": "analyses" } }, { "field.long": { "name": "id" } }, { "identity.primary": { "@fields": "id" } } ] } } @@ -25,15 +25,15 @@ async function codes(json: string): Promise { describe("a C#-only attribute (R40)", () => { test("loads under the strict loader", async () => { - expect(await codes(model(`"@dbSetName": "Diagnosis",`))).toEqual([]); + expect(await codes(model(`"@dbSetName": "Analysis",`))).toEqual([]); }); test("is type-checked: a list is not a DbSet name", async () => { - expect(await codes(model(`"@dbSetName": ["Diagnosis"],`))).not.toEqual([]); + expect(await codes(model(`"@dbSetName": ["Analysis"],`))).not.toEqual([]); }); test("an attribute the registry does not carry still fails", async () => { - expect(await codes(model(`"@dbSetNameX": "Diagnosis",`))).toContain("ERR_UNKNOWN_ATTR"); + expect(await codes(model(`"@dbSetNameX": "Analysis",`))).toContain("ERR_UNKNOWN_ATTR"); }); test("the vocabulary names the ports that act on it", async () => { diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts index 9324b15aca..2522d471fe 100644 --- a/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts +++ b/server/typescript/packages/migrate-ts/test/expected-schema-field-object-storage.test.ts @@ -99,8 +99,8 @@ describe("buildExpectedSchema — field.object @storage", () => { { "object.value": { name: "ContactInfo", children: [ { "field.string": { name: "email" } }, ]}}, - { "object.entity": { name: "Patient", children: [ - { "source.rdb": { "@table": "patients" } }, + { "object.entity": { name: "Player", children: [ + { "source.rdb": { "@table": "players" } }, { "field.long": { name: "id" } }, { "field.object": { name: "contactInfos", isArray: true, "@objectRef": "ContactInfo", "@storage": "jsonb" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, @@ -109,8 +109,8 @@ describe("buildExpectedSchema — field.object @storage", () => { }, }); const snap = buildExpectedSchema(root, { dialect: "postgres" }); - const patients = snap.tables.find((t) => t.name === "patients")!; - const contactInfos = patients.columns.find((c) => c.name === "contact_infos"); + const players = snap.tables.find((t) => t.name === "players")!; + const contactInfos = players.columns.find((c) => c.name === "contact_infos"); expect(contactInfos?.sqlType.kind).toBe("json"); }); diff --git a/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts b/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts index 617307d718..db2f98ac14 100644 --- a/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts +++ b/server/typescript/packages/migrate-ts/test/expected-schema-fk-refcolumn-override.test.ts @@ -30,11 +30,11 @@ function model(clientIdField: Record): string { }, { "object.entity": { - "name": "Patient", + "name": "Player", "children": [ { "field.uuid": { "name": "id" } }, { "field.uuid": { "name": "clientId", "@column": "ClientId" } }, - { "source.rdb": { "name": "src", "@table": "Patients" } }, + { "source.rdb": { "name": "src", "@table": "Players" } }, { "identity.primary": { "name": "pk", "@fields": ["id"] } }, { "identity.reference": { @@ -51,9 +51,9 @@ function model(clientIdField: Record): string { }); } -function patientFk(root: MetaData) { +function playerFk(root: MetaData) { const snapshot = buildExpectedSchema(root, { dialect: "postgres" }); - const table = snapshot.tables.find((t) => t.name === "Patients"); + const table = snapshot.tables.find((t) => t.name === "Players"); expect(table).toBeDefined(); expect(table!.foreignKeys).toHaveLength(1); return table!.foreignKeys[0]!; @@ -62,7 +62,7 @@ function patientFk(root: MetaData) { describe("buildExpectedSchema — FK refColumns resolve the target PK's @column override", () => { test("target PK field with @column override → refColumns uses the physical name", async () => { const root = await loadJson(model({ "name": "id", "@column": "Id" })); - const fk = patientFk(root); + const fk = playerFk(root); expect(fk.columns).toEqual(["ClientId"]); expect(fk.refTable).toBe("Clients"); expect(fk.refColumns).toEqual(["Id"]); @@ -70,7 +70,7 @@ describe("buildExpectedSchema — FK refColumns resolve the target PK's @column test("target PK field without @column override → refColumns keeps the field name", async () => { const root = await loadJson(model({ "name": "id" })); - const fk = patientFk(root); + const fk = playerFk(root); expect(fk.refColumns).toEqual(["id"]); }); }); diff --git a/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts b/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts index 838e301024..5dd9f6aa3b 100644 --- a/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/sqlite-rebuild-down-reverses.test.ts @@ -40,7 +40,7 @@ const AFTER: Shape = { kindColumn: "kind", microchip: true, nameRequired: false function model(s: Shape): string { return JSON.stringify({ "metadata.root": { - package: "clinic", + package: "depot", children: [ { "object.entity": { diff --git a/site-reference/types/object.html b/site-reference/types/object.html index f430768794..ae9358eff5 100644 --- a/site-reference/types/object.html +++ b/site-reference/types/object.html @@ -119,7 +119,7 @@

    object.entity

    - + @@ -206,7 +206,7 @@

    object.projection

    - + @@ -224,7 +224,7 @@

    object.projection

    - + @@ -314,7 +314,7 @@

    object.report

    - + diff --git a/spec/metamodel/object.json b/spec/metamodel/object.json index 7dbadfcd07..fbae6bec09 100644 --- a/spec/metamodel/object.json +++ b/spec/metamodel/object.json @@ -31,7 +31,7 @@ { "type": "segment", "subType": "*", "name": "*", "min": 0, "max": null }, { "type": "attr", "subType": "string", "name": "discriminator", "min": 0, "max": 1, "description": "FR-014: names the field on this entity (resolvable via extends:) that holds the subtype-discriminator value. Subtypes of this entity declare @discriminatorValue to bind their rows to a discriminator value. The discriminator field itself is an ordinary field declaration (typically field.enum or field.int / field.string)." }, { "type": "attr", "subType": "string", "name": "discriminatorValue", "min": 0, "max": 1, "description": "FR-014: on a subtype of an entity with @discriminator — the value that identifies rows of this subtype in the shared discriminator field. Wire form is always a string; the underlying field's subtype (enum / int / string) controls codegen + storage coercion. Required on every concrete subtype of a discriminated entity." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] }, @@ -54,12 +54,12 @@ "whenToUse": "You need a derived, read-only view over entities — a report, summary, or joined/aggregated read model. Declare it (with origin.* children) instead of hand-writing the SELECT/joins; it stays read-only and regenerates.", "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ - { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] }, @@ -76,7 +76,7 @@ { "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional segment of @from scoping the rows." }, { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope over @from's fields; may use relative-date values." }, { "type": "attr", "subType": "string", "name": "spine", "min": 0, "max": 1, "description": "Optional to-one path from @from to the entity whose rows supply the report's rows (e.g. 'Purchase.program'), written like a dimension's @via. With it the report has one row per distinct dimension tuple among THAT entity's rows, including the ones no row of @from refers to: a count there is 0 and any other measure is null unless it declares @default. Every listed dimension must be reached through this path. @segment and @filter still scope the rows of @from and never remove a row. A row of @from whose reference is null or matches nothing is in no row of the report." }, - { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, + { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] } From d02f59535f61b11d461f2d11c2157fbf87edf074 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 21:22:24 -0500 Subject: [PATCH 218/267] docs(python): the discriminator path example keeps a multi-word value Co-Authored-By: Claude Opus 5.5 --- server/python/src/metaobjects/codegen/generators/tph_plan.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/python/src/metaobjects/codegen/generators/tph_plan.py b/server/python/src/metaobjects/codegen/generators/tph_plan.py index ef57c886f1..b7223d451b 100644 --- a/server/python/src/metaobjects/codegen/generators/tph_plan.py +++ b/server/python/src/metaobjects/codegen/generators/tph_plan.py @@ -7,7 +7,7 @@ TPH-aware generator reads, so the route-segment rule and subtype set never drift. The per-subtype REST route segment is the ``@discriminatorValue`` lowercased -(``"Bridge"`` → ``bridge``, ``"Permit"`` → ``permit``) — derived in exactly +(``"Bridge"`` → ``bridge``, ``"BulkPermit"`` → ``bulkpermit``) — derived in exactly one place (:func:`route_segment`). """ from __future__ import annotations From f773bac39f6593ce787c43422883843e42dcb8db Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 21:51:02 -0500 Subject: [PATCH 219/267] chore(tests): the package-binding test and spec use a neutral adopter's names The real-config test and its spec named an adopter's package map; the all-caps-prefixed enum namespaces become EDI*, the export one a warehouse feed, the cases package orders. The casing quirks the test pins are kept. Co-Authored-By: Claude Opus 5.5 --- ...ross-port-package-binding-config-design.md | 36 +++++++++---------- .../PackageBindingResolverTests.cs | 6 ++-- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md index 202d41f579..c5580bdfc7 100644 --- a/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md +++ b/docs/superpowers/specs/2026-06-08-fr-025-cross-port-package-binding-config-design.md @@ -7,7 +7,7 @@ ## Why this doc exists -FR-019 introduced the C# `GenConfig.PackageNamespaces: Dictionary` map and a single `ProvidedEnumNamespace` fallback **scoped to `@provided` enums only**. That map is exactly the right primitive — bind a metadata package (`acme::cases`, `acme::domain::dataEnums::authorizations`) to a per-port output identity (a C# namespace, a TS module specifier, a Java package, …). Three gaps in the current shape: +FR-019 introduced the C# `GenConfig.PackageNamespaces: Dictionary` map and a single `ProvidedEnumNamespace` fallback **scoped to `@provided` enums only**. That map is exactly the right primitive — bind a metadata package (`acme::orders`, `acme::domain::dataEnums::authorizations`) to a per-port output identity (a C# namespace, a TS module specifier, a Java package, …). Three gaps in the current shape: 1. **It's only wired for `@provided` enums.** The same primitive should govern where entities and value-objects land in each port's emitted output. The pattern is identical; only the consumer differs. 2. **Only the C# port has it.** TS has a single `providedEnumModule` string with no map; Java and Python have nothing. Cross-port symmetry is missing. @@ -30,11 +30,11 @@ Each language has its own term for "where this lands." The cross-port config use | Port | Section | Field | Example value | |---|---|---|---| -| **C#** | `csharp:` | `namespace` | `Acme.Domain.Entities.Cases` | -| **Java** | `java:` | `package` | `com.acme.app.cases` | -| **Kotlin** | `kotlin:` | `package` | `com.acme.app.cases` | -| **TS** | `typescript:` | `module` | `@acme/app/cases` | -| **Python** | `python:` | `module` | `acme.app.cases` | +| **C#** | `csharp:` | `namespace` | `Acme.Domain.Entities.Orders` | +| **Java** | `java:` | `package` | `com.acme.app.orders` | +| **Kotlin** | `kotlin:` | `package` | `com.acme.app.orders` | +| **TS** | `typescript:` | `module` | `@acme/app/orders` | +| **Python** | `python:` | `module` | `acme.app.orders` | Rationale: a Java developer reading `java: { package: ... }` sees their language's term, not `javaPackage`. The port section already carries the language identity; doubling it as a key prefix is redundant. The retired `@csEnumType` attr was wrong for the *opposite* reason — it carried language vocabulary into metadata where it didn't belong. @@ -93,14 +93,14 @@ Resolution is **per named type**, not per package. The resolver receives `(metad | 5 | Join segments by `convention.separator` (`.`) | `UsersAccess` | | 6 | Prepend `convention.prepend` + `convention.separator` | `Acme.Domain.Entities.UsersAccess` | -Multi-segment example, `acme::cases::custom-properties`: +Multi-segment example, `acme::orders::custom-properties`: | Step | Result | |---|---| -| Strip `acme::` | `cases::custom-properties` | -| Split by `::` | `["cases", "custom-properties"]` | -| PascalCase each | `["Cases", "CustomProperties"]` | -| Join by `.` | `Cases.CustomProperties` | -| Prepend base | `Acme.Domain.Entities.Cases.CustomProperties` | +| Strip `acme::` | `orders::custom-properties` | +| Split by `::` | `["orders", "custom-properties"]` | +| PascalCase each | `["Orders", "CustomProperties"]` | +| Join by `.` | `Orders.CustomProperties` | +| Prepend base | `Acme.Domain.Entities.Orders.CustomProperties` | The metadata separator (`::`) is **never** configurable — it's part of the metaobjects spec. The convention rule's `separator` is the per-port output joiner: `.` for C#, `/` for TS module paths, `.` for Java packages, etc. @@ -200,14 +200,14 @@ csharp: "acme::authorizations::AuthorizationStatus": "Acme.Domain.DataEnums.Authorizations" "acme::authorizations::CouponCardStatus": "Acme.Domain.DataEnums.CouponCards" # ... 6 more Coupon* enums in acme::authorizations - "acme::integrations::DataExportRunStatusEnum": "Acme.Domain.DataEnums.DataExportIntegration" - "acme::integrations::SPFileType": "Acme.Domain.DataEnums.SPIntegration" - "acme::integrations::SPProcessLogStatus": "Acme.Domain.DataEnums.SPIntegration" + "acme::integrations::WarehouseFeedRunStatusEnum": "Acme.Domain.DataEnums.WarehouseFeed" + "acme::integrations::EDIFileType": "Acme.Domain.DataEnums.EDIIntegration" + "acme::integrations::EDIProcessLogStatus": "Acme.Domain.DataEnums.EDIIntegration" unmappedStrategy: error ``` Resolves: -- `acme::cases` → convention → `Acme.Domain.Entities.Cases` +- `acme::orders` → convention → `Acme.Domain.Entities.Orders` - `acme::users-access` → convention → `Acme.Domain.Entities.UsersAccess` - `acme::reporting` → override → `Acme.Domain.Entities.ReportEntities` - `acme::players::Gender` (provided enum) → `providedEnumNamespace` → `Acme.Domain.DataEnums.Gender` @@ -247,7 +247,7 @@ typescript: ``` Resolves: -- `acme::cases` → `@acme/app/cases` +- `acme::orders` → `@acme/app/orders` - `acme::users-access` → `@acme/app/users-access` **Hypothetical Java adopter:** @@ -263,7 +263,7 @@ java: ``` Resolves: -- `acme::cases` → `com.acme.app.cases` +- `acme::orders` → `com.acme.app.orders` - `acme::usersaccess` → `com.acme.app.usersaccess` ## Per-port codegen surface diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs index eeb51a6ea1..1c02f4a725 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageBindingResolverTests.cs @@ -257,7 +257,7 @@ public void TryResolve_returns_null_when_nothing_matches_for_provided_enum_use_c } [Fact] - public void Real_P3_config_resolves_all_18_domains_correctly() + public void Adopter_style_config_resolves_all_domains_correctly() { var cfg = CfgWithDefaults() with { @@ -275,8 +275,8 @@ public void Real_P3_config_resolves_all_18_domains_correctly() ["acme::domain::dataEnums"] = "Acme.Domain.DataEnums", ["acme::domain::dataEnums::authorizations"] = "Acme.Domain.DataEnums.Authorizations", ["acme::domain::dataEnums::couponCards"] = "Acme.Domain.DataEnums.CouponCards", - ["acme::domain::dataEnums::dataExportIntegration"] = "Acme.Domain.DataEnums.DataExportIntegration", - ["acme::domain::dataEnums::spIntegration"] = "Acme.Domain.DataEnums.SPIntegration", + ["acme::domain::dataEnums::warehouseFeed"] = "Acme.Domain.DataEnums.WarehouseFeed", + ["acme::domain::dataEnums::ediIntegration"] = "Acme.Domain.DataEnums.EDIIntegration", }, }; From b6ec4814ff52237174cdb506b734e4f84fd93b02 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 21:53:15 -0500 Subject: [PATCH 220/267] chore(fixtures): the remaining case-shaped models are consignments The Case entity (caseId, caseStatus, a case number) in the view and parameter-ref conformance fixtures, their tests, the comments naming a caseId path, two specs and a CHANGELOG line becomes Consignment, as the other renamed models already are. Meaning unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++-- ...5-28-fr-015-source-parameter-ref-design.md | 12 +++++----- ...-024-entity-surfaces-projections-design.md | 6 ++--- .../input/meta.views.json | 12 +++++----- .../expected-errors.json | 2 +- .../input/meta.demo.json | 6 ++--- .../input/meta.tasks.json | 10 ++++---- .../expected.json | 16 ++++++------- .../input/meta.views.json | 16 ++++++------- .../expected.json | 2 +- .../input/meta.demo.json | 2 +- .../expected.json | 8 +++---- .../input/meta.demo.json | 8 +++---- .../expected.json | 14 +++++------ .../input/meta.tasks.json | 10 ++++---- .../source-db-table-with-schema/expected.json | 6 ++--- .../input/meta.demo.json | 6 ++--- .../Fr015CodegenTests.cs | 16 ++++++------- .../MetaObjects/Loader/ValidationPasses.cs | 2 +- server/csharp/MetaObjects/Meta/FilterPath.cs | 2 +- .../migrate-projection-kinds.test.ts | 2 +- .../codegen-ts/src/templates/callable-file.ts | 2 +- .../test/golden/api-docs-accuracy.test.ts | 4 ++-- .../build-projection-views-kinds.test.ts | 2 +- .../projection/filter-joined-path.test.ts | 24 +++++++++---------- .../test/reference-byte-identical.test.ts | 4 ++-- .../test/templates/callable-file.test.ts | 4 ++-- .../src/core/relationship/filter-path.ts | 2 +- .../metadata/src/loader/validation-passes.ts | 2 +- .../test/fr015-source-parameter-ref.test.ts | 2 +- 30 files changed, 104 insertions(+), 104 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80afa8716d..a64324c04a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -894,8 +894,8 @@ vocabulary; upgrade every port together. `fixtures/conformance/projection-filter-unprojected-base-field`. - **A projection `@filter` reads a joined field the view does not output** (rc.19 Phase 5, bug G7, joined half). A filter key may be a path of to-one hops from the base entity, named as an - origin's `@via` names them, then a field of the entity reached: `@filter: { "caseId.status": - "open" }` joins `cases` (sharing a join an origin already walks) and lowers to + origin's `@via` names them, then a field of the entity reached: `@filter: { "consignmentId.status": + "open" }` joins `consignments` (sharing a join an origin already walks) and lowers to `WHERE c.status = 'open'`. A to-many hop is refused (`ERR_BAD_ATTR_FILTER`): it would multiply the base rows. Pinned by `fixtures/conformance/projection-filter-joined-path` and `error-projection-filter-path-to-many`. diff --git a/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md b/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md index e1b60b40e0..0b4b1aa755 100644 --- a/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md @@ -33,10 +33,10 @@ Add one attribute, `@parameterRef`, to `source.rdb`'s attribute schema in `persi "name": "PhaseSummaryArgs", "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true, "children": [ - { "origin.passthrough": { "@from": "Case.id" } } + { "origin.passthrough": { "@from": "Consignment.id" } } ] }}, { "field.timestamp": { "name": "asOfDate" } } @@ -135,10 +135,10 @@ Some stored procedures (especially in legacy SQL Server / Oracle codebases) have | Port | Emission for a `source.rdb @kind: "storedProc" @parameterRef: "PhaseSummaryArgs"` | |---|---| | **TypeScript** | Method on the generated repo / service: `getPhaseSummaryPerCase(args: PhaseSummaryArgs): Promise`. The `PhaseSummaryArgs` type comes from the value-object's TS codegen. Drizzle: `sql.raw` wrapper helper. | -| **Java** | Spring repo method with `@Query(value = "{ call fn_get_phase_summary_per_case(:caseId, :asOfDate) }", nativeQuery = true)` and parameter binding driven by `PhaseSummaryArgs` field order. | +| **Java** | Spring repo method with `@Query(value = "{ call fn_get_phase_summary_per_case(:consignmentId, :asOfDate) }", nativeQuery = true)` and parameter binding driven by `PhaseSummaryArgs` field order. | | **Kotlin** | Exposed `transaction { ... }` block with stored-function call wrapper; typed arguments via the `PhaseSummaryArgs` data class. | -| **C#** | EF Core: `context.PhaseSummaryPerCase.FromSqlInterpolated($"SELECT * FROM analytics.fn_get_phase_summary_per_case({args.CaseId}, {args.AsOfDate})")` or a static helper on a `Procedures` partial. | -| **Python** | SQLAlchemy: `session.execute(text("SELECT * FROM analytics.fn_get_phase_summary_per_case(:case_id, :as_of_date)"), args.model_dump())`. Pydantic `PhaseSummaryArgs` validates inputs at call site. | +| **C#** | EF Core: `context.PhaseSummaryPerCase.FromSqlInterpolated($"SELECT * FROM analytics.fn_get_phase_summary_per_case({args.ConsignmentId}, {args.AsOfDate})")` or a static helper on a `Procedures` partial. | +| **Python** | SQLAlchemy: `session.execute(text("SELECT * FROM analytics.fn_get_phase_summary_per_case(:consignment_id, :as_of_date)"), args.model_dump())`. Pydantic `PhaseSummaryArgs` validates inputs at call site. | Every port emits the `object.value` shape (`PhaseSummaryArgs`) as a native type per its existing object.value codegen path. **No new codegen mechanics are required** — both the value-object and the source-with-parameter-ref reuse already-shipped per-port pipelines. @@ -162,7 +162,7 @@ Under `fixtures/conformance/`: 1. `parameter-ref-on-stored-proc/` — full shape: `source.rdb @kind: "storedProc" @parameterRef + object.value with 2 fields + return columns`. 2. `parameter-ref-on-table-function/` — same shape with `@kind: "tableFunction"`. -3. `parameter-ref-with-origin-passthrough/` — at least one parameter field uses `origin.passthrough @from: "Case.id"`; loader's effective-tree resolution links the parameter type to the source field's type. +3. `parameter-ref-with-origin-passthrough/` — at least one parameter field uses `origin.passthrough @from: "Consignment.id"`; loader's effective-tree resolution links the parameter type to the source field's type. 4. `parameter-ref-shared-across-procs/` — two `source.rdb` instances on different entities both reference the same `object.value`. Confirms reusability. 5. `parameter-ref-optional-parameter/` — one required, one optional parameter (`@required: false` on a field child); call signature reflects optionality per port. 6. `parameter-ref-no-args/` — `@kind: "storedProc"` with `@parameterRef` omitted (a zero-argument procedure). Loader accepts; codegen emits a no-arg method. diff --git a/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md b/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md index b591be58bc..cf6430888f 100644 --- a/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md +++ b/docs/superpowers/specs/2026-06-12-fr-024-entity-surfaces-projections-design.md @@ -127,7 +127,7 @@ This mechanism is **universal**, not projection-specific: column: customer_id }`: shape (type/docs/validators) pulls through; the rename is the own-`@column`; presence in the projection = presence in the inclusive list. - **Value fields** — proc parameters and command inputs whose fields are entity ids: - `field.int: { name: caseId, extends: Case.id }` pulls shape through with **no** + `field.int: { name: consignmentId, extends: Consignment.id }` pulls shape through with **no** identity semantics, **no** population, **no** referential (FK) claim. - **Entity derived fields** — optional shape pull-through alongside the origin (§7). @@ -136,8 +136,8 @@ What every use gets: **load-time drift protection**. Renaming or retyping input that references it — the contract breaks the build, not production. This is a *stronger* gate than verify-time origin resolution: it fires at load. -What it also makes computable: "this parameter is a Case identifier" (the extends -target IS `Case`'s identity field) — doc-gen, FR-022 emission, and future MCP tool +What it also makes computable: "this parameter is a Consignment identifier" (the extends +target IS `Consignment`'s identity field) — doc-gen, FR-022 emission, and future MCP tool schemas derive the semantic with zero new attrs. Inheritance semantics are the existing `extends` semantics: child attrs override diff --git a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json index 48ec4ce7a6..c0bbeedf0e 100644 --- a/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json +++ b/fixtures/conformance/error-origin-computed-case-mixed-types/input/meta.views.json @@ -32,11 +32,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -87,18 +87,18 @@ }, { "object.projection": { - "name": "BadCase", + "name": "BadConsignment", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_badcase" + "@view": "v_badconsignment" } }, { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -136,7 +136,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json index da10f876b2..f0a1bb8e4c 100644 --- a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json +++ b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/expected-errors.json @@ -9,7 +9,7 @@ ], "jsonPath": "$['metadata.root'].children[1]['object.value'].children[0]['field.int'].children[0]['origin.passthrough']", "referrer": "Args::label", - "target": "demo::Case.label" + "target": "demo::Consignment.label" } } ], diff --git a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json index a476074970..1c635c075a 100644 --- a/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json +++ b/fixtures/conformance/error-parameter-ref-passthrough-type-mismatch/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -40,7 +40,7 @@ "children": [ { "origin.passthrough": { - "@from": "demo::Case.label" + "@from": "demo::Consignment.label" } } ] diff --git a/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json b/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json index 1d95da3239..7ccfebeb90 100644 --- a/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json +++ b/fixtures/conformance/error-projection-filter-path-to-many/input/meta.tasks.json @@ -2,8 +2,8 @@ "metadata.root": { "package": "acme::tasks", "children": [ - { "object.entity": { "name": "Case", "children": [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { "name": "Consignment", "children": [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "status" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, @@ -13,11 +13,11 @@ { "source.rdb": { "@table": "tasks" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "title" } }, - { "field.long": { "name": "caseId" } }, + { "field.long": { "name": "consignmentId" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "acme::tasks::Case" } } + { "identity.reference": { "name": "consignmentId", "@fields": "consignmentId", "@references": "acme::tasks::Consignment" } } ] } }, - { "object.projection": { "name": "OpenTasks", "@filter": { "caseId.tasks.title": "x" }, "children": [ + { "object.projection": { "name": "OpenTasks", "@filter": { "consignmentId.tasks.title": "x" }, "children": [ { "source.rdb": { "@kind": "view", "@view": "v_open_tasks" } }, { "field.long": { "name": "id", "extends": "acme::tasks::Task.id" } }, { "field.string": { "name": "title", "extends": "acme::tasks::Task.title" } }, diff --git a/fixtures/conformance/origin-computed-case-over-joined/expected.json b/fixtures/conformance/origin-computed-case-over-joined/expected.json index d411f39af1..6f7e040e8f 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/expected.json +++ b/fixtures/conformance/origin-computed-case-over-joined/expected.json @@ -39,11 +39,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -98,18 +98,18 @@ }, { "object.projection": { - "name": "CaseLabels", + "name": "ConsignmentLabels", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_caselabels" + "@view": "v_consignmentlabels" } }, { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -119,7 +119,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.name", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -132,7 +132,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.displayName", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -249,7 +249,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json index a4ff072c5b..fa0329eddb 100644 --- a/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json +++ b/fixtures/conformance/origin-computed-case-over-joined/input/meta.views.json @@ -37,11 +37,11 @@ }, { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -92,18 +92,18 @@ }, { "object.projection": { - "name": "CaseLabels", + "name": "ConsignmentLabels", "children": [ { "source.rdb": { "@kind": "view", - "@view": "v_caselabels" + "@view": "v_consignmentlabels" } }, { "field.long": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } }, { @@ -113,7 +113,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.name", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -126,7 +126,7 @@ { "origin.passthrough": { "@from": "acme::views::Status.displayName", - "@via": "acme::views::Case.statusId" + "@via": "acme::views::Consignment.statusId" } } ] @@ -243,7 +243,7 @@ { "identity.primary": { "name": "id", - "extends": "acme::views::Case.id" + "extends": "acme::views::Consignment.id" } } ] diff --git a/fixtures/conformance/parameter-ref-on-stored-proc/expected.json b/fixtures/conformance/parameter-ref-on-stored-proc/expected.json index bd411f6965..a0740035e3 100644 --- a/fixtures/conformance/parameter-ref-on-stored-proc/expected.json +++ b/fixtures/conformance/parameter-ref-on-stored-proc/expected.json @@ -8,7 +8,7 @@ "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, diff --git a/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json b/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json index faef10bce8..98bf09ae8c 100644 --- a/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json +++ b/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json @@ -8,7 +8,7 @@ "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true } }, diff --git a/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json b/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json index dd527e5074..531884c187 100644 --- a/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json +++ b/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -33,12 +33,12 @@ "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true, "children": [ { "origin.passthrough": { - "@from": "demo::Case.id" + "@from": "demo::Consignment.id" } } ] diff --git a/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json b/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json index afaa447fd7..2c8ddae04f 100644 --- a/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json +++ b/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -31,12 +31,12 @@ "children": [ { "field.int": { - "name": "caseId", + "name": "consignmentId", "@required": true, "children": [ { "origin.passthrough": { - "@from": "demo::Case.id" + "@from": "demo::Consignment.id" } } ] diff --git a/fixtures/conformance/projection-filter-joined-path/expected.json b/fixtures/conformance/projection-filter-joined-path/expected.json index 7122594bb5..6e7f65f1a1 100644 --- a/fixtures/conformance/projection-filter-joined-path/expected.json +++ b/fixtures/conformance/projection-filter-joined-path/expected.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "cases" + "@table": "consignments" } }, { @@ -60,7 +60,7 @@ }, { "field.long": { - "name": "caseId" + "name": "consignmentId" } }, { @@ -73,11 +73,11 @@ }, { "identity.reference": { - "name": "caseId", + "name": "consignmentId", "@fields": [ - "caseId" + "consignmentId" ], - "@references": "acme::tasks::Case" + "@references": "acme::tasks::Consignment" } } ] @@ -87,7 +87,7 @@ "object.projection": { "name": "OpenTasks", "@filter": { - "caseId.status": { + "consignmentId.status": { "eq": "open" } }, diff --git a/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json b/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json index e6bf337e67..9ac298a913 100644 --- a/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json +++ b/fixtures/conformance/projection-filter-joined-path/input/meta.tasks.json @@ -2,8 +2,8 @@ "metadata.root": { "package": "acme::tasks", "children": [ - { "object.entity": { "name": "Case", "children": [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { "name": "Consignment", "children": [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "status" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, @@ -13,11 +13,11 @@ { "source.rdb": { "@table": "tasks" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "title" } }, - { "field.long": { "name": "caseId" } }, + { "field.long": { "name": "consignmentId" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, - { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "acme::tasks::Case" } } + { "identity.reference": { "name": "consignmentId", "@fields": "consignmentId", "@references": "acme::tasks::Consignment" } } ] } }, - { "object.projection": { "name": "OpenTasks", "@filter": { "caseId.status": "open" }, "children": [ + { "object.projection": { "name": "OpenTasks", "@filter": { "consignmentId.status": "open" }, "children": [ { "source.rdb": { "@kind": "view", "@view": "v_open_tasks" } }, { "field.long": { "name": "id", "extends": "acme::tasks::Task.id" } }, { "field.string": { "name": "title", "extends": "acme::tasks::Task.title" } }, diff --git a/fixtures/conformance/source-db-table-with-schema/expected.json b/fixtures/conformance/source-db-table-with-schema/expected.json index 229c73f7e6..94b0202d89 100644 --- a/fixtures/conformance/source-db-table-with-schema/expected.json +++ b/fixtures/conformance/source-db-table-with-schema/expected.json @@ -4,12 +4,12 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { "@schema": "public", - "@table": "Cases" + "@table": "Consignments" } }, { @@ -19,7 +19,7 @@ }, { "field.string": { - "name": "caseNumber" + "name": "consignmentNumber" } }, { diff --git a/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json b/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json index 002f40dea6..97cb736428 100644 --- a/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json +++ b/fixtures/conformance/source-db-table-with-schema/input/meta.demo.json @@ -4,11 +4,11 @@ "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ { "source.rdb": { - "@table": "Cases", + "@table": "Consignments", "@schema": "public" } }, @@ -19,7 +19,7 @@ }, { "field.string": { - "name": "caseNumber" + "name": "consignmentNumber" } }, { diff --git a/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs index a7f58b5868..1eaa02e029 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs @@ -6,14 +6,14 @@ // // public static Task> Call(global::Acme.Generated.AppDbContext db, global::Acme.Analytics.PhaseSummaryArgs args) // => db.Set() -// .FromSqlInterpolated($"SELECT * FROM analytics.fn_phase_summary({args.CaseId}, {args.AsOfDate})") +// .FromSqlInterpolated($"SELECT * FROM analytics.fn_phase_summary({args.ConsignmentId}, {args.AsOfDate})") // .ToListAsync()...; // // and, when it IS (the default suite — §A6 / no-magic-physical-names), references the // procedure's name through FromSqlRaw, because an interpolation hole is a PARAMETER and an // identifier cannot be one: // -// .FromSqlRaw("SELECT * FROM " + global::Acme.Analytics.PhaseSummaryNames.SourcePrimarySchema + "." + global::Acme.Analytics.PhaseSummaryNames.SourcePrimaryProc + "({0}, {1})", args.CaseId, args.AsOfDate) +// .FromSqlRaw("SELECT * FROM " + global::Acme.Analytics.PhaseSummaryNames.SourcePrimarySchema + "." + global::Acme.Analytics.PhaseSummaryNames.SourcePrimaryProc + "({0}, {1})", args.ConsignmentId, args.AsOfDate) // // Args bind in the @parameterRef value-object's field DECLARATION order on both arms. A // callable with no @parameterRef emits a zero-arg overload calling fn_x(). @@ -40,7 +40,7 @@ public class Fr015CodegenTests internal const string Model = """ { "metadata.root": { "package": "acme::analytics", "children": [ { "object.value": { "name": "PhaseSummaryArgs", "children": [ - { "field.int": { "name": "caseId", "@required": true } }, + { "field.int": { "name": "consignmentId", "@required": true } }, { "field.timestamp": { "name": "asOfDate" } } ]}}, { "object.projection": { "name": "PhaseSummary", "children": [ @@ -117,9 +117,9 @@ public void StoredProc_with_parameterRef_emits_FromSqlInterpolated_in_declaratio // Returns the projection rows. Assert.Contains("Task>", c); // FromSqlInterpolated with schema-qualified proc name + args in declaration - // order (caseId, asOfDate → CaseId, AsOfDate). + // order (consignmentId, asOfDate → ConsignmentId, AsOfDate). Assert.Contains( - "FromSqlInterpolated($\"SELECT * FROM analytics.fn_phase_summary({args.CaseId}, {args.AsOfDate})\")", + "FromSqlInterpolated($\"SELECT * FROM analytics.fn_phase_summary({args.ConsignmentId}, {args.AsOfDate})\")", c); Assert.Contains("db.Set()", c); Assert.Contains("ToListAsync", c); @@ -131,7 +131,7 @@ public void TableFunction_with_parameterRef_emits_unqualified_proc_name() var c = Content(Files(), "ActivePhases.callable.g.cs"); // No @schema → bare function name. Assert.Contains( - "FromSqlInterpolated($\"SELECT * FROM fn_active_phases({args.CaseId}, {args.AsOfDate})\")", + "FromSqlInterpolated($\"SELECT * FROM fn_active_phases({args.ConsignmentId}, {args.AsOfDate})\")", c); Assert.Contains("global::Acme.Generated.AppDbContext db, global::Acme.Analytics.PhaseSummaryArgs args", c); } @@ -177,7 +177,7 @@ public void NamesOn_references_the_constant_through_FromSqlRaw_including_the_sch // qualification is ruled on separately across the ports" — it has been ruled on, every // port qualifies, and this was the one C# site that qualified at all. Assert.Contains( - ".FromSqlRaw(\"SELECT * FROM \" + global::Acme.Analytics.PhaseSummaryNames.SourcePrimarySchema + \".\" + global::Acme.Analytics.PhaseSummaryNames.SourcePrimaryProc + \"({0}, {1})\", args.CaseId, args.AsOfDate)", + ".FromSqlRaw(\"SELECT * FROM \" + global::Acme.Analytics.PhaseSummaryNames.SourcePrimarySchema + \".\" + global::Acme.Analytics.PhaseSummaryNames.SourcePrimaryProc + \"({0}, {1})\", args.ConsignmentId, args.AsOfDate)", c); Assert.DoesNotContain("FromSqlInterpolated", c); // The doc summary names it the same way the SQL does. @@ -192,7 +192,7 @@ public void NamesOn_table_function_without_schema_has_no_prefix() { var c = Content(NamesOnFiles(), "ActivePhases.callable.g.cs"); Assert.Contains( - ".FromSqlRaw(\"SELECT * FROM \" + global::Acme.Analytics.ActivePhasesNames.SourcePrimaryFunction + \"({0}, {1})\", args.CaseId, args.AsOfDate)", + ".FromSqlRaw(\"SELECT * FROM \" + global::Acme.Analytics.ActivePhasesNames.SourcePrimaryFunction + \"({0}, {1})\", args.ConsignmentId, args.AsOfDate)", c); Assert.Contains("typed wrapper around the table function named by ActivePhasesNames.SourcePrimaryFunction.", c); Assert.DoesNotContain("fn_active_phases", c); diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index cd32d4ffb0..21daa49382 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2379,7 +2379,7 @@ public static IReadOnlyList ValidateProjectionFilter(MetaData root) if (EntityFieldAggregates(f)) aggregateDerived.Add(f.Name); } // G7 (joined) / entity-derived: a key that is a PATH of to-one hops from the base, - // then a field of the entity reached (`caseId.status`). Not output; the view joins it. + // then a field of the entity reached (`consignmentId.status`). Not output; the view joins it. if (baseEntity is MetaObject baseObject) { foreach (var key in FilterKeys(filter)) diff --git a/server/csharp/MetaObjects/Meta/FilterPath.cs b/server/csharp/MetaObjects/Meta/FilterPath.cs index 9c05d5bffb..bb23e95e37 100644 --- a/server/csharp/MetaObjects/Meta/FilterPath.cs +++ b/server/csharp/MetaObjects/Meta/FilterPath.cs @@ -1,5 +1,5 @@ // G7 (joined half) and entity-derived — a projection @filter key may be a PATH: to-one hops from -// the base entity, then a field of the entity they reach (`caseId.status`). A hop is an +// the base entity, then a field of the entity they reach (`consignmentId.status`). A hop is an // identity.reference or a relationship with @cardinality one; a to-many hop is refused. Ported // from typescript/packages/metadata/src/core/relationship/filter-path.ts. diff --git a/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts b/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts index c43e0b7107..266429df40 100644 --- a/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts +++ b/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts @@ -49,7 +49,7 @@ const META = JSON.stringify({ { "object.value": { name: "PhaseArgs", - children: [{ "field.int": { name: "caseId", "@required": true } }], + children: [{ "field.int": { name: "consignmentId", "@required": true } }], }, }, { diff --git a/server/typescript/packages/codegen-ts/src/templates/callable-file.ts b/server/typescript/packages/codegen-ts/src/templates/callable-file.ts index 9a6f1e7624..604550bb15 100644 --- a/server/typescript/packages/codegen-ts/src/templates/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/callable-file.ts @@ -11,7 +11,7 @@ // args: PhaseSummaryArgs, // ): Promise { // const r = await db.execute( -// sql`SELECT * FROM fn_phase_summary(${args.caseId}, ${args.asOfDate})`, +// sql`SELECT * FROM fn_phase_summary(${args.consignmentId}, ${args.asOfDate})`, // ); // return r.rows.map((row) => PhaseSummarySchema.parse(row)); // } diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts index 73b575e9cc..c017bcaa2a 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts @@ -877,7 +877,7 @@ const T5_FIXTURE = JSON.stringify({ "object.value": { name: "PhaseSummaryArgs", children: [ - { "field.long": { name: "caseId", "@required": true } }, + { "field.long": { name: "consignmentId", "@required": true } }, { "field.string": { name: "asOfDate", "@required": true } }, ], }, @@ -889,7 +889,7 @@ const T5_FIXTURE = JSON.stringify({ name: "PhaseSummary", children: [ { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseSummaryArgs" } }, - { "field.long": { name: "caseId" } }, + { "field.long": { name: "consignmentId" } }, { "field.string": { name: "phase" } }, ], }, diff --git a/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts b/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts index e0d786b2a0..785609b48f 100644 --- a/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts @@ -56,7 +56,7 @@ const MODEL: unknown[] = [ { "object.value": { name: "PhaseArgs", - children: [{ "field.int": { name: "caseId", "@required": true } }], + children: [{ "field.int": { name: "consignmentId", "@required": true } }], }, }, { diff --git a/server/typescript/packages/codegen-ts/test/projection/filter-joined-path.test.ts b/server/typescript/packages/codegen-ts/test/projection/filter-joined-path.test.ts index cbd823b763..99ce18cdc6 100644 --- a/server/typescript/packages/codegen-ts/test/projection/filter-joined-path.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/filter-joined-path.test.ts @@ -1,5 +1,5 @@ // Phase 5, bug G7 (joined half): a projection @filter key may be a PATH of to-one hops from the -// base entity, then a field of the entity reached (`caseId.status`). The view joins along the +// base entity, then a field of the entity reached (`consignmentId.status`). The view joins along the // path and filters on the reached column without outputting it. A to-many hop is refused. import { describe, test, expect } from "bun:test"; @@ -16,8 +16,8 @@ const model = (filter: unknown, extraField?: unknown) => ({ { "field.boolean": { name: "active" } }, { "identity.primary": { name: "id", "@fields": "id" } }, ] } }, - { "object.entity": { name: "Case", children: [ - { "source.rdb": { "@table": "cases" } }, + { "object.entity": { name: "Consignment", children: [ + { "source.rdb": { "@table": "consignments" } }, { "field.long": { name: "id" } }, { "field.string": { name: "status" } }, { "field.long": { name: "programId", "@required": true } }, @@ -29,9 +29,9 @@ const model = (filter: unknown, extraField?: unknown) => ({ { "source.rdb": { "@table": "tasks" } }, { "field.long": { name: "id" } }, { "field.string": { name: "title" } }, - { "field.long": { name: "caseId" } }, + { "field.long": { name: "consignmentId" } }, { "identity.primary": { name: "id", "@fields": "id" } }, - { "identity.reference": { name: "caseId", "@fields": "caseId", "@references": "Case" } }, + { "identity.reference": { name: "consignmentId", "@fields": "consignmentId", "@references": "Consignment" } }, ] } }, { "object.projection": { name: "OpenTasks", "@filter": filter, children: [ { "source.rdb": { "@kind": "view", "@table": "v_open_tasks" } }, @@ -50,34 +50,34 @@ async function load(filter: unknown, extraField?: unknown) { describe("G7 — a view @filter on a joined field the view does not output", () => { test("one hop: joins the reference and filters on its column", async () => { - const { root, errors } = await load({ "caseId.status": "open" }); + const { root, errors } = await load({ "consignmentId.status": "open" }); expect(errors).toEqual([]); const [v] = buildProjectionViews(root, { dialect: "postgres" }); - expect(v!.sql).toContain("LEFT OUTER JOIN public.cases c ON c.id = t.case_id"); + expect(v!.sql).toContain("LEFT OUTER JOIN public.consignments c ON c.id = t.consignment_id"); expect(v!.sql).toContain("WHERE c.status = 'open'"); expect(v!.sql).not.toContain("AS status"); }); test("two hops, sharing the join an origin already walks", async () => { const { root, errors } = await load( - { "caseId.programId.active": true }, - { "field.string": { name: "caseStatus", children: [{ "origin.passthrough": { "@from": "Case.status", "@via": "Task.caseId" } }] } }, + { "consignmentId.programId.active": true }, + { "field.string": { name: "consignmentStatus", children: [{ "origin.passthrough": { "@from": "Consignment.status", "@via": "Task.consignmentId" } }] } }, ); expect(errors).toEqual([]); const [v] = buildProjectionViews(root, { dialect: "postgres" }); - expect(v!.sql.match(/JOIN public\.cases/g)?.length).toBe(1); + expect(v!.sql.match(/JOIN public\.consignments/g)?.length).toBe(1); expect(v!.sql).toContain("JOIN public.programs p ON p.id = c.program_id"); expect(v!.sql).toContain("WHERE p.active = TRUE"); }); test("a to-many hop is refused", async () => { - const { errors } = await load({ "caseId.tasks.title": "x" }); + const { errors } = await load({ "consignmentId.tasks.title": "x" }); expect(errors.map((e) => (e as { code?: string }).code)).toEqual(["ERR_BAD_ATTR_FILTER"]); expect(String((errors[0] as Error).message)).toContain("to-many"); }); test("a field the reached entity does not declare is refused", async () => { - const { errors } = await load({ "caseId.nope": "x" }); + const { errors } = await load({ "consignmentId.nope": "x" }); expect(errors.map((e) => (e as { code?: string }).code)).toEqual(["ERR_BAD_ATTR_FILTER"]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index 1f1b038744..d8685458a1 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -991,7 +991,7 @@ const CALLABLE_MODEL = { "object.value": { name: "PhaseSummaryArgs", children: [ - { "field.int": { name: "caseId", "@required": true } }, + { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, ], }, @@ -1013,7 +1013,7 @@ const CALLABLE_MODEL = { name: "OpenCase", children: [ { "source.rdb": { "@kind": "tableFunction", "@function": "fn_open_cases" } }, - { "field.long": { name: "caseId" } }, + { "field.long": { name: "consignmentId" } }, ], }, }, diff --git a/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts b/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts index effe9c35ff..977287189f 100644 --- a/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts @@ -29,7 +29,7 @@ describe("renderCallableFile", () => { "object.value": { name: "PhaseSummaryArgs", children: [ - { "field.int": { name: "caseId", "@required": true } }, + { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, ], }, @@ -58,7 +58,7 @@ describe("renderCallableFile", () => { expect(out).toContain("export async function callPhaseSummary"); expect(out).toContain("args: PhaseSummaryArgs"); expect(out).toContain("fn_phase_summary"); - expect(out).toContain("args.caseId"); + expect(out).toContain("args.consignmentId"); expect(out).toContain("args.asOfDate"); expect(out).toContain("Promise"); }); diff --git a/server/typescript/packages/metadata/src/core/relationship/filter-path.ts b/server/typescript/packages/metadata/src/core/relationship/filter-path.ts index beacf66eab..f12d17dcf7 100644 --- a/server/typescript/packages/metadata/src/core/relationship/filter-path.ts +++ b/server/typescript/packages/metadata/src/core/relationship/filter-path.ts @@ -1,5 +1,5 @@ // G7 (joined half) and entity-derived — a projection @filter key may be a PATH: to-one hops -// from the base entity, then a field of the entity they reach (`caseId.status`, +// from the base entity, then a field of the entity they reach (`consignmentId.status`, // `orderId.customerId.hasActiveMembership`). A hop is an identity.reference (a forward FK) or // a relationship with @cardinality one, named as an origin @via names its hops. A to-many hop // would multiply the base rows, so it is refused. One resolver for the loaders and the view diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index c3bbb3d41c..4594ceadc2 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -3591,7 +3591,7 @@ export function validateProjectionFilter(root: MetaData): ParseError[] { if (!fields.has(f.name)) fields.set(f.name, { derived: entityFieldAggregates(f), ops: opsForField(f) }); } // G7 (joined) / entity-derived: a key that is a PATH of to-one hops from the base, then a - // field of the entity reached (`caseId.status`). Not output; the view joins what it walks. + // field of the entity reached (`consignmentId.status`). Not output; the view joins what it walks. for (const key of filterKeys(filter)) { if (fields.has(key)) continue; const path = resolveFilterPath(base as MetaObject, key); diff --git a/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts b/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts index fc396982fe..774cbbec72 100644 --- a/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts +++ b/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts @@ -53,7 +53,7 @@ describe("FR-015 happy paths", () => { "object.value": { name: "PhaseSummaryArgs", children: [ - { "field.int": { name: "caseId", "@required": true } }, + { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, ], }, From 8ac93e6a52751d4661a45b0c041e0037a62faeeb Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 13 Nov 2026 21:53:47 -0500 Subject: [PATCH 221/267] fix(csharp): make frozen metadata cache thread-safe; allow patch releases from release branches (#578) * fix(csharp): a frozen node's memoized reads are safe across threads MetaData.Cached stored derived reads in a plain Dictionary. A loaded model is shared across threads, so two concurrent first reads of one node could corrupt it, and every later read then threw "Operations that change non-concurrent collections must have exclusive access". The cache is now a ConcurrentDictionary; a racing first read keeps the first stored value. Brought onto release/1.2 from main's fix (a266a51c7) for the 1.2.2 patch. * feat(release): cut a patch from a release/. maintenance branch release.mjs and finish-release.mjs refused any branch but main, so a patch on a line main has moved past could not go through its own guarded scripts. Both now accept release/. as well (one shared rule in scripts/lib/release-branch.mjs): the version must be on that branch's own line, every push goes to that branch, and finish-release's sync check compares HEAD with origin/. Every other gate is unchanged. docs/RELEASING.md gains the maintenance-branch section, including that the site deploys from the newest vN.N.N tag wherever it was cut. * no-mistakes(review): gate latest-regression before npm publish; clean unpushed-branch die * no-mistakes(review): refuse an rc of an already-shipped version * no-mistakes(document): docs: fix RELEASING.md main-only release claims --- CHANGELOG.md | 10 +++ docs/RELEASING.md | 45 +++++++++- scripts/ci-local.sh | 2 +- scripts/eject-release-gate.test.ts | 8 +- scripts/finish-release.mjs | 28 +++--- scripts/finish-release.test.ts | 58 +++++++++++++ scripts/lib/release-branch.mjs | 87 +++++++++++++++++++ scripts/release.mjs | 29 +++++-- scripts/test-release-branch.mjs | 77 ++++++++++++++++ .../CachedReadConcurrencyTests.cs | 47 ++++++++++ server/csharp/MetaObjects/Meta/MetaData.cs | 9 +- tsconfig.scripts.json | 1 + 12 files changed, 372 insertions(+), 29 deletions(-) create mode 100644 scripts/lib/release-branch.mjs create mode 100644 scripts/test-release-branch.mjs create mode 100644 server/csharp/MetaObjects.Conformance.Tests/CachedReadConcurrencyTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index b81c89d1cd..65ea81188b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,16 @@ file changes. No vocabulary or `metamodelVersion` change._ dropping it (nothing is stored); its runner skips that one scenario, recorded in the Python codegen `KNOWN_GAPS.md`. +### Fixed + +- **C#: concurrent reads of a loaded model no longer corrupt its cache.** `MetaData.Cached` + memoized derived reads (`Validators()`, `ResolvedIsArray()`, `OwnAttrs()`, …) in a plain + `Dictionary`, so two threads touching a frozen node for the first time could corrupt it, and + every later read in the process then failed with "Operations that change non-concurrent + collections must have exclusive access". A host that loads metadata once and serves requests + from it in parallel, or a parallel test run, hit this. The cache is now a + `ConcurrentDictionary`. + ## [1.2.1] — Python only _PyPI `1.2.1` only. npm, NuGet and Maven Central stay at `1.2.0` (`8.2.0`): none of them has a diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 5028ef3db1..05b2cbbdcf 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -186,7 +186,9 @@ Publish in tier order so a dependent never lands before its dependency. **`forge released. `v0.24.5` carries exactly that, and nothing caught it because no page displayed a coordinate yet. - So `release.mjs` pushes `main` and **stops**. After the ports are bumped, committed, + So `release.mjs` pushes the branch it runs on (`main`, or a `release/.` + maintenance branch — see the maintenance-branch section below) and **stops**. After the + ports are bumped, committed, pushed and tagged (`python-v*`, `csharp-v*`, `java-v.*` — `java-v8.*` at the 1.0 cut, NOT `java-v7.*`), run: @@ -614,6 +616,43 @@ default, so a dispatch meant to report cannot write. Then verify: `npm dist-tag ls @metaobjectsdev/` — authoritative, where `npm view` is CDN-cached and lags right after publish. +## Patch from a maintenance branch (`release/.`) + +**When.** `main` already holds work for the next minor (or major) that must not ship yet, and a +fix has to go out on the line already released. Cut the patch from a maintenance branch named +exactly `release/.` (for example `release/1.2`), branched from that line's last +release commit, with the fix merged into it by PR. If `main` has nothing unreleased beyond the +patch, cut from `main` as usual instead. + +**What the scripts do differently.** `scripts/release.mjs` and `scripts/finish-release.mjs` +accept `release/.` as well as `main` (the rule is +[`scripts/lib/release-branch.mjs`](../scripts/lib/release-branch.mjs), shared by both): + +- The version must be on the branch's own line: `release/1.2` cuts `1.2.x` (and `1.2.x-rc.N`) + and refuses anything else, such as `1.3.0`. +- Every push goes to that branch (`git push origin release/1.2`), never `main`. +- `finish-release`'s sync check compares HEAD with `origin/release/1.2`, not `origin/main`. + +Every other gate is unchanged. Bump the PyPI/NuGet/Maven manifests, run `bun run site:payload`, +commit and push on the maintenance branch, and push the `python-v*` / `csharp-v*` / `java-v*` +tags from it, exactly as on `main`. + +**The site follows the newest tag.** The website deploys from the newest `vN.N.N` release tag +(rule 7), wherever it was cut. A patch tag on a maintenance branch therefore becomes what +metaobjects.dev shows, including its payload and coordinates, until the next release is tagged. +The converse is enforced: `finish-release` refuses to tag a patch on a line older than a tag +that already exists (`v1.2.3` once `v1.3.0` exists), because the deploy would never resolve it. +So a maintenance patch is for a line that is still the newest release. The same holds on npm: +`release.mjs` publishes to `latest`, and a patch cut after a newer minor shipped would move +`latest` backwards — so `release.mjs` refuses, in its preflight and before anything is +published, any version older than the newest release tag, and any release candidate of a +version that has already shipped (npm sorts it below the full release; resolved the same +way the site deploy resolves its tag). It offers no non-`latest` dist-tag path. + +**Then bring the fix to `main`.** A maintenance branch is never merged back wholesale (its +version bumps and CHANGELOG would collide with `main`'s). Cherry-pick or re-land each fix on +`main` by PR. + ## Isolated patch (one package) If only one package changed (e.g. a `cli` bugfix), bump just that package, `rm bun.lock && bun @@ -696,7 +735,9 @@ lock the repo/owner IDs against resurrection attacks.) ## Procedure -1. **Pick the publish commit on `main`** (a stable, merged tip — not a mid-refactor branch). Ensure +1. **Pick the publish commit on the branch the release is cut from** (`main`, or the + `release/.` maintenance branch for a patch — the workflow publishes the + COMMITTED ``, so the tag must name that branch's tree). Ensure the packaging config + `publish-csharp.yml` are on it. Set `` in `Directory.Build.props`. 2. **Validate locally** (catches immutable-version mistakes before they're permanent): ```bash diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 11b50b23e8..4e3a92a4c4 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -487,7 +487,7 @@ gate_site_reference() { bun_install && bun scripts/build-site-reference.ts --che # exercised) are the ones worth a test at all. See scripts/maven-coordinate.mjs. # And the publish workflows' tag check (scripts/check-release-tag.mjs), whose test also reads # each real manifest, so a layout change fails here rather than on a release tag. -gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && bash tools/prerelease/test-prerelease-link.sh; } +gate_release_tag() { bun test scripts/finish-release.test.ts scripts/eject-release-gate.test.ts && node scripts/test-maven-coordinate.mjs && node scripts/test-prerelease-version.mjs && node scripts/test-check-release-tag.mjs && node scripts/test-changelog-promote.mjs && node scripts/test-release-branch.mjs && bash tools/prerelease/test-prerelease-link.sh; } # ── repo-root scripts/ typechecks ───────────────────────────────────────────── # `bun test` transpiles per file and never typechecks, and `bun run --filter '*' diff --git a/scripts/eject-release-gate.test.ts b/scripts/eject-release-gate.test.ts index 98e743f50c..90f45b093c 100644 --- a/scripts/eject-release-gate.test.ts +++ b/scripts/eject-release-gate.test.ts @@ -102,9 +102,9 @@ describe("eject release gate — the command and its wiring", () => { // ADR-0034 Amendment 8 makes the gate the first preflight check of `release.mjs`. The // check after it is the branch check, so a fixture on another branch tells the two apart: - // a refused version stops before "must be on main", and an allowed one reaches it. + // a refused version stops before "not on main", and an allowed one reaches it. test("release.mjs asks the gate first in its preflight, and stops on a refusal", () => { - const RELEASE_SCRIPTS = ["release.mjs", "lib/changelog-promote.mjs", "publish-set.mjs", "maven-coordinate.mjs"]; + const RELEASE_SCRIPTS = ["release.mjs", "lib/changelog-promote.mjs", "lib/release-branch.mjs", "publish-set.mjs", "maven-coordinate.mjs"]; const onBranch = (pending: (typeof ENTRY)[]) => { const root = repoWith(JSON.stringify(manifest(pending)), RELEASE_SCRIPTS); const git = (...args: string[]) => spawnSync("git", ["-C", root, ...args], { encoding: "utf8" }); @@ -119,11 +119,11 @@ describe("eject release gate — the command and its wiring", () => { const refused = release(blocked, "1.1.0"); expect(refused.code).not.toBe(0); expect(refused.out).toContain("the eject contract does not hold yet"); - expect(refused.out).not.toContain("must be on main"); + expect(refused.out).not.toContain("not on main"); for (const allowed of [release(blocked, "1.1.0-rc.1"), release(onBranch([]), "1.1.0")]) { expect(allowed.out).not.toContain("the eject contract does not hold yet"); - expect(allowed.out).toContain("must be on main (you are on not-main)"); + expect(allowed.out).toContain("not on main or a release/. maintenance branch (you are on not-main)"); } }); diff --git a/scripts/finish-release.mjs b/scripts/finish-release.mjs index b3c7909529..5fb4529d37 100644 --- a/scripts/finish-release.mjs +++ b/scripts/finish-release.mjs @@ -37,6 +37,7 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { mavenVersion } from "./maven-coordinate.mjs"; import { ejectReleaseRefusalAt } from "./eject-release-gate.mjs"; +import { releaseBranchRefusal, newestNpmReleaseTag } from "./lib/release-branch.mjs"; const REPO = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const CHECK_ONLY = process.argv.includes("--check"); @@ -80,8 +81,13 @@ ok("eject contract: the pending list is empty"); if (out("git status --porcelain") !== "") { die("working tree is dirty — commit or stash before tagging, or the tag names a tree you did not review"); } -if (out("git rev-parse --abbrev-ref HEAD") !== "main") die("not on main"); -// NOT `|| true`. A swallowed fetch leaves `origin/main` at a STALE remote-tracking ref, +// `main`, or a `release/.` maintenance branch tagging a version on its own +// line (scripts/lib/release-branch.mjs). The sync check below compares against THAT +// branch's remote, never origin/main. +const branch = out("git rev-parse --abbrev-ref HEAD"); +const branchRefusal = releaseBranchRefusal(branch, VERSION); +if (branchRefusal !== null) die(branchRefusal); +// NOT `|| true`. A swallowed fetch leaves `origin/` at a STALE remote-tracking ref, // and the very next comparison then prints "synced with origin" having verified nothing — // with git's own "Could not read from remote repository" scrolling past just above the // tick. The realistic case is the port-bump commit pushed from another checkout while @@ -93,10 +99,12 @@ try { die(`git fetch origin failed, so "synced with origin" cannot be verified: ` + `${e instanceof Error ? e.message : String(e)}`); } -if (out("git rev-parse HEAD") !== out("git rev-parse origin/main")) { - die("HEAD is not origin/main — push first; the deploy clones the REMOTE tag"); +// `|| true` here is not the swallow warned about above: a maintenance branch that was +// never pushed has no `origin/`, and that must read as "not synced", not crash. +if (out("git rev-parse HEAD") !== out(`git rev-parse --verify --quiet origin/${branch} || true`)) { + die(`HEAD is not origin/${branch} — push first; the deploy clones the REMOTE tag`); } -ok("on main, clean, synced with origin"); +ok(`on ${branch}, clean, synced with origin`); // ── 2. the tag is free ─────────────────────────────────────────────────────── // Never move a tag. A moved tag silently changes what the website deploys, and any @@ -378,13 +386,9 @@ ok("the llms mirrors state this release"); // newest tag of a frozen line and passes green forever. After the 1.0 cut it would have // resolved v0.25.0 at every future release, so the check could never fire again — the same // defect that kept the live site on 0.25.0 with every deploy step green. Nothing here needs -// maintaining at the next major. -const resolved = out(`git tag -l 'v*' | grep -E '^v[0-9]+\\.[0-9]+\\.[0-9]+$' | sort -rV || true`) - .split("\n").map((t) => t.trim()).filter(Boolean) - .find((t) => { - const pkg = out(`git show ${t}:server/typescript/packages/cli/package.json 2>/dev/null || true`); - try { return JSON.parse(pkg).version === t.slice(1); } catch { return false; } - }) ?? ""; +// maintaining at the next major. The selector itself is shared with `release.mjs` +// (scripts/lib/release-branch.mjs), so the two cannot disagree about the npm line. +const resolved = newestNpmReleaseTag(out); const wouldResolve = [resolved, tag].filter(Boolean).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).at(-1); if (wouldResolve !== tag) { diff --git a/scripts/finish-release.test.ts b/scripts/finish-release.test.ts index ea089fc87e..713bdfe6eb 100644 --- a/scripts/finish-release.test.ts +++ b/scripts/finish-release.test.ts @@ -36,6 +36,8 @@ const SCRIPT = readFileSync(resolve(REPO, "scripts/finish-release.mjs"), "utf8") const MAVEN_COORD = readFileSync(resolve(REPO, "scripts/maven-coordinate.mjs"), "utf8"); // Gate 0 asks the eject release gate, and the fixture ships the real one for the same reason. const EJECT_GATE = readFileSync(resolve(REPO, "scripts/eject-release-gate.mjs"), "utf8"); +// Gate 1's branch rule, shared with release.mjs — the real module, for the same reason. +const RELEASE_BRANCH = readFileSync(resolve(REPO, "scripts/lib/release-branch.mjs"), "utf8"); const EJECT_MANIFEST = "fixtures/generator-registry-conformance/registry.json"; /** The shared file as the release branch leaves it: nothing pending. */ const EJECT_CLEAR = `${JSON.stringify({ eject: { pending: [] } })}\n`; @@ -173,6 +175,7 @@ function makeRepo(spec: Spec = {}): Fixture { "scripts/finish-release.mjs": SCRIPT, "scripts/maven-coordinate.mjs": MAVEN_COORD, "scripts/eject-release-gate.mjs": EJECT_GATE, + "scripts/lib/release-branch.mjs": RELEASE_BRANCH, })) { const full = join(work, rel); mkdirSync(dirname(full), { recursive: true }); @@ -291,6 +294,46 @@ describe("finish-release gate 1: the tree that will be tagged", () => { expect(r.out).toContain("HEAD is not origin/main"); }); + // A maintenance branch `release/.` may tag a patch on its own line; the + // rule itself is unit-tested in scripts/test-release-branch.mjs. These cases prove the + // script wires it: the branch is accepted, a version off its line is refused, and the + // sync check compares against origin/, never origin/main. + const onMaintenance = (name: string, push = true) => { + const f = makeRepo(); + f.git(f.work, "checkout", "--quiet", "-b", name); + if (push) f.git(f.work, "push", "--quiet", "-u", "origin", name); + return f; + }; + + test("a maintenance branch on the release's own line passes gate 1", () => { + const r = onMaintenance("release/0.24").run(RELEASE, "--check"); + expect(r.out).toContain("on release/0.24, clean, synced with origin"); + expect(r.code).toBe(0); + }); + + test("a maintenance branch refuses a version off its line", () => { + const r = onMaintenance("release/0.23").run(RELEASE, "--check"); + expect(r.code).not.toBe(0); + expect(r.out).toContain("cuts only 0.23.x"); + expect(r.out).not.toContain("synced with origin"); + }); + + test("a maintenance branch syncs against its OWN remote, not origin/main", () => { + const f = onMaintenance("release/0.24"); + writeFileSync(join(f.work, "NOTES.md"), "unpushed\n"); + f.git(f.work, "add", "-A"); + f.git(f.work, "commit", "--quiet", "-m", "local only"); + const r = f.run(RELEASE, "--check"); + expect(r.code).not.toBe(0); + expect(r.out).toContain("HEAD is not origin/release/0.24"); + }); + + test("a maintenance branch never pushed is refused, not crashed on", () => { + const r = onMaintenance("release/0.24", false).run(RELEASE, "--check"); + expect(r.code).not.toBe(0); + expect(r.out).toContain("HEAD is not origin/release/0.24"); + }); + // The defect: the fetch was `|| true`, so a failure left `origin/main` at a stale // remote-tracking ref and the very next line printed "synced with origin" having // verified nothing. The realistic case is the port-bump commit pushed from another @@ -647,6 +690,21 @@ describe("finish-release gate 7: cutting the tag", () => { expect(f.git(f.origin, "tag", "-l")).toContain(`v${RELEASE}`); }); + test("tags and pushes from a maintenance branch, leaving origin/main where it was", () => { + const f = makeRepo(); + const mainBefore = f.git(f.origin, "rev-parse", "main"); + f.git(f.work, "checkout", "--quiet", "-b", "release/0.24"); + writeFileSync(join(f.work, "NOTES.md"), "the patch\n"); + f.git(f.work, "add", "-A"); + f.git(f.work, "commit", "--quiet", "-m", "patch on the maintenance line"); + f.git(f.work, "push", "--quiet", "-u", "origin", "release/0.24"); + const r = f.run(RELEASE); + expect(r.out).toContain(`cut and pushed v${RELEASE}`); + expect(r.code).toBe(0); + expect(f.git(f.origin, "rev-parse", `v${RELEASE}^{commit}`)).toBe(f.git(f.work, "rev-parse", "HEAD")); + expect(f.git(f.origin, "rev-parse", "main")).toBe(mainBefore); + }); + test("--check cuts nothing", () => { const f = makeRepo(); expect(f.run(RELEASE, "--check").code).toBe(0); diff --git a/scripts/lib/release-branch.mjs b/scripts/lib/release-branch.mjs new file mode 100644 index 0000000000..50b1813214 --- /dev/null +++ b/scripts/lib/release-branch.mjs @@ -0,0 +1,87 @@ +// Which branch a release may be cut from — shared by `scripts/release.mjs` and +// `scripts/finish-release.mjs`, so the two cannot disagree about it. +// +// Two kinds of branch qualify: +// +// - `main`, for every release, as before. +// - a maintenance branch named `release/.`, for a PATCH on a line `main` +// has moved past. It may cut only versions on its own line: `release/1.2` cuts 1.2.x +// and nothing else, because a 1.3.0 cut from it would ship a minor without the work +// `main` holds for that minor. +// +// The caller pushes to, and compares HEAD against, `origin/` — never `origin/main` +// when it is on a maintenance branch. + +/** The pattern a maintenance branch name must match. */ +export const MAINTENANCE_BRANCH = /^release\/(\d+)\.(\d+)$/; + +/** + * Why `version` may not be released from `branch`, or `null` when it may. + * + * @param {string} branch the current branch, as `git rev-parse --abbrev-ref HEAD` prints it + * @param {string} version the version being cut (`1.2.2`, or `1.2.2-rc.1` for release.mjs) + * @returns {string | null} + */ +export function releaseBranchRefusal(branch, version) { + if (branch === "main") return null; + const m = MAINTENANCE_BRANCH.exec(branch); + if (m === null) { + return `not on main or a release/. maintenance branch (you are on ${branch})`; + } + const [, major, minor] = m; + const v = /^(\d+)\.(\d+)\./.exec(version); + if (v === null || v[1] !== major || v[2] !== minor) { + return `${branch} is the ${major}.${minor} maintenance branch and cuts only ${major}.${minor}.x — ` + + `${version} is not on that line (cut it from main, or from its own release/.)`; + } + return null; +} + +/** + * The newest tag on the npm release line, the way the site deploy resolves it: the newest + * `vN.N.N` whose `server/typescript/packages/cli/package.json` is versioned as the tag — + * the property that DEFINES the npm line, never a version prefix (the JVM `v7.20.12` ships + * cli `0.20.11` and must not count). `""` when no release tag exists. + * + * @param {(cmd: string) => string} out run a command and return its trimmed stdout, like + * each script's own `out` + * @returns {string} + */ +export function newestNpmReleaseTag(out) { + return out(`git tag -l 'v*' | grep -E '^v[0-9]+\\.[0-9]+\\.[0-9]+$' | sort -rV || true`) + .split("\n").map((t) => t.trim()).filter(Boolean) + .find((t) => { + const pkg = out(`git show ${t}:server/typescript/packages/cli/package.json 2>/dev/null || true`); + try { return JSON.parse(pkg).version === t.slice(1); } catch { return false; } + }) ?? ""; +} + +/** + * Why `version` may not be released while `newestTag` is the newest release tag, or `null` + * when it may. `bun publish` tags `latest`, so a version older than the newest release + * would move `latest` backwards — including an `-rc` cut on a line a newer release passed, + * and an `-rc` of the very version that already shipped (npm sorts `1.2.4-rc.1` below + * `1.2.4`). + * + * @param {string} version the version being cut (`1.2.4`, or `1.2.4-rc.1`) + * @param {string} newestTag the newest npm-line release tag (`v1.3.0`), or `""` if none + * @returns {string | null} + */ +export function latestRegressionRefusal(version, newestTag) { + if (newestTag === "") return null; + const a = /^(\d+)\.(\d+)\.(\d+)/.exec(version); + const b = /^v(\d+)\.(\d+)\.(\d+)$/.exec(newestTag); + if (a === null || b === null) return null; + for (let i = 1; i <= 3; i++) { + if (Number(a[i]) === Number(b[i])) continue; + if (Number(a[i]) > Number(b[i])) return null; + return `${version} is older than ${newestTag.slice(1)}, the newest release — npm publishes to ` + + `\`latest\`, so this would move \`latest\` backwards. A patch on a line a newer release ` + + `has passed needs a non-\`latest\` dist-tag path this script does not yet offer.`; + } + return /-rc\.\d+$/.test(version) + ? `${version} is a release candidate for ${newestTag.slice(1)}, which has already shipped — ` + + `npm sorts it below the full release, so publishing to \`latest\` would move \`latest\` ` + + `backwards.` + : null; +} diff --git a/scripts/release.mjs b/scripts/release.mjs index 04ef11d357..31a985fbd6 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -33,6 +33,7 @@ import { createInterface } from "node:readline/promises"; import { publishSet } from "./publish-set.mjs"; import { mavenVersion } from "./maven-coordinate.mjs"; import { ejectReleaseRefusalAt } from "./eject-release-gate.mjs"; +import { releaseBranchRefusal, newestNpmReleaseTag, latestRegressionRefusal } from "./lib/release-branch.mjs"; const VERSION = process.argv[2]; const DRY = process.argv.includes("--dry-run"); @@ -70,10 +71,17 @@ console.log(`\n── Releasing ${VERSION}${DRY ? " (DRY RUN)" : ""} ──\n`) const ejectRefusal = ejectReleaseRefusalAt(VERSION, join(dirname(fileURLToPath(import.meta.url)), "..")); if (ejectRefusal !== null) die(ejectRefusal); +// `main`, or a `release/.` maintenance branch cutting a version on its own +// line (scripts/lib/release-branch.mjs). Everything below that pushes or compares against +// the remote uses THIS branch, so a maintenance cut never touches main. const branch = out("git rev-parse --abbrev-ref HEAD"); -if (branch !== "main") die(`must be on main (you are on ${branch})`); +const branchRefusal = releaseBranchRefusal(branch, VERSION); +if (branchRefusal !== null) die(branchRefusal); sh("git fetch origin", { quiet: true }); -if (out("git rev-list --count HEAD..origin/main") !== "0") die("main is behind origin/main — pull first"); +if (out(`git rev-parse --verify --quiet origin/${branch} || true`) === "") { + die(`${branch} has no origin/${branch} — push the branch first`); +} +if (out(`git rev-list --count HEAD..origin/${branch}`) !== "0") die(`${branch} is behind origin/${branch} — pull first`); // Clean tree, except the CHANGELOG (we promote its [Unreleased] section) and untracked noise. const dirty = out("git status --porcelain").split("\n") @@ -82,6 +90,13 @@ if (dirty.length) die(`uncommitted changes:\n${dirty.join("\n")}\n(commit or sta if (out(`git tag -l v${VERSION}`)) die(`tag v${VERSION} already exists`); +// `bun publish` tags `latest`, so a version older than the newest release would move +// `latest` backwards — finish-release gate 6 catches that only after the publish; this +// refuses it before anything irreversible. Same npm-line tag resolution the site deploy +// uses (scripts/lib/release-branch.mjs). +const latestRefusal = latestRegressionRefusal(VERSION, newestNpmReleaseTag(out)); +if (latestRefusal !== null) die(latestRefusal); + // Can we publish AT ALL? Checked here, before the version bump, because the bump is // committed and pushed long before the first `bun publish` — so discovering a dead // credential at the publish step strands the release mid-flight. The 0.24.0 cut found @@ -129,7 +144,7 @@ const taken = (await Promise.all(set.map(async (p) => { if (taken.length) die(`${VERSION} is already published for:\n ${taken.join("\n ")}\n` + `npm versions are permanent — pick the next free version.`); -ok(`preflight: on main, synced, ${VERSION} free on all ${set.length} packages`); +ok(`preflight: on ${branch}, synced, ${VERSION} free on all ${set.length} packages`); ok(`lockstep set @ ${current}: ${set.length} packages → ${VERSION}`); // The showcase corpus is what metaobjects.dev publishes as "real `meta gen` output", @@ -262,7 +277,7 @@ for (const pkg of ordered) { // --- PHASE 8: push (the tag is NOT cut here) ------------------------------- // This script publishes npm, which is one of FOUR registries. The PyPI/NuGet/Maven -// version bump is a separate, later commit — so at this point `main` states the new npm +// version bump is a separate, later commit — so at this point the branch states the new npm // coordinate and three stale ones, and the site payload committed above says exactly // that. // @@ -274,8 +289,8 @@ for (const pkg of ordered) { // // So the tag moves to the END of the coordinated cut: `scripts/finish-release.mjs`, // which refuses to tag until the payload's coordinates match what actually shipped. -sh("git push origin main", { quiet: true }); -ok("pushed main (tag deferred to finish-release)"); +sh(`git push origin ${branch}`, { quiet: true }); +ok(`pushed ${branch} (tag deferred to finish-release)`); // --- PHASE 11: post-publish smoke (the RC's safety net) ------------------- // NOT under tmpdir(). Node's resolution walks UP from the scratch dir, so a stale @@ -299,4 +314,4 @@ console.log(` 3. \`bun scripts/finish-release.mjs ${VERSION}\` — gates the c console.log(` The website pins to v${VERSION}, so tagging before step 1 publishes three stale versions.`); console.log(` Docs version refs are NOT auto-bumped (low-value churn for a patch); batch them when convenient.`); console.log(` The site payload IS auto-bumped and committed here — but only its npm coordinate.`); -console.log(` The PyPI/NuGet/Maven bump commit must run \`bun run site:payload\` or gates goes red on main.\n`); +console.log(` The PyPI/NuGet/Maven bump commit must run \`bun run site:payload\` or gates goes red on ${branch}.\n`); diff --git a/scripts/test-release-branch.mjs b/scripts/test-release-branch.mjs new file mode 100644 index 0000000000..d3e67e0ec6 --- /dev/null +++ b/scripts/test-release-branch.mjs @@ -0,0 +1,77 @@ +#!/usr/bin/env node +// Tests for scripts/lib/release-branch.mjs — which branch a release may be cut from. +// +// node scripts/test-release-branch.mjs + +import { releaseBranchRefusal, latestRegressionRefusal, newestNpmReleaseTag } from "./lib/release-branch.mjs"; + +let fails = 0; +const check = (cond, label) => (cond ? console.log(`ok: ${label}`) : (console.error(`FAIL: ${label}`), fails++)); +const refused = (branch, version) => releaseBranchRefusal(branch, version) !== null; + +// main is unchanged: any version, any line. +check(!refused("main", "1.2.2"), "main cuts a patch"); +check(!refused("main", "1.3.0"), "main cuts a minor"); +check(!refused("main", "2.0.0-rc.1"), "main cuts a release candidate"); + +// A maintenance branch cuts its own line only. +check(!refused("release/1.2", "1.2.2"), "release/1.2 cuts 1.2.2"); +check(!refused("release/1.2", "1.2.10"), "release/1.2 cuts 1.2.10"); +check(!refused("release/1.2", "1.2.3-rc.1"), "release/1.2 cuts a 1.2.x release candidate"); +check(refused("release/1.2", "1.3.0"), "release/1.2 refuses 1.3.0 (mismatched minor)"); +check(refused("release/1.2", "1.1.9"), "release/1.2 refuses 1.1.9 (an older minor)"); +check(refused("release/1.2", "2.2.0"), "release/1.2 refuses 2.2.0 (mismatched major)"); +check(refused("release/1.2", "1.20.0"), "release/1.2 refuses 1.20.0 (a prefix is not a match)"); +check(refused("release/1.20", "1.2.0"), "release/1.20 refuses 1.2.0"); +check(releaseBranchRefusal("release/1.2", "1.3.0")?.includes("cuts only 1.2.x") === true, + "the mismatch refusal names the line the branch cuts"); + +// Anything else is refused, as before. +check(refused("release-prep", "1.2.2"), "an ordinary branch is refused"); +check(refused("release/1", "1.2.2"), "release/ alone is not a maintenance branch"); +check(refused("release/1.2.x", "1.2.2"), "release/1.2.x is not a maintenance branch"); +check(refused("fix/release/1.2", "1.2.2"), "a nested name is not a maintenance branch"); +check(refused("HEAD", "1.2.2"), "a detached HEAD is refused"); +check(releaseBranchRefusal("release-prep", "1.2.2")?.includes("not on main") === true, + "the refusal for an ordinary branch still says it is not on main"); + +// `latest` never moves backwards: `bun publish` tags `latest`, so a version older than the +// newest release must be refused. The oracle is npm's own dist-tag semantics: `latest` +// resolves to whichever version was published last, so publishing an older one regresses it. +check(latestRegressionRefusal("1.2.4", "v1.3.0") !== null, + "a version older than the newest release is refused"); +check(latestRegressionRefusal("1.2.4-rc.1", "v1.3.0") !== null, + "an RC on a line a newer release passed is refused too"); +check(latestRegressionRefusal("1.2.4-rc.1", "v1.2.4") !== null, + "an RC of the version that already shipped is refused"); +check(latestRegressionRefusal("1.2.4", "v1.2.4") === null, + "the released version itself is not a regression"); +check(latestRegressionRefusal("1.3.0-rc.1", "v1.2.4") === null, + "an RC of a NEWER triple passes"); +check(latestRegressionRefusal("1.3.1", "v1.3.0") === null, + "a version newer than the newest release passes"); +check(latestRegressionRefusal("1.2.4", "v1.2.3") === null, + "a patch on the newest release line passes"); +check(latestRegressionRefusal("1.2.4", "") === null, + "no released tag yet passes"); +check(latestRegressionRefusal("1.2.4", "v1.3.0")?.includes("`latest` backwards") === true, + "the refusal names the `latest` constraint"); + +// The newest release is resolved by the property that defines the npm line (deploy.yml's +// selector): the newest `vN.N.N` whose cli/package.json is versioned as the tag. A version +// prefix would wrongly pick `v8.2.2` (no cli tree) or the JVM `v7.20.12` (cli 0.20.11). +const cliOf = new Map([["v1.3.0", "1.3.0"], ["v1.2.2", "1.2.2"], ["v7.20.12", "0.20.11"]]); +const fakeOut = (cmd) => { + if (cmd.startsWith("git tag -l")) return "v8.2.2\nv1.3.0\nv1.2.2\nv7.20.12"; + const t = /^git show (v[\d.]+):/.exec(cmd)?.[1]; + const v = t === undefined ? undefined : cliOf.get(t); + return v === undefined ? "" : `{"name":"@metaobjectsdev/cli","version":"${v}"}`; +}; +check(newestNpmReleaseTag(fakeOut) === "v1.3.0", + "the newest npm-line tag wins; a treeless tag and the JVM line are skipped"); + +if (fails > 0) { + console.error(`\n${fails} check(s) failed`); + process.exit(1); +} +console.log("\nall checks passed"); diff --git a/server/csharp/MetaObjects.Conformance.Tests/CachedReadConcurrencyTests.cs b/server/csharp/MetaObjects.Conformance.Tests/CachedReadConcurrencyTests.cs new file mode 100644 index 0000000000..83f5ed87ed --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/CachedReadConcurrencyTests.cs @@ -0,0 +1,47 @@ +using MetaObjects; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +/// +/// A frozen tree is shared across threads (a host loads metadata once and serves every request +/// from it), so the first concurrent touch of a node's memoized reads must not corrupt its cache. +/// +public class CachedReadConcurrencyTests +{ + [Fact] + public void Concurrent_first_reads_of_a_frozen_node_do_not_corrupt_its_cache() + { + for (var round = 0; round < 200; round++) + { + var entity = new MetaObject(new TypeId("object", "entity"), "Order"); + for (var i = 0; i < 40; i++) + { + var f = new MetaField(new TypeId("field", "string"), $"f{i}"); + f.AddChild(new MetaRequiredValidator(new TypeId("validator", "required"), "req")); + entity.AddChild(f); + } + entity.Freeze(); + var fields = entity.OwnFields(); + + using var start = new ManualResetEventSlim(false); + var workers = Enumerable.Range(0, 8).Select(w => Task.Run(() => + { + start.Wait(); + foreach (var f in fields) + { + _ = f.Validators(); + _ = f.ResolvedIsArray(); + _ = f.OwnAttrs(); + _ = f.IsRequired; + } + _ = entity.Fields(); + })).ToArray(); + start.Set(); + Task.WaitAll(workers); + + Assert.All(fields, f => Assert.Single(f.Validators())); + } + } +} diff --git a/server/csharp/MetaObjects/Meta/MetaData.cs b/server/csharp/MetaObjects/Meta/MetaData.cs index f4a86651f9..8f9c086249 100644 --- a/server/csharp/MetaObjects/Meta/MetaData.cs +++ b/server/csharp/MetaObjects/Meta/MetaData.cs @@ -150,7 +150,9 @@ public void SetCanonicalAttr(string name, object? canonical) private ErrorSource _source = CodeSource.Default; /// Per-instance read cache: only populated once the node is frozen. - private readonly Dictionary _cache = new(); + // Concurrent: a frozen tree is shared across threads (loaded once, read by every request + // or test), and a plain Dictionary corrupts on two concurrent first writes. + private readonly System.Collections.Concurrent.ConcurrentDictionary _cache = new(); // --------------------------------------------------------------------------- // Constructor @@ -179,8 +181,9 @@ protected T Cached(string key, Func compute) return (T)cached!; } T value = compute(); - if (_frozen) _cache[key] = value; - return value; + // A racing first read computes the same value from the same immutable tree; keep the + // first one stored so every caller gets one instance. + return _frozen ? (T)_cache.GetOrAdd(key, value)! : value; } // --------------------------------------------------------------------------- diff --git a/tsconfig.scripts.json b/tsconfig.scripts.json index 1d8f364c53..bde36e2df4 100644 --- a/tsconfig.scripts.json +++ b/tsconfig.scripts.json @@ -149,6 +149,7 @@ "scripts/maven-coordinate.mjs", "scripts/eject-release-gate.mjs", "scripts/lib/changelog-promote.mjs", + "scripts/lib/release-branch.mjs", "scripts/check-release-tag.mjs" ] } From 1da085810824cfe49f7fc5eb1d054bca98825d11 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 21:54:27 -0500 Subject: [PATCH 222/267] fix(verify): a defaulted parameter may be left out of a declared function; say what the signature check does not see A declared arity between the function's required and full parameter counts matches. The check compares plain type names, so json, array, enum and user-defined kinds are not type-checked and a domain is compared by its own name; the docs, the CHANGELOG and the verify output say so. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++- docs/features/relationships.md | 6 ++++- .../packages/cli/src/commands/verify.ts | 2 ++ .../test/verify-declared-functions.test.ts | 2 ++ .../test/view-vocabulary-rc21-pg.test.ts | 6 +++++ .../packages/migrate-ts/src/index.ts | 2 +- .../src/introspect/declared-functions.ts | 23 +++++++++++++++---- 7 files changed, 37 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a64324c04a..313f14b06f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,8 @@ vocabulary; upgrade every port together. column type, the one its table column would have (length or `@dbColumnType` spelling, precision and scale, a local or zoned timestamp). The signature is a declaration: `meta verify --db` reads each function from `pg_proc` and fails on a missing function or a parameter or return type that - differs, so the cast never hides a wrong `@returns`. Declared on an entity it is entity-derived + differs, so the cast never hides a wrong `@returns` (a defaulted parameter may be left out; json, + array, enum and user-defined kinds are not type-checked, and a domain is compared by its name). Declared on an entity it is entity-derived (Postgres only). On `object.projection`: `@grain` / `@grainOrdinal`, one row per element of a jsonb `field.object` array, its members read through `origin.passthrough @from: .`; and diff --git a/docs/features/relationships.md b/docs/features/relationships.md index 33bf7e44e6..873c063677 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -286,7 +286,11 @@ expressions read. column type, the one its table column would have (length or `@dbColumnType` spelling, precision and scale, a local or zoned timestamp). The signature is a declaration that `meta verify --db` checks: it reads the function from `pg_proc` and fails on a missing function, or a parameter or return -type that differs, so the cast never hides a wrong `@returns`. Declared on an entity, it is +type that differs, so the cast never hides a wrong `@returns`. A declared arity between the +function's required and full parameter counts matches (the rest take their defaults). The +comparison is by plain type name: a json, array, enum or user-defined kind is not type-checked +(only the arity is), and a domain is compared by its own name, so a domain-typed parameter or +result is reported as a mismatch. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. MetaObjects never creates the function (it is owned SQL, created before the view). Postgres only. diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index a3181125a5..c721382d37 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -78,6 +78,7 @@ import { verifyReplay, introspect, checkDeclaredFunctions, + DECLARED_FUNCTION_CHECK_LIMITS, diff, withoutViewRecreates, readSnapshot, @@ -1472,6 +1473,7 @@ export async function verifyCommand( if (kysely.dialect === "postgres") { try { functionDrift = await checkDeclaredFunctions(kysely.db, root); + if (functionDrift.length > 0) log.warn(`verify: ${DECLARED_FUNCTION_CHECK_LIMITS}`); } catch (err) { schemaRunError = `failed to read the declared functions from ${kysely.displayUrl}: ${describeError(err)}`; log.error(`verify: ${schemaRunError}`); diff --git a/server/typescript/packages/cli/test/verify-declared-functions.test.ts b/server/typescript/packages/cli/test/verify-declared-functions.test.ts index 1a8b0bd40c..bb85272ff9 100644 --- a/server/typescript/packages/cli/test/verify-declared-functions.test.ts +++ b/server/typescript/packages/cli/test/verify-declared-functions.test.ts @@ -71,6 +71,8 @@ describe("meta verify --db — declared origin.function signatures", () => { expect(bad.code).toBe(1); expect(bad.out).toContain("origin.function verify_fn.meter_reading on MeterRow.reading: declared (long) → int, which needs " + "verify_fn.meter_reading(bigint) → integer; the database has verify_fn.meter_reading(bigint) → numeric."); + // Fix round 3 (M2): the run says what the comparison does not see. + expect(bad.out).toContain("a domain is compared by its own name, not its base type"); const good = await capture(async () => verifyCommand(["--db", PG_URL!], await project("decimal", "decimal"))); expect(good.out).not.toContain("origin.function verify_fn.meter_reading"); diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts index 75c3e47047..36184a6ace 100644 --- a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -269,6 +269,12 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { // A parameter of another type, and a function that does not exist. const [param] = await findings({ "field.decimal": fn({ name: "limit" }, { "@function": "credit_limit", "@args": ["pin"], "@params": ["int"], "@returns": "decimal" }) }); expect(param).toMatch(/needs app\.credit_limit\(integer\) → numeric; the database has app\.credit_limit\(bigint\) → numeric\.$/); + // Fix round 3 (M1): a trailing defaulted parameter may be left out; fewer than the required ones is a finding. + await sql.raw(`CREATE FUNCTION app.tier_label(bigint, as_of date DEFAULT current_date) RETURNS text LANGUAGE sql STABLE + AS $$ SELECT 'tier-' || $1 || '@' || $2 $$`).execute(k); + expect(await findings({ "field.string": fn({ name: "tierLabel" }, { "@function": "tier_label", "@args": ["id"], "@params": ["long"], "@returns": "string" }) })).toEqual([]); + const [tooFew] = await findings({ "field.string": fn({ name: "tierLabel" }, { "@function": "tier_label", "@args": [], "@params": [], "@returns": "string" }) }); + expect(tooFew).toMatch(/needs app\.tier_label\(\) → text \| character varying \| character; the database has app\.tier_label\(bigint, date\) → text\.$/); const [missing] = await findings({ "field.int": fn({ name: "score" }, { "@function": "no_such_fn", "@args": [], "@params": [], "@returns": "int" }) }); expect(missing).toBe("origin.function app.no_such_fn on AccountRow.score: no such function in the database (declared () → int)."); }, 60_000); diff --git a/server/typescript/packages/migrate-ts/src/index.ts b/server/typescript/packages/migrate-ts/src/index.ts index 0598f081ba..c9d007f957 100644 --- a/server/typescript/packages/migrate-ts/src/index.ts +++ b/server/typescript/packages/migrate-ts/src/index.ts @@ -17,7 +17,7 @@ export { export type { ExpectedSchemaWithProvenance, SchemaProvenance, SchemaBuildSettings } from "./expected-schema.js"; export { introspect, introspectPostgres, introspectSqlite } from "./introspect/index.js"; // rc.21 part B (N2): each declared origin.function, checked against pg_proc by `meta verify --db`. -export { checkDeclaredFunctions } from "./introspect/declared-functions.js"; +export { checkDeclaredFunctions, DECLARED_FUNCTION_CHECK_LIMITS } from "./introspect/declared-functions.js"; export { diff } from "./diff/index.js"; export { defaultConventions, efcoreConventions, resolveSchemaConventions, SCHEMA_CONVENTION_PRESETS, diff --git a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts index 1598717a6d..41b3657ae0 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -3,6 +3,11 @@ // load and codegen, so a wrong one would be hidden by that cast (a `numeric` result declared `int` // rounds). `meta verify --db` reads each declared function from `pg_proc` and refuses any whose // parameter or return types are not the declared ones. +// +// What it does not check (fix round 3, M2): a parameter or result whose column kind has no plain +// Postgres type name here — json/jsonb, arrays, an enum, a user-defined type — matches any type at +// that position (only the arity is checked there). A domain is not seen through: `format_type` +// names the domain, so a domain-typed parameter or result is reported as a mismatch. import type { Kysely } from "kysely"; import { sql } from "kysely"; @@ -34,6 +39,8 @@ interface DeclaredFunction { /** One overload as `pg_proc` has it, its types spelled by `format_type(oid, NULL)`. */ interface PgFunction { readonly args: readonly string[]; + /** How many trailing parameters have a default (`pronargdefaults`): a call may omit them. */ + readonly defaults: number; readonly returns: string; readonly retset: boolean; } @@ -120,16 +127,19 @@ export function declaredFunctions(root: MetaData): DeclaredFunction[] { } async function overloads(db: Kysely, schema: string, name: string): Promise { - const result = await sql<{ args: string[]; returns: string; retset: boolean }>` + const result = await sql<{ args: string[]; defaults: number; returns: string; retset: boolean }>` SELECT ARRAY(SELECT format_type(a.t, NULL) FROM unnest(p.proargtypes::oid[]) WITH ORDINALITY AS a(t, i) ORDER BY a.i) AS args, - format_type(p.prorettype, NULL) AS returns, p.proretset AS retset + p.pronargdefaults::int AS defaults, format_type(p.prorettype, NULL) AS returns, p.proretset AS retset FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${schema} AND p.proname = ${name} AND p.prokind = 'f'`.execute(db); - return result.rows.map((r) => ({ args: r.args, returns: r.returns, retset: r.retset })); + return result.rows.map((r) => ({ args: r.args, defaults: Number(r.defaults), returns: r.returns, retset: r.retset })); } function matches(declared: DeclaredFunction, fn: PgFunction): boolean { - if (fn.retset || fn.args.length !== declared.params.length) return false; + // A declared arity between the required count and the full count matches: the omitted + // trailing parameters take their defaults (fix round 3, M1). + const declaredCount = declared.params.length; + if (fn.retset || declaredCount > fn.args.length || declaredCount < fn.args.length - fn.defaults) return false; if (declared.returns.length > 0 && !declared.returns.includes(fn.returns)) return false; return declared.params.every((accepted, i) => accepted.length === 0 || accepted.includes(fn.args[i]!)); } @@ -138,6 +148,11 @@ function matches(declared: DeclaredFunction, fn: PgFunction): boolean { * The findings for every declared `origin.function` the Postgres database does not have with * the declared parameter and return types: one line each, empty when all match. */ +/** Printed under any finding: what the comparison does not see (fix round 3, M2). */ +export const DECLARED_FUNCTION_CHECK_LIMITS = + "origin.function signatures are compared by plain type name: a json, array, enum or user-defined " + + "kind is not type-checked (only the arity is), and a domain is compared by its own name, not its base type."; + export async function checkDeclaredFunctions(db: Kysely, root: MetaData): Promise { const findings: string[] = []; for (const declared of declaredFunctions(root)) { From 4d3ac9c0cafe4884fc069d1d2411c464281b7ef6 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 21:55:48 -0500 Subject: [PATCH 223/267] fix(views): an entity's computed field that reads itself is refused as a one-node cycle Codegen did not recurse on it; it read a column the derived field does not have, so the view failed at CREATE VIEW. The cycle pass now reports it (TS and C#). On a projection the same name is the base entity's field, so it stays legal. Co-Authored-By: Claude Opus 5.5 --- .../ViewVocabularyRc21LoaderTests.cs | 11 +++++++++++ .../csharp/MetaObjects/Loader/ValidationPasses.cs | 6 +++++- .../metadata/src/loader/validation-passes.ts | 8 +++++++- .../metadata/test/rc21b-view-vocabulary.test.ts | 13 +++++++++++++ 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index 73835cac22..6987db82bd 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -287,4 +287,15 @@ public void A_cycle_through_derived_function_arguments_is_refused_naming_the_pat """{ "field.long": { "name": "c", "children": [ { "origin.computed": { "@expr": { "fn": "coalesce", "args": [ { "field": "a" }, { "field": "id" } ] } } } ] } }""")); Assert.Empty(Load(Meter(FnField("a", "b"), FnField("b", "id")))); } + + // Fix round 3 (M3): on an entity, a computed field that reads its own name reads itself; on a + // projection that name is the base entity's field, so it is no cycle. + [Fact] + public void An_entity_computed_field_that_reads_itself_is_a_one_node_cycle() + { + Refused("ERR_INVALID_ORIGIN", "Meter.a: a derived field depends on itself through a → a", + Meter("""{ "field.long": { "name": "a", "children": [ { "origin.computed": { "@expr": { "fn": "coalesce", "args": [ { "field": "a" }, { "field": "id" } ] } } } ] } }""")); + Assert.DoesNotContain(Load(View(Computed("customerId", "long", Fn("coalesce", F("customerId"), F("id"))))), + e => e.Message.Contains("depends on itself", StringComparison.Ordinal)); + } } diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 21daa49382..418ae56202 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1791,6 +1791,10 @@ List Deps(MetaData f) { var origin = OriginOf(f); var names = new List(); + // A function naming itself in @args is refused by ValidateFunctionOrigin already. On an + // entity, a computed expression reading its own name reads itself: a one-node cycle, + // reported here (M3). On a projection that name is the base entity's field: no cycle. + var selfAllowed = origin?.SubType == ORIGIN_SUBTYPE_COMPUTED && obj.SubType != OBJECT_SUBTYPE_PROJECTION; if (origin?.SubType == ORIGIN_SUBTYPE_FUNCTION) { var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); @@ -1802,7 +1806,7 @@ List Deps(MetaData f) names.AddRange(ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Select(n => n.Split('.')[0])); } return names.Select(n => byName.TryGetValue(n, out var d) ? d : null) - .Where(d => d is not null && !ReferenceEquals(d, f) && OriginOf(d) is not null).Select(d => d!).ToList(); + .Where(d => d is not null && (selfAllowed || !ReferenceEquals(d, f)) && OriginOf(d) is not null).Select(d => d!).ToList(); } var done = new HashSet(ReferenceEqualityComparer.Instance); var reported = new HashSet(); diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 4594ceadc2..d835a3cdb9 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -2080,13 +2080,19 @@ export function validateDerivedCycles(root: MetaData): ParseError[] { const deps = (f: MetaData): MetaData[] => { const origin = originOf(f); const names: string[] = []; + // A function naming itself in @args is refused by _validateFunctionOrigin already. On an entity, + // a computed expression reading its own name reads itself: a one-node cycle, reported here (fix + // round 3, M3). On a projection that name is the base entity's field, so it is no cycle. + let selfAllowed = false; if (origin?.subType === ORIGIN_SUBTYPE_FUNCTION) { const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); for (const n of raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]) if (typeof n === "string") names.push(n); } else if (origin?.subType === ORIGIN_SUBTYPE_COMPUTED) { + selfAllowed = obj.subType !== OBJECT_SUBTYPE_PROJECTION; for (const n of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) names.push(n.split(".")[0]!); } - return names.map((n) => byName.get(n)).filter((d): d is MetaData => d !== undefined && d !== f && originOf(d) !== undefined); + return names.map((n) => byName.get(n)) + .filter((d): d is MetaData => d !== undefined && (selfAllowed || d !== f) && originOf(d) !== undefined); }; const done = new Set(); const reported = new Set(); diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts index e88493df7f..53f53731e3 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -192,6 +192,19 @@ describe("U10 — origin.function", () => { // A chain without a cycle loads. await ok(meter(fnField("a", "b"), fnField("b", "id")), meterRow); }); + // Fix round 3 (M3): on an entity, a computed field that reads its own name reads itself. + test("an entity's computed field that reads itself is a one-node cycle; on a projection the name is the base field", async () => { + const selfRef = { "field.long": { name: "a", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "a" }, { field: "id" } ] } } } ] } }; + await refused("ERR_INVALID_ORIGIN", /Meter\.a: a derived field depends on itself through a → a/, + { "object.entity": { name: "Meter", children: [ { "source.rdb": { "@table": "meters" } }, { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, selfRef ] } }, + { "object.projection": { name: "MeterRow", children: [ { "source.rdb": { "@kind": "view", "@table": "v_meter" } }, + { "field.long": { name: "id", extends: "Meter.id" } }, + { "field.long": { name: "a", children: [ { "origin.passthrough": { "@from": "Meter.a" } } ] } }, + { "identity.primary": { name: "id", extends: "Meter.id" } } ] } }); + // A projection field over the base field of the same name is no cycle. + await ok(orderView([computed("customerId", "long", { fn: "coalesce", args: [ { field: "customerId" }, { field: "id" } ] })])); + }); test("an unreached function field on an entity with no read source is refused", async () => { await refused("ERR_DERIVED_FIELD_NO_READ_SOURCE", /tier/, withFn({ "@function": "tier_of", "@args": ["id"], "@params": ["long"], "@returns": "string" })); }); From 9592cdc0c73122073263fff49a86511579dae18f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 22:06:14 -0500 Subject: [PATCH 224/267] chore(fixtures): the stage-summary procedure and the last case models are neutral fn_get_phase_summary(_per_case) and the generated names that spell it become a stage summary per consignment; the last Case entity in a codegen test, a plan and a doc comment follow. Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-05-20-schema-namespacing.md | 12 +++--- ...1-metamodel-batch-metadata-codegen-plan.md | 2 +- ...5-28-fr-015-source-parameter-ref-design.md | 22 +++++----- ...source-rdb-name-and-kind-aliases-design.md | 2 +- .../expected.json | 8 ++-- .../input/meta.demo.json | 8 ++-- .../expected.json | 8 ++-- .../input/meta.demo.json | 8 ++-- .../expected.json | 4 +- .../input/meta.demo.json | 4 +- .../Fr015CodegenTests.cs | 42 +++++++++---------- .../Generators/CallableGenerator.cs | 2 +- .../PackageBindingResolver.cs | 2 +- .../KotlinApiDocsSourceSelectionKtTest.kt | 24 +++++------ .../source/Fr016SourcePhysicalNameTest.java | 12 +++--- .../migrate-projection-kinds.test.ts | 6 +-- .../codegen-ts/src/templates/callable-file.ts | 14 +++---- .../callable-file-divergent-primary.test.ts | 8 ++-- .../test/golden/api-docs-accuracy.test.ts | 32 +++++++------- .../build-projection-views-kinds.test.ts | 4 +- .../test/reference-byte-identical.test.ts | 12 +++--- .../test/templates/callable-file.test.ts | 28 ++++++------- .../test/fr015-source-parameter-ref.test.ts | 8 ++-- ...fr016-source-name-and-kind-aliases.test.ts | 12 +++--- .../ADR-0018-per-kind-physical-name-attrs.md | 2 +- 25 files changed, 143 insertions(+), 143 deletions(-) diff --git a/docs/superpowers/plans/2026-05-20-schema-namespacing.md b/docs/superpowers/plans/2026-05-20-schema-namespacing.md index 4553805b4f..c000639954 100644 --- a/docs/superpowers/plans/2026-05-20-schema-namespacing.md +++ b/docs/superpowers/plans/2026-05-20-schema-namespacing.md @@ -844,11 +844,11 @@ Create `fixtures/conformance/source-db-table-with-schema/input/meta.demo.json`: "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ - { "source.dbTable": { "@name": "Cases", "@schema": "public" } }, + { "source.dbTable": { "@name": "Consignments", "@schema": "public" } }, { "field.long": { "name": "id" } }, - { "field.string": { "name": "caseNumber" } }, + { "field.string": { "name": "consignmentNumber" } }, { "identity.primary": { "@fields": "id" } } ] } @@ -867,11 +867,11 @@ Create `fixtures/conformance/source-db-table-with-schema/expected.json` with the "children": [ { "object.entity": { - "name": "Case", + "name": "Consignment", "children": [ - { "source.dbTable": { "@name": "Cases", "@schema": "public" } }, + { "source.dbTable": { "@name": "Consignments", "@schema": "public" } }, { "field.long": { "name": "id" } }, - { "field.string": { "name": "caseNumber" } }, + { "field.string": { "name": "consignmentNumber" } }, { "identity.primary": { "@fields": ["id"] } } ] } diff --git a/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md b/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md index edbbc09871..788a417864 100644 --- a/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md +++ b/docs/superpowers/plans/2026-05-31-metamodel-batch-metadata-codegen-plan.md @@ -174,7 +174,7 @@ The FR specifies how the **calling code** emits. It does NOT specify whether sto - **Opt-in:** an additive attribute `@exposeAsRoute: true` on `source.rdb` causes `routesFile` to emit a `POST /procs/` (or whatever path the project's `apiPrefix` + naming convention dictates) accepting the `@parameterRef` value-object as the request body, returning the projection array. - **Generator surfaces gated by `@exposeAsRoute: true`** (when set): - `server/typescript/packages/codegen-ts/src/generators/routesFile.ts` — Fastify POST handler. - - `server/typescript/packages/codegen-ts-tanstack/src/generators/tanstackQuery.ts` — `useGetPhaseSummaryPerCase(args)` hook (a `useQuery` wrapping the POST since the args are a body). + - `server/typescript/packages/codegen-ts-tanstack/src/generators/tanstackQuery.ts` — `useGetStageSummaryPerConsignment(args)` hook (a `useQuery` wrapping the POST since the args are a body). - `server/typescript/packages/codegen-ts/src/generators/entityFile.ts` — Zod schema for the parameter value-object (already covered by the value-object's existing codegen path — should be no-op). - `server/java/codegen-spring/ControllerGenerator.java` — Spring `@PostMapping` analog. - C# / Kotlin / Python equivalents. diff --git a/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md b/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md index 0b4b1aa755..9c9a2b1bcb 100644 --- a/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-015-source-parameter-ref-design.md @@ -30,7 +30,7 @@ Add one attribute, `@parameterRef`, to `source.rdb`'s attribute schema in `persi // 1. The input shape — an ordinary object.value with typed fields. // Fields may carry origin.passthrough to drift-protect against the entities they reference. { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { "name": "consignmentId", @@ -46,13 +46,13 @@ Add one attribute, `@parameterRef`, to `source.rdb`'s attribute schema in `persi // 2. The proc-backed entity references the input value-object via @parameterRef, // exactly as templates reference their payload via @payloadRef. { "object.entity": { - "name": "PhaseSummaryPerCase", + "name": "StageSummaryPerConsignment", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary_per_case", // see FR-016 / ADR-0018: kind-aware physical-name attr + "@proc": "fn_get_stage_summary_per_consignment", // see FR-016 / ADR-0018: kind-aware physical-name attr "@schema": "analytics", - "@parameterRef": "PhaseSummaryArgs" + "@parameterRef": "StageSummaryArgs" } }, // Return columns are ordinary fields, as today. { "field.long": { "name": "phaseId" } }, @@ -132,15 +132,15 @@ Some stored procedures (especially in legacy SQL Server / Oracle codebases) have ## Per-port codegen mapping -| Port | Emission for a `source.rdb @kind: "storedProc" @parameterRef: "PhaseSummaryArgs"` | +| Port | Emission for a `source.rdb @kind: "storedProc" @parameterRef: "StageSummaryArgs"` | |---|---| -| **TypeScript** | Method on the generated repo / service: `getPhaseSummaryPerCase(args: PhaseSummaryArgs): Promise`. The `PhaseSummaryArgs` type comes from the value-object's TS codegen. Drizzle: `sql.raw` wrapper helper. | -| **Java** | Spring repo method with `@Query(value = "{ call fn_get_phase_summary_per_case(:consignmentId, :asOfDate) }", nativeQuery = true)` and parameter binding driven by `PhaseSummaryArgs` field order. | -| **Kotlin** | Exposed `transaction { ... }` block with stored-function call wrapper; typed arguments via the `PhaseSummaryArgs` data class. | -| **C#** | EF Core: `context.PhaseSummaryPerCase.FromSqlInterpolated($"SELECT * FROM analytics.fn_get_phase_summary_per_case({args.ConsignmentId}, {args.AsOfDate})")` or a static helper on a `Procedures` partial. | -| **Python** | SQLAlchemy: `session.execute(text("SELECT * FROM analytics.fn_get_phase_summary_per_case(:consignment_id, :as_of_date)"), args.model_dump())`. Pydantic `PhaseSummaryArgs` validates inputs at call site. | +| **TypeScript** | Method on the generated repo / service: `getStageSummaryPerConsignment(args: StageSummaryArgs): Promise`. The `StageSummaryArgs` type comes from the value-object's TS codegen. Drizzle: `sql.raw` wrapper helper. | +| **Java** | Spring repo method with `@Query(value = "{ call fn_get_stage_summary_per_consignment(:consignmentId, :asOfDate) }", nativeQuery = true)` and parameter binding driven by `StageSummaryArgs` field order. | +| **Kotlin** | Exposed `transaction { ... }` block with stored-function call wrapper; typed arguments via the `StageSummaryArgs` data class. | +| **C#** | EF Core: `context.StageSummaryPerConsignment.FromSqlInterpolated($"SELECT * FROM analytics.fn_get_stage_summary_per_consignment({args.ConsignmentId}, {args.AsOfDate})")` or a static helper on a `Procedures` partial. | +| **Python** | SQLAlchemy: `session.execute(text("SELECT * FROM analytics.fn_get_stage_summary_per_consignment(:consignment_id, :as_of_date)"), args.model_dump())`. Pydantic `StageSummaryArgs` validates inputs at call site. | -Every port emits the `object.value` shape (`PhaseSummaryArgs`) as a native type per its existing object.value codegen path. **No new codegen mechanics are required** — both the value-object and the source-with-parameter-ref reuse already-shipped per-port pipelines. +Every port emits the `object.value` shape (`StageSummaryArgs`) as a native type per its existing object.value codegen path. **No new codegen mechanics are required** — both the value-object and the source-with-parameter-ref reuse already-shipped per-port pipelines. ## `migrate-ts` impact diff --git a/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md b/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md index 4e9d157c72..228a686d8f 100644 --- a/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md +++ b/docs/superpowers/specs/2026-05-28-fr-016-source-rdb-name-and-kind-aliases-design.md @@ -14,7 +14,7 @@ 2. **[ADR-0018](../../../spec/decisions/ADR-0018-per-kind-physical-name-attrs.md)** (issued alongside this FR) revises ADR-0007's choice of a universal `@table` within rdb to per-kind physical-name aliases — `@view` / `@materializedView` / `@proc` / `@function` for the non-table kinds. Same single internal slot; the canonical attr key matches the kind. Both gaps surface together when authoring stored-proc and view declarations: -- Reader sees `@table: "fn_get_phase_summary_per_case"` with `@kind: "storedProc"` and translates mentally that this isn't actually a table. +- Reader sees `@table: "fn_get_stage_summary_per_consignment"` with `@kind: "storedProc"` and translates mentally that this isn't actually a table. - Reader sees a `source.rdb` with no `name` attr and no way to disambiguate it from other sources on the same entity in error messages. This FR closes both gaps in one focused pass — same files, same registration points, same conformance corpus refresh. diff --git a/fixtures/conformance/parameter-ref-on-stored-proc/expected.json b/fixtures/conformance/parameter-ref-on-stored-proc/expected.json index a0740035e3..109fcda9e5 100644 --- a/fixtures/conformance/parameter-ref-on-stored-proc/expected.json +++ b/fixtures/conformance/parameter-ref-on-stored-proc/expected.json @@ -4,7 +4,7 @@ "children": [ { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { @@ -22,13 +22,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@parameterRef": "demo::PhaseSummaryArgs", - "@proc": "fn_get_phase_summary" + "@parameterRef": "demo::StageSummaryArgs", + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json b/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json index 98bf09ae8c..a9599a2bca 100644 --- a/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json +++ b/fixtures/conformance/parameter-ref-on-stored-proc/input/meta.demo.json @@ -4,7 +4,7 @@ "children": [ { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { @@ -22,13 +22,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", - "@parameterRef": "demo::PhaseSummaryArgs" + "@proc": "fn_get_stage_summary", + "@parameterRef": "demo::StageSummaryArgs" } }, { diff --git a/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json b/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json index 531884c187..4ba87977d7 100644 --- a/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json +++ b/fixtures/conformance/parameter-ref-with-origin-passthrough/expected.json @@ -29,7 +29,7 @@ }, { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { @@ -49,13 +49,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@parameterRef": "demo::PhaseSummaryArgs", - "@proc": "fn_get_phase_summary" + "@parameterRef": "demo::StageSummaryArgs", + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json b/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json index 2c8ddae04f..d747a0e2a8 100644 --- a/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json +++ b/fixtures/conformance/parameter-ref-with-origin-passthrough/input/meta.demo.json @@ -27,7 +27,7 @@ }, { "object.value": { - "name": "PhaseSummaryArgs", + "name": "StageSummaryArgs", "children": [ { "field.int": { @@ -47,13 +47,13 @@ }, { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", - "@parameterRef": "demo::PhaseSummaryArgs" + "@proc": "fn_get_stage_summary", + "@parameterRef": "demo::StageSummaryArgs" } }, { diff --git a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json index 0bab414a97..9e5d141e5c 100644 --- a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json +++ b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/expected.json @@ -4,12 +4,12 @@ "children": [ { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary" + "@proc": "fn_get_stage_summary" } }, { diff --git a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json index 0bab414a97..9e5d141e5c 100644 --- a/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json +++ b/fixtures/conformance/source-rdb-kind-proc-with-proc-attr/input/meta.demo.json @@ -4,12 +4,12 @@ "children": [ { "object.projection": { - "name": "PhaseSummary", + "name": "StageSummary", "children": [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary" + "@proc": "fn_get_stage_summary" } }, { diff --git a/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs index 1eaa02e029..b430a426aa 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Fr015CodegenTests.cs @@ -4,16 +4,16 @@ // method (one .callable.cs per callable entity). Per the FR-015 spec, the C# // emission uses EF Core FromSqlInterpolated when the names artifact is NOT in the run: // -// public static Task> Call(global::Acme.Generated.AppDbContext db, global::Acme.Analytics.PhaseSummaryArgs args) -// => db.Set() -// .FromSqlInterpolated($"SELECT * FROM analytics.fn_phase_summary({args.ConsignmentId}, {args.AsOfDate})") +// public static Task> Call(global::Acme.Generated.AppDbContext db, global::Acme.Analytics.StageSummaryArgs args) +// => db.Set() +// .FromSqlInterpolated($"SELECT * FROM analytics.fn_stage_summary({args.ConsignmentId}, {args.AsOfDate})") // .ToListAsync()...; // // and, when it IS (the default suite — §A6 / no-magic-physical-names), references the // procedure's name through FromSqlRaw, because an interpolation hole is a PARAMETER and an // identifier cannot be one: // -// .FromSqlRaw("SELECT * FROM " + global::Acme.Analytics.PhaseSummaryNames.SourcePrimarySchema + "." + global::Acme.Analytics.PhaseSummaryNames.SourcePrimaryProc + "({0}, {1})", args.ConsignmentId, args.AsOfDate) +// .FromSqlRaw("SELECT * FROM " + global::Acme.Analytics.StageSummaryNames.SourcePrimarySchema + "." + global::Acme.Analytics.StageSummaryNames.SourcePrimaryProc + "({0}, {1})", args.ConsignmentId, args.AsOfDate) // // Args bind in the @parameterRef value-object's field DECLARATION order on both arms. A // callable with no @parameterRef emits a zero-arg overload calling fn_x(). @@ -39,17 +39,17 @@ public class Fr015CodegenTests // storedProc entity (no @parameterRef). internal const string Model = """ { "metadata.root": { "package": "acme::analytics", "children": [ - { "object.value": { "name": "PhaseSummaryArgs", "children": [ + { "object.value": { "name": "StageSummaryArgs", "children": [ { "field.int": { "name": "consignmentId", "@required": true } }, { "field.timestamp": { "name": "asOfDate" } } ]}}, - { "object.projection": { "name": "PhaseSummary", "children": [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@schema": "analytics", "@parameterRef": "PhaseSummaryArgs" } }, + { "object.projection": { "name": "StageSummary", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@schema": "analytics", "@parameterRef": "StageSummaryArgs" } }, { "field.long": { "name": "phaseId" } }, { "field.string": { "name": "phaseName" } } ]}}, { "object.projection": { "name": "ActivePhases", "children": [ - { "source.rdb": { "@kind": "tableFunction", "@function": "fn_active_phases", "@parameterRef": "PhaseSummaryArgs" } }, + { "source.rdb": { "@kind": "tableFunction", "@function": "fn_active_phases", "@parameterRef": "StageSummaryArgs" } }, { "field.long": { "name": "phaseId" } } ]}}, { "object.projection": { "name": "AllPhases", "children": [ @@ -88,9 +88,9 @@ private static string Content(IEnumerable files, string path) => public void Source_ParameterRef_and_IsCallable_reflect_attrs() { var root = Load(); - var ps = root.FindObject("PhaseSummary")!.Sources()[0]; + var ps = root.FindObject("StageSummary")!.Sources()[0]; Assert.True(ps.IsCallable()); - Assert.Equal("acme::analytics::PhaseSummaryArgs", ps.ParameterRef); + Assert.Equal("acme::analytics::StageSummaryArgs", ps.ParameterRef); var plain = root.FindObject("Plain")!.Sources()[0]; Assert.False(plain.IsCallable()); @@ -103,25 +103,25 @@ public void Only_callable_entities_emit_a_callable_file() var files = Files(); var paths = files.Select(f => System.IO.Path.GetFileName(f.Path)).OrderBy(p => p, StringComparer.Ordinal).ToList(); Assert.Equal( - ["ActivePhases.callable.g.cs", "AllPhases.callable.g.cs", "PhaseSummary.callable.g.cs"], + ["ActivePhases.callable.g.cs", "AllPhases.callable.g.cs", "StageSummary.callable.g.cs"], paths); } [Fact] public void StoredProc_with_parameterRef_emits_FromSqlInterpolated_in_declaration_order() { - var c = Content(Files(), "PhaseSummary.callable.g.cs"); + var c = Content(Files(), "StageSummary.callable.g.cs"); // Method signature: db + the args value-object. - Assert.Contains("global::Acme.Generated.AppDbContext db, global::Acme.Analytics.PhaseSummaryArgs args", c); + Assert.Contains("global::Acme.Generated.AppDbContext db, global::Acme.Analytics.StageSummaryArgs args", c); // Returns the projection rows. - Assert.Contains("Task>", c); + Assert.Contains("Task>", c); // FromSqlInterpolated with schema-qualified proc name + args in declaration // order (consignmentId, asOfDate → ConsignmentId, AsOfDate). Assert.Contains( - "FromSqlInterpolated($\"SELECT * FROM analytics.fn_phase_summary({args.ConsignmentId}, {args.AsOfDate})\")", + "FromSqlInterpolated($\"SELECT * FROM analytics.fn_stage_summary({args.ConsignmentId}, {args.AsOfDate})\")", c); - Assert.Contains("db.Set()", c); + Assert.Contains("db.Set()", c); Assert.Contains("ToListAsync", c); } @@ -133,7 +133,7 @@ public void TableFunction_with_parameterRef_emits_unqualified_proc_name() Assert.Contains( "FromSqlInterpolated($\"SELECT * FROM fn_active_phases({args.ConsignmentId}, {args.AsOfDate})\")", c); - Assert.Contains("global::Acme.Generated.AppDbContext db, global::Acme.Analytics.PhaseSummaryArgs args", c); + Assert.Contains("global::Acme.Generated.AppDbContext db, global::Acme.Analytics.StageSummaryArgs args", c); } [Fact] @@ -170,20 +170,20 @@ private static IReadOnlyList NamesOnFiles() [Fact] public void NamesOn_references_the_constant_through_FromSqlRaw_including_the_schema() { - var c = Content(NamesOnFiles(), "PhaseSummary.callable.g.cs"); + var c = Content(NamesOnFiles(), "StageSummary.callable.g.cs"); // The identifier is text; each argument is a `{n}` placeholder → a DbParameter. // BOTH halves of the qualified name are constants now. The schema used to stay a // spelled literal here while the artifact's schema constant sat unread, justified by "schema // qualification is ruled on separately across the ports" — it has been ruled on, every // port qualifies, and this was the one C# site that qualified at all. Assert.Contains( - ".FromSqlRaw(\"SELECT * FROM \" + global::Acme.Analytics.PhaseSummaryNames.SourcePrimarySchema + \".\" + global::Acme.Analytics.PhaseSummaryNames.SourcePrimaryProc + \"({0}, {1})\", args.ConsignmentId, args.AsOfDate)", + ".FromSqlRaw(\"SELECT * FROM \" + global::Acme.Analytics.StageSummaryNames.SourcePrimarySchema + \".\" + global::Acme.Analytics.StageSummaryNames.SourcePrimaryProc + \"({0}, {1})\", args.ConsignmentId, args.AsOfDate)", c); Assert.DoesNotContain("FromSqlInterpolated", c); // The doc summary names it the same way the SQL does. - Assert.Contains("typed wrapper around the stored procedure named by PhaseSummaryNames.SourcePrimaryProc in schema PhaseSummaryNames.SourcePrimarySchema.", c); + Assert.Contains("typed wrapper around the stored procedure named by StageSummaryNames.SourcePrimaryProc in schema StageSummaryNames.SourcePrimarySchema.", c); // Neither physical name appears in the file — the proc name OR the schema. - Assert.DoesNotContain("fn_phase_summary", c); + Assert.DoesNotContain("fn_stage_summary", c); Assert.DoesNotContain("\"analytics", c); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs index 212c00bf6f..84f2669543 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs @@ -49,7 +49,7 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) var cls = CSharpNaming.Pascal(entity.Name); - // Schema-qualified physical proc/function name (e.g. analytics.fn_phase_summary). + // Schema-qualified physical proc/function name (e.g. analytics.fn_stage_summary). var physical = source.PhysicalName; var schemaPrefix = string.IsNullOrEmpty(source.Schema) ? "" : $"{source.Schema}."; var procName = $"{schemaPrefix}{physical}"; diff --git a/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs b/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs index 8ee2e96f6b..8422f0faa7 100644 --- a/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs +++ b/server/csharp/MetaObjects.Codegen/PackageBindingResolver.cs @@ -128,7 +128,7 @@ void Consider(MetaObjects.Meta.MetaObject? target) /// . /// /// The codegen config holding the convention + overrides. - /// Metadata package (e.g. acme::cases). Empty/null → fall through + /// Metadata package (e.g. acme::orders). Empty/null → fall through /// to the unmapped strategy (no overrides/convention apply to no-package). /// Optional named type within the package. When provided, enables the /// type-level override layer (typeOverrides["::"]). When null, only diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt index 9818a9f7a5..c2abf1c3db 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/codegen/kotlin/apidocs/KotlinApiDocsSourceSelectionKtTest.kt @@ -42,16 +42,16 @@ class KotlinApiDocsSourceSelectionKtTest { const val PROJECT = "apidocs-source-selection" } - // PhaseSummary declares its @role:replica VIEW source FIRST and its @role:primary + // StageSummary declares its @role:replica VIEW source FIRST and its @role:primary // STORED-PROC source SECOND. Both are read-only kinds, so nothing about the shape is // exotic beyond the declaration order, and it loads with zero errors. private val fixture = """{ "metadata.root": { "package": "acme::demo", "children": [ - { "object.projection": { "name": "PhaseSummary", "children": [ + { "object.projection": { "name": "StageSummary", "children": [ { "source.rdb": { "name": "replicaView", "@kind": "view", - "@table": "v_phase_summary", "@role": "replica" } }, + "@table": "v_stage_summary", "@role": "replica" } }, { "source.rdb": { "name": "primaryProc", "@kind": "storedProc", - "@proc": "fn_phase_summary", "@role": "primary" } }, + "@proc": "fn_stage_summary", "@role": "primary" } }, { "field.int": { "name": "id" } }, { "field.string": { "name": "label" } } ] } } @@ -95,7 +95,7 @@ class KotlinApiDocsSourceSelectionKtTest { @Test fun twoDistinctlyNamedSourcesBothSurviveOnChildren() { - val obj = loader.metaObjects.single { it.name.endsWith("::PhaseSummary") } + val obj = loader.metaObjects.single { it.name.endsWith("::StageSummary") } val sources = obj.getChildren(RdbSource::class.java, true) assertEquals( listOf("primaryProc", "replicaView"), @@ -109,11 +109,11 @@ class KotlinApiDocsSourceSelectionKtTest { // Ground truth: what the real generators actually wrote. Both select by role, so // the primary storedProc wins and the replica view contributes nothing. assertTrue( - Files.exists(outDir.resolve("acme/demo/PhaseSummaryProc.kt")), - "expected PhaseSummaryProc.kt; files=${Files.walk(outDir).toList()}", + Files.exists(outDir.resolve("acme/demo/StageSummaryProc.kt")), + "expected StageSummaryProc.kt; files=${Files.walk(outDir).toList()}", ) assertFalse( - Files.exists(outDir.resolve("acme/demo/PhaseSummaryTable.kt")), + Files.exists(outDir.resolve("acme/demo/StageSummaryTable.kt")), "the primary source is a storedProc, so no Exposed table object is emitted", ) } @@ -121,22 +121,22 @@ class KotlinApiDocsSourceSelectionKtTest { @Test fun theDocumentedDataAccessSymbolIsTheOneTheGeneratorsEmit() { val model = KotlinApiModelBuilder(com.metaobjects.generator.kotlin.Fr019SharedEnum.ProvidedEnumConfig.fromArgs(null)).build(loader, PROJECT) - val unit = model.units.single { it.node.endsWith("PhaseSummary") } + val unit = model.units.single { it.node.endsWith("StageSummary") } val dataAccess = unit.symbols.filter { it.kind == ApiSymbolKind.DATA_ACCESS } assertEquals( - listOf("PhaseSummaryProc"), + listOf("StageSummaryProc"), dataAccess.map { it.name }, "the docs must name the symbol the role-scoped generators emit, not the one the " + "first-DECLARED source would suggest", ) // ...and the symbol it names is really in the generated source. assertTrue( - "object PhaseSummaryProc" in allGenerated, + "object StageSummaryProc" in allGenerated, "the documented data-access symbol must exist in the generated Kotlin", ) assertFalse( - "PhaseSummaryTable" in allGenerated, + "StageSummaryTable" in allGenerated, "guards the inverse: the wrongly-documented symbol is emitted by nothing", ) } diff --git a/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java b/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java index 41961c5f8f..9b149e005f 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/source/Fr016SourcePhysicalNameTest.java @@ -188,10 +188,10 @@ public void step1KindMatchingViewForViewKind() { @Test public void step1KindMatchingProcForStoredProcKind() { MetaDataLoader l = loadThrough( - oneSourceEntity("PhaseSummary", - "{ \"@kind\": \"storedProc\", \"@proc\": \"fn_get_phase_summary\" }"), + oneSourceEntity("StageSummary", + "{ \"@kind\": \"storedProc\", \"@proc\": \"fn_get_stage_summary\" }"), "fr016-step1-proc.json"); - assertEquals("fn_get_phase_summary", firstSource(l).getPhysicalName()); + assertEquals("fn_get_stage_summary", firstSource(l).getPhysicalName()); } @Test @@ -216,10 +216,10 @@ public void step1KindMatchingFunctionForTableFunction() { public void step2LegacyTableForNonTableKind() { // Legacy: @table with non-table @kind still resolves (and emits a warning). MetaDataLoader l = loadThrough( - oneSourceEntity("PhaseSummary", - "{ \"@kind\": \"storedProc\", \"@table\": \"fn_legacy_phase_summary\" }"), + oneSourceEntity("StageSummary", + "{ \"@kind\": \"storedProc\", \"@table\": \"fn_legacy_stage_summary\" }"), "fr016-step2-legacy.json"); - assertEquals("fn_legacy_phase_summary", firstSource(l).getPhysicalName()); + assertEquals("fn_legacy_stage_summary", firstSource(l).getPhysicalName()); } @Test diff --git a/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts b/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts index 266429df40..659f769a9e 100644 --- a/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts +++ b/server/typescript/packages/cli/test/integration/migrate-projection-kinds.test.ts @@ -54,12 +54,12 @@ const META = JSON.stringify({ }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { name: "src", "@kind": "storedProc", - "@proc": "fn_phase_summary", "@parameterRef": "PhaseArgs", + "@proc": "fn_stage_summary", "@parameterRef": "PhaseArgs", }, }, { "field.long": { name: "phaseId" } }, @@ -130,7 +130,7 @@ describe("meta migrate — proc/matview projection kinds (real sqlite)", () => { expect(byName.get("v_programs")).toBe("view"); // …the matview is NOT silently created as a plain view, and the proc emits nothing. expect(byName.has("mv_program_stats")).toBe(false); - expect([...byName.keys()].some((n) => n.includes("fn_phase_summary"))).toBe(false); + expect([...byName.keys()].some((n) => n.includes("fn_stage_summary"))).toBe(false); // …and the STANDALONE read-model is left alone: hand-authored SQL, so migrate // neither creates nor drops it. The load-bearing assertion is `exit === 0` and // `programs` existing above — before the fix, this projection aborted the entire diff --git a/server/typescript/packages/codegen-ts/src/templates/callable-file.ts b/server/typescript/packages/codegen-ts/src/templates/callable-file.ts index 604550bb15..a9191ef79b 100644 --- a/server/typescript/packages/codegen-ts/src/templates/callable-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/callable-file.ts @@ -3,17 +3,17 @@ // // import { sql } from "drizzle-orm"; // import type { PgDatabase, PgQueryResultHKT } from "drizzle-orm/pg-core"; -// import type { PhaseSummaryArgs } from "./PhaseSummaryArgs.js"; -// import { PhaseSummarySchema, type PhaseSummary } from "./PhaseSummary.js"; +// import type { StageSummaryArgs } from "./StageSummaryArgs.js"; +// import { StageSummarySchema, type StageSummary } from "./StageSummary.js"; // -// export async function callPhaseSummary( +// export async function callStageSummary( // db: PgDatabase>, -// args: PhaseSummaryArgs, -// ): Promise { +// args: StageSummaryArgs, +// ): Promise { // const r = await db.execute( -// sql`SELECT * FROM fn_phase_summary(${args.consignmentId}, ${args.asOfDate})`, +// sql`SELECT * FROM fn_stage_summary(${args.consignmentId}, ${args.asOfDate})`, // ); -// return r.rows.map((row) => PhaseSummarySchema.parse(row)); +// return r.rows.map((row) => StageSummarySchema.parse(row)); // } // // Zero-argument procs (no @parameterRef) emit a no-args version that drops the diff --git a/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts b/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts index 357bdea74b..e62497d47a 100644 --- a/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts +++ b/server/typescript/packages/codegen-ts/test/callable-file-divergent-primary.test.ts @@ -84,16 +84,16 @@ describe("renderCallableFile — divergent primary sources", () => { const root = await loadClean([ { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { name: "procSrc", "@kind": "storedProc", "@proc": "phase_summary" } }, + { "source.rdb": { name: "procSrc", "@kind": "storedProc", "@proc": "stage_summary" } }, { "field.long": { name: "id" } }, ], }, }, ]); - const proj = root.children().find((c) => c.name === "PhaseSummary")! as MetaObject; + const proj = root.children().find((c) => c.name === "StageSummary")! as MetaObject; expect(isCallableEntity(proj)).toBe(true); - expect(renderCallableFile(proj)).toContain("phase_summary"); + expect(renderCallableFile(proj)).toContain("stage_summary"); }); }); diff --git a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts index c017bcaa2a..c47e29961c 100644 --- a/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts +++ b/server/typescript/packages/codegen-ts/test/golden/api-docs-accuracy.test.ts @@ -872,23 +872,23 @@ const T5_FIXTURE = JSON.stringify({ ], }, }, - // PhaseSummaryArgs — the @parameterRef value-object for the callable. + // StageSummaryArgs — the @parameterRef value-object for the callable. { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ { "field.long": { name: "consignmentId", "@required": true } }, { "field.string": { name: "asOfDate", "@required": true } }, ], }, }, - // PhaseSummary — a projection entity backed by a stored procedure → the - // callable generator emits callPhaseSummary(db, args): Promise. + // StageSummary — a projection entity backed by a stored procedure → the + // callable generator emits callStageSummary(db, args): Promise. { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseSummaryArgs" } }, + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@parameterRef": "StageSummaryArgs" } }, { "field.long": { name: "consignmentId" } }, { "field.string": { name: "phase" } }, ], @@ -944,7 +944,7 @@ describe("api-docs ACCURACY gate (T5) — relations / callable / prompt / Hono", model = buildApiModel(root, { outputLayout: "flat", loadedRoot: root, includeHonoRoutes: true }); expect(entityFiles.length).toBeGreaterThan(0); - // Exactly one callable entity in the fixture (PhaseSummary). + // Exactly one callable entity in the fixture (StageSummary). expect(callableFiles.length).toBe(1); // One aggregated prompts.ts. expect(promptFiles.length).toBe(1); @@ -1014,21 +1014,21 @@ describe("api-docs ACCURACY gate (T5) — relations / callable / prompt / Hono", // ----------------------------------------------------------------------- // CALLABLE: call in .callable.ts at the documented path. // ----------------------------------------------------------------------- - test("CALLABLE: callPhaseSummary documented + emitted at PhaseSummary.callable", () => { - const unit = model.units.find((u) => u.node === "PhaseSummary")!; + test("CALLABLE: callStageSummary documented + emitted at StageSummary.callable", () => { + const unit = model.units.find((u) => u.node === "StageSummary")!; const callable = unit.symbols.find((s) => s.kind === "callable"); - expect(callable, "PhaseSummary carries a callable symbol").toBeDefined(); - expect(callable!.name).toBe("callPhaseSummary"); + expect(callable, "StageSummary carries a callable symbol").toBeDefined(); + expect(callable!.name).toBe("callStageSummary"); - const f = fileFor(callableFiles, "PhaseSummary.callable.ts")!; + const f = fileFor(callableFiles, "StageSummary.callable.ts")!; expect(f, "callable file emitted").toBeDefined(); - expect(hasExportedFn(f.content, "callPhaseSummary")).toBe(true); - expect(callable!.importPath).toBe("PhaseSummary.callable"); + expect(hasExportedFn(f.content, "callStageSummary")).toBe(true); + expect(callable!.importPath).toBe("StageSummary.callable"); expect(`${callable!.importPath}.ts`).toBe(f.path); // Signature: takes the @parameterRef args VO + returns the projection array. - expect(callable!.signature).toContain("PhaseSummaryArgs"); - expect(callable!.returns).toBe("PhaseSummary[]"); + expect(callable!.signature).toContain("StageSummaryArgs"); + expect(callable!.returns).toBe("StageSummary[]"); }); test("CALLABLE inverse: a non-callable entity carries no callable symbol", () => { diff --git a/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts b/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts index 785609b48f..ed5978befe 100644 --- a/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/build-projection-views-kinds.test.ts @@ -61,9 +61,9 @@ const MODEL: unknown[] = [ }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseArgs" } }, + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@parameterRef": "PhaseArgs" } }, { "field.long": { name: "phaseId" } }, { "field.string": { name: "phaseName" } }, ], diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index d8685458a1..1381ac909b 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -989,7 +989,7 @@ const CALLABLE_MODEL = { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, @@ -999,9 +999,9 @@ const CALLABLE_MODEL = { { // A stored procedure taking typed arguments. "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ - { "source.rdb": { "@kind": "storedProc", "@proc": "fn_phase_summary", "@parameterRef": "PhaseSummaryArgs" } }, + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_stage_summary", "@parameterRef": "StageSummaryArgs" } }, { "field.long": { name: "phaseId" } }, { "field.string": { name: "phaseName" } }, ], @@ -1012,7 +1012,7 @@ const CALLABLE_MODEL = { "object.projection": { name: "OpenCase", children: [ - { "source.rdb": { "@kind": "tableFunction", "@function": "fn_open_cases" } }, + { "source.rdb": { "@kind": "tableFunction", "@function": "fn_open_consignments" } }, { "field.long": { name: "consignmentId" } }, ], }, @@ -1020,10 +1020,10 @@ const CALLABLE_MODEL = { { // An ordinary table: must emit no wrapper on either side. "object.entity": { - name: "Case", + name: "Consignment", children: [ { "field.long": { name: "id" } }, - { "source.rdb": { "@table": "cases" } }, + { "source.rdb": { "@table": "consignments" } }, { "identity.primary": { name: "pk", "@fields": ["id"] } }, ], }, diff --git a/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts b/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts index 977287189f..1388b89c7d 100644 --- a/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/callable-file.test.ts @@ -15,7 +15,7 @@ async function loadFirstEntity(doc: unknown) { new InMemoryStringSource(JSON.stringify(doc), { id: "demo.json" }), ]); if (errors.length > 0) throw new Error(`load errors: ${errors.map((e) => e.message).join("; ")}`); - const procEntity = root.objects().find((o) => o.name === "PhaseSummary")!; + const procEntity = root.objects().find((o) => o.name === "StageSummary")!; return { root, procEntity }; } @@ -27,7 +27,7 @@ describe("renderCallableFile", () => { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, @@ -36,13 +36,13 @@ describe("renderCallableFile", () => { }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_phase_summary", - "@parameterRef": "PhaseSummaryArgs", + "@proc": "fn_stage_summary", + "@parameterRef": "StageSummaryArgs", }, }, { "field.long": { name: "phaseId" } }, @@ -55,12 +55,12 @@ describe("renderCallableFile", () => { }); const out = renderCallableFile(procEntity); - expect(out).toContain("export async function callPhaseSummary"); - expect(out).toContain("args: PhaseSummaryArgs"); - expect(out).toContain("fn_phase_summary"); + expect(out).toContain("export async function callStageSummary"); + expect(out).toContain("args: StageSummaryArgs"); + expect(out).toContain("fn_stage_summary"); expect(out).toContain("args.consignmentId"); expect(out).toContain("args.asOfDate"); - expect(out).toContain("Promise"); + expect(out).toContain("Promise"); }); test("tableFunction with @parameterRef emits the same shape with the @function name", async () => { @@ -70,19 +70,19 @@ describe("renderCallableFile", () => { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [{ "field.int": { name: "id" } }], }, }, { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { "@kind": "tableFunction", "@function": "fn_phase_listing", - "@parameterRef": "PhaseSummaryArgs", + "@parameterRef": "StageSummaryArgs", }, }, { "field.long": { name: "id" } }, @@ -104,7 +104,7 @@ describe("renderCallableFile", () => { children: [ { "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { @@ -120,7 +120,7 @@ describe("renderCallableFile", () => { }, }); const out = renderCallableFile(procEntity); - expect(out).toContain("callPhaseSummary(db"); + expect(out).toContain("callStageSummary(db"); expect(out).not.toContain("args:"); expect(out).toContain("fn_ping()"); }); diff --git a/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts b/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts index 774cbbec72..0dec82de4f 100644 --- a/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts +++ b/server/typescript/packages/metadata/test/fr015-source-parameter-ref.test.ts @@ -51,7 +51,7 @@ describe("FR-015 happy paths", () => { children: [ { "object.value": { - name: "PhaseSummaryArgs", + name: "StageSummaryArgs", children: [ { "field.int": { name: "consignmentId", "@required": true } }, { "field.timestamp": { name: "asOfDate" } }, @@ -62,13 +62,13 @@ describe("FR-015 happy paths", () => { // FR-024 (B4b): proc-result shapes are object.projection (read-only, // external assembly); identity dropped (optional; no base entity here). "object.projection": { - name: "PhaseSummary", + name: "StageSummary", children: [ { "source.rdb": { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", - "@parameterRef": "PhaseSummaryArgs", + "@proc": "fn_get_stage_summary", + "@parameterRef": "StageSummaryArgs", }, }, { "field.long": { name: "phaseId" } }, diff --git a/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts b/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts index 0bbba79f5f..ff03728c97 100644 --- a/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts +++ b/server/typescript/packages/metadata/test/fr016-source-name-and-kind-aliases.test.ts @@ -188,12 +188,12 @@ describe("FR-016 MetaSource.physicalName — four-step resolution", () => { test("step 1: kind-matching @proc for storedProc kind", async () => { const s = await firstSource( - oneSourceEntity("PhaseSummary", { + oneSourceEntity("StageSummary", { "@kind": "storedProc", - "@proc": "fn_get_phase_summary", + "@proc": "fn_get_stage_summary", }), ); - expect(s.physicalName).toBe("fn_get_phase_summary"); + expect(s.physicalName).toBe("fn_get_stage_summary"); }); test("step 1: kind-matching @materializedView for materializedView kind", async () => { @@ -218,12 +218,12 @@ describe("FR-016 MetaSource.physicalName — four-step resolution", () => { test("step 2: legacy @table for non-table kind still resolves", async () => { const s = await firstSource( - oneSourceEntity("PhaseSummary", { + oneSourceEntity("StageSummary", { "@kind": "storedProc", - "@table": "fn_legacy_phase_summary", + "@table": "fn_legacy_stage_summary", }), ); - expect(s.physicalName).toBe("fn_legacy_phase_summary"); + expect(s.physicalName).toBe("fn_legacy_stage_summary"); }); test("step 3: derives from source's structural name when no alias is set (table kind)", async () => { diff --git a/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md b/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md index 4c5a8ec159..d3f1f99c43 100644 --- a/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md +++ b/spec/decisions/ADR-0018-per-kind-physical-name-attrs.md @@ -24,7 +24,7 @@ Where ADR-0007 made a separate, weaker choice was inside the `rdb` paradigm: it | TypeORM | `@Entity({ name })` | `@ViewEntity({ name })` | (raw SQL only) | | SQL standard | `CREATE TABLE` | `CREATE VIEW` | `CREATE PROCEDURE` / `CREATE FUNCTION` | -Zero of them call a non-table relation "table." The single-attr choice in ADR-0007 was a deviation from universal practice, made for internal-design simplicity at the cost of reader ergonomics. Metadata files in adopter projects would read `@table: "fn_get_phase_summary_per_case"` with `@kind: "storedProc"` — internally consistent but immediately disorienting to anyone scanning the source. +Zero of them call a non-table relation "table." The single-attr choice in ADR-0007 was a deviation from universal practice, made for internal-design simplicity at the cost of reader ergonomics. Metadata files in adopter projects would read `@table: "fn_get_stage_summary_per_consignment"` with `@kind: "storedProc"` — internally consistent but immediately disorienting to anyone scanning the source. The decision to revisit happens now because: 1. **No external adopters depend on `@table`-for-everything yet.** The cost of revising is bounded; the cost of shipping the smell to 1.0 is permanent. From 1997f152eb10cadbb8ad892cdac7e0937f99d5a4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 13 Nov 2026 22:53:13 -0500 Subject: [PATCH 225/267] chore(release): @metaobjectsdev TypeScript packages 1.2.2 --- CHANGELOG.md | 4 ++ bun.lock | 156 +++++++++++++++++++++++++++------------------------ 2 files changed, 88 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65ea81188b..9f23c0356c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ here.** ## [Unreleased] +## [1.2.2] — 2026-11-13 + +_npm `1.2.2` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ + _Proposed as npm `1.2.2` (all 14 `@metaobjectsdev/*` packages), NuGet `1.2.2` and Maven Central `8.2.2`; `1.2.1` was spent by the Python-only release. PyPI stays at `1.2.1`: no Python product file changes. No vocabulary or `metamodelVersion` change._ diff --git a/bun.lock b/bun.lock index 9def0b0bbb..e17b5343bf 100644 --- a/bun.lock +++ b/bun.lock @@ -468,23 +468,23 @@ "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], - "@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], + "@babel/core": ["@babel/core@7.29.13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.13", "@babel/helpers": "^7.29.13", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw=="], - "@babel/generator": ["@babel/generator@7.29.12", "", { "dependencies": { "@babel/parser": "^7.29.12", "@babel/types": "^7.29.11", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-2W76mhjrpQFO1lK5e8IvGYB2D0YZ7S2R1Z2BjO2ZUYuW+amcpK/z60U6ZZmzskwoa7sJ6XohP/Wg8H5KxXI/IA=="], + "@babel/generator": ["@babel/generator@7.29.14", "", { "dependencies": { "@babel/parser": "^7.29.14", "@babel/types": "^7.29.14", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g=="], "@babel/helper-annotate-as-pure": ["@babel/helper-annotate-as-pure@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw=="], - "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.7", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="], + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.13", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w=="], - "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@7.29.12", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/traverse": "^7.29.12", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-ACxGoWMV866q/QlZHeCOaQZAR5QclKsIvkAmlDemqjm6+6Bynijs1mH068BzH2N2e+wSuDmBWY87fqKfvhi1Lw=="], + "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@7.29.13", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", "@babel/traverse": "^7.29.13", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-fo8/Fr44/DMV71FQjk/HA0Npmu3bo5DFoWTCW1dhUR8Vx3NFfAVeEy0TbcBpt4e+hd2QhdmWgmspHo/9iWj8RA=="], "@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], - "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg=="], + "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@7.29.14", "", { "dependencies": { "@babel/helper-skip-transparent-expression-wrappers": "^7.29.13", "@babel/traverse": "^7.29.14", "@babel/types": "^7.29.14" } }, "sha512-FuTSn8mXKAP+aHXnbkCYQsQAdlEIJptEutwc2NaPd28hyVqsjRDmBnI2EPJX6HCodKIqOHfayQHqtxQCkqwthA=="], "@babel/helper-module-imports": ["@babel/helper-module-imports@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="], - "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.7", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="], + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.14", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.14" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA=="], "@babel/helper-optimise-call-expression": ["@babel/helper-optimise-call-expression@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong=="], @@ -492,17 +492,17 @@ "@babel/helper-replace-supers": ["@babel/helper-replace-supers@7.29.7", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ=="], - "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ=="], + "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@7.29.13", "", { "dependencies": { "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11" } }, "sha512-Abm4rKIH0tmCayJLwcoeOkdzpYUphTbO52fHhyEBHn7S0R+ni4epNLI/8nq1L0DN2Bl0u5qmgWm2Og/z4fBb+Q=="], - "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.11", "", {}, "sha512-snZbO7MEDOof+hvNa97EjEY7qD7h2kwvQr5AJC3ZhQudKW5dnej6k3kP9NQV88hJwaS8vDqRLFo9rivLEhle2g=="], + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.14", "", {}, "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ=="], "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], "@babel/helper-validator-option": ["@babel/helper-validator-option@7.29.7", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="], - "@babel/helpers": ["@babel/helpers@7.29.10", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.8" } }, "sha512-EMCx3AGZ3WfAl6ht7AyQoPm2Lh+BGYEMdc4Q6Hf7uSCDOZFuLq44qNwL+iaim8VlyYhRAo4X43+weadK8ZB4Yg=="], + "@babel/helpers": ["@babel/helpers@7.29.14", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.14" } }, "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ=="], - "@babel/parser": ["@babel/parser@7.29.12", "", { "dependencies": { "@babel/types": "^7.29.11" }, "bin": "./bin/babel-parser.js" }, "sha512-WJ7JBp/Q4+z/ImydtI7jS6NVco5++632ExBemSX+Ysb+G1lCwQ5BVo3SY+jGGOcZXI4ZccbZSUSJLNBW6eEpJg=="], + "@babel/parser": ["@babel/parser@7.29.14", "", { "dependencies": { "@babel/types": "^7.29.14" }, "bin": "./bin/babel-parser.js" }, "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w=="], "@babel/plugin-proposal-decorators": ["@babel/plugin-proposal-decorators@7.29.7", "", { "dependencies": { "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/plugin-syntax-decorators": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-EtU0Hi3GvrTqD56xKmZvV/uCXK2ZbwVNPNLAquVItcAZpUhkXwWlo3Fmj0c2LxgSf2I8IDULeAepwNP1OefLXg=="], @@ -512,23 +512,23 @@ "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="], - "@babel/plugin-transform-destructuring": ["@babel/plugin-transform-destructuring@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-iPX8aD6H9zV5s7ZsqTdNocPN/MGQ5sSMnElKrktxjJRMnB2jN/1p2+R7GkfD6CAYoVFqy5A4XnSIUeGgJzIWpg=="], + "@babel/plugin-transform-destructuring": ["@babel/plugin-transform-destructuring@7.29.13", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/traverse": "^7.29.13" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-X2meXB39NOPPmmshSRJzyd50hX9uCzbscNQwVCjLCtq363PZIJFFxJIeZPpgAewC570vpdeGIHTcltwd0QUlJg=="], "@babel/plugin-transform-explicit-resource-management": ["@babel/plugin-transform-explicit-resource-management@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/plugin-transform-destructuring": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-Rstj7coNz8sE+7Ju7ihpHLI564lsK5pUpNNlvptCIC/16E/S5hbl6n3kESPKdNRmqEWlpn5xpS5Q2dvXBsySLw=="], - "@babel/plugin-transform-modules-commonjs": ["@babel/plugin-transform-modules-commonjs@7.29.7", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ=="], + "@babel/plugin-transform-modules-commonjs": ["@babel/plugin-transform-modules-commonjs@7.29.14", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.14", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-mbv2yy5dqP6e3DbusCx+5AypXkFbyJD/JhG4/XhA+BIADOw5o7W+X0ewSp/h3w7gRL3oR5yny2/K8ljiydj4uA=="], "@babel/plugin-transform-typescript": ["@babel/plugin-transform-typescript@7.29.9", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/plugin-syntax-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-FFwIwzU+7SCOuxxV4YtJql6T9981ZVTm+FHO5GhVsRqCTdy0WwrEZh3l42ARpXruJUDGOptdduHW6Zr7pNPLNg=="], "@babel/preset-typescript": ["@babel/preset-typescript@7.28.5", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.27.1", "@babel/helper-validator-option": "^7.27.1", "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-transform-modules-commonjs": "^7.27.1", "@babel/plugin-transform-typescript": "^7.28.5" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-+bQy5WOI2V6LJZpPVxY+yp66XdZ2yifu0Mc1aP5CQKgjn4QM5IN2i5fAZ4xKop47pr8rpVhiAeu+nDQa12C8+g=="], - "@babel/runtime": ["@babel/runtime@7.29.10", "", {}, "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA=="], + "@babel/runtime": ["@babel/runtime@7.29.14", "", {}, "sha512-Y5tqevQaUAZhhj82BpYMNC1ssvLQTVAfwKdm8iy8qwmhvC2/CpcAu8OC+QEtjM7pMk7knx83u1Qj8gzkicyelw=="], "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], - "@babel/traverse": ["@babel/traverse@7.29.12", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.12", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.12", "@babel/template": "^7.29.7", "@babel/types": "^7.29.11", "debug": "^4.3.1" } }, "sha512-MscXe/NAZcOkYEsRajHZFt3ynsb22PUi6CTrp5U7+RYycR9By84mn9mFN54YgfITiqK4hFx3Ju3tZSyzfpS5ew=="], + "@babel/traverse": ["@babel/traverse@7.29.14", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.14", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.14", "@babel/template": "^7.29.7", "@babel/types": "^7.29.14", "debug": "^4.3.1" } }, "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA=="], - "@babel/types": ["@babel/types@7.29.11", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.11", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-WCsemW40Cpc6gouC1SrY6PBaZ+oLRlEVY9XBvZBI7il/HyUrb2nJ505wE1MHEFyDZNnrWDEuy4jL50WVHfTTSQ=="], + "@babel/types": ["@babel/types@7.29.14", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.14", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w=="], "@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="], @@ -580,7 +580,7 @@ "@csstools/css-tokenizer": ["@csstools/css-tokenizer@4.0.2", "", {}, "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw=="], - "@electric-sql/pglite": ["@electric-sql/pglite@0.5.13", "", {}, "sha512-4rZuxK1k07w6sSpJzjMri0B9+HuXuC7V9pxVB51pR0T9KPqXg6TD0mdaEwBA9rkcL4jdht4tGDf/wYzAiGhT7g=="], + "@electric-sql/pglite": ["@electric-sql/pglite@0.5.16", "", {}, "sha512-Nj8KcIsJL748W408U2N8q4+9IlONdpRIU8MJypIAAINMJ5nqKyqpX7Mgg/5XKkXiAib3AoZGR6hnJFlrlLBrcg=="], "@electric-sql/pglite-socket": ["@electric-sql/pglite-socket@0.1.3", "", { "peerDependencies": { "@electric-sql/pglite": "0.4.3" }, "bin": { "pglite-server": "dist/scripts/server.js" } }, "sha512-LAciWM0M1dCL8hlsxu2venbVZcdxema0BtDfpWYVqr+Y468UADw0pFWidhKw1M8sfJ8rdLT71tjMmnirf/IZRQ=="], @@ -598,7 +598,7 @@ "@fastify/error": ["@fastify/error@4.2.1", "", {}, "sha512-MYBumuIwP+5MIpXSyKm6/o1Eigcoij186lWUssX3LH5U8KWqU0ktZhzC4CErIX9EJeQeRGI+zJZQWakBlFbUcg=="], - "@fastify/fast-json-stringify-compiler": ["@fastify/fast-json-stringify-compiler@5.1.1", "", { "dependencies": { "fast-json-stringify": "^7.0.0" } }, "sha512-pyxRKk7UpUnnrztP9pF4+ZYxusEQ4LifTyzRdiXmyql1QezNHxO02D25MVU2o4kMeAMYWAjG6RKRlojgkbiDAw=="], + "@fastify/fast-json-stringify-compiler": ["@fastify/fast-json-stringify-compiler@5.2.0", "", { "dependencies": { "fast-json-stringify": "^7.3.0" } }, "sha512-LPTVA0w4oPITWHAvox9NgI1rDSrjUnjxX6QN5MCb9FY+HqvDsUmgLucbj9eQakqC8lYwO7UgkDPHEQLJNl9vtg=="], "@fastify/forwarded": ["@fastify/forwarded@3.1.2", "", {}, "sha512-89WiRG+hW3VQSfCwg4Hb8b43PeyEX15K5+lEfsZ4EUth/FyOjS/lv8HsVuswUNXWiSnxMGNouE/fq/0w3VumHQ=="], @@ -652,37 +652,37 @@ "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.33.5", "", { "os": "win32", "cpu": "x64" }, "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg=="], - "@inquirer/ansi": ["@inquirer/ansi@2.0.10", "", {}, "sha512-dwrc+1aqVZpHNkNDswXGtn1typ+Pxpo5FHZRyBw1le7onEJUkPUkYOY1FIFC1LvFMYUqqLuWBwElhAmencL7MQ=="], + "@inquirer/ansi": ["@inquirer/ansi@2.1.0", "", {}, "sha512-63GU5AD9KhNbWM0jlhHoMJTEFck2upFOPxHlnCKf3xYTV3rjTUUQfodihmTnfYQzMLS29oy8lK/gA1eJgu4bhA=="], - "@inquirer/checkbox": ["@inquirer/checkbox@5.2.8", "", { "dependencies": { "@inquirer/ansi": "^2.0.10", "@inquirer/core": "^12.0.6", "@inquirer/figures": "^2.0.10", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-NY/S1EalQhlonqhwwsarrcnkH7s9ByQuvjWYdk1jB2Gb9EPQJjKkhCTWjM3yQ0UpHaLm1XbIL89b+32G8rhO5w=="], + "@inquirer/checkbox": ["@inquirer/checkbox@5.3.0", "", { "dependencies": { "@inquirer/ansi": "^2.1.0", "@inquirer/core": "^12.1.0", "@inquirer/figures": "^2.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-3QQSO87A+JoRtOtjtsgX2enwTL+3+VBVrkUpdqrIxMOgn5+W5sE57PcCPAiNUIESHxV4Q6mNEGxq2xLmRa0/yw=="], - "@inquirer/confirm": ["@inquirer/confirm@6.3.5", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-BJ59BOyURiZiAxdr9AuRu38/k+rV+DcTIM2fUF/c/BXrab6H8zMZTTOl3LgkSJH96Xob2vOJxDiBkHiz32Xx2w=="], + "@inquirer/confirm": ["@inquirer/confirm@6.4.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-+DCZxrOF01Q/1SzTQkgycAQPS/Jf+Yol0h1P/MVmopukTsxGOu1h/LKqf30y0eHKFZYYrgUMVhGDhEbPmSPi9A=="], - "@inquirer/core": ["@inquirer/core@12.0.6", "", { "dependencies": { "@inquirer/ansi": "^2.0.10", "@inquirer/figures": "^2.0.10", "@inquirer/type": "4.2.1", "cli-width": "^4.1.0", "fast-wrap-ansi": "^0.2.0", "mute-stream": "^3.0.0", "signal-exit": "^4.1.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-5yxn2LsJ8Tu4ei2a+yNkmFRhM/cb+JMEsEs/AW6CCOnBnpMy4IjYiPMFyHtYq8weOmlTyqqCx40y0DsD7OsEPw=="], + "@inquirer/core": ["@inquirer/core@12.1.0", "", { "dependencies": { "@inquirer/ansi": "^2.1.0", "@inquirer/figures": "^2.1.0", "@inquirer/type": "4.3.0", "cli-width": "^4.1.0", "fast-wrap-ansi": "^0.2.0", "mute-stream": "^4.0.0", "signal-exit": "^4.1.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-6H7usRWw4Gdjgpaem10CA5MfZ/xoYPGyInriR1Xubqjv+SVo8LIJ1erpFxW5JgCza6VZVZiKLTko7RtUU3AQMg=="], - "@inquirer/editor": ["@inquirer/editor@5.3.6", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/external-editor": "^3.0.7", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-Z5SOeRC5VNkINfKN4rY8BSaYKb3GYi8iSEqZZRqogsE2GhBBToQ0Xw25SbI+4bcatLzU009mZ5d9EuJNiJuUCg=="], + "@inquirer/editor": ["@inquirer/editor@5.4.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/external-editor": "^3.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-L7vdCe4jnMpzhDisu1tAnr4WGvfPOVz+vNFXyIIL7O2Ycn/n90sn1ARvg+4cwzLf+us51BE/cX7uhnrLcal3+g=="], - "@inquirer/expand": ["@inquirer/expand@5.1.8", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-dMEnTkpLqzM/sbILwL7QJgx9iX5hoEM8+bh6shgwd9mYJamdOnth7y2mMaFd08Glj9AXEFKllWcGYyBqnJsHrA=="], + "@inquirer/expand": ["@inquirer/expand@5.2.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-AOp2KQk7QojUyWOP7VkqdBWmxLRaVH58wQMx3N4//P530EDtpVp1EWIjAJubx9ZohWS/UCEpIkA1TuiNki0iOA=="], - "@inquirer/external-editor": ["@inquirer/external-editor@3.0.7", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.2" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-enNqTJpojgISCG+a5acjnfJ02hcRTFUBVm8uXiCY40PRPZtSzFnNLskOTU+kDUUEODYma90syxuea1rRtUFh0Q=="], + "@inquirer/external-editor": ["@inquirer/external-editor@3.1.0", "", { "dependencies": { "chardet": "^2.1.1", "iconv-lite": "^0.7.2" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-27JAkF38nXqXaoveU28iA/+Z8nutnF8B3JsbdToPHn9WnkrsMtZ0/YoJ29YwbtFexYIo+tIy6ikMvTdHKjjmGA=="], - "@inquirer/figures": ["@inquirer/figures@2.0.10", "", {}, "sha512-51elrUJV3jZpvD0ygz8+U10Kc6+Lzqln+/tYmnbhy6jo5oXpE6hMCcv+OTBC0enwJXsb3JIuT3VtEinRNCSK2A=="], + "@inquirer/figures": ["@inquirer/figures@2.1.0", "", {}, "sha512-CR9u2PME23jxy2SOyTb117efwAAPm98Zr+LoWI+PiQ55D6U8Yeu/HyFTxwytKhPa6oxAGzdsm2Kg7oLS6B9z8w=="], - "@inquirer/input": ["@inquirer/input@5.1.9", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-2Vd5T7lTxfgJMpAd3aOu6bQpbUnCU7tBgvTQIZkP/7juJzmRmTM2t5XfOCuirFduWLTSJI/WZp32Cq1E01TVeg=="], + "@inquirer/input": ["@inquirer/input@5.2.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-sIUPnN2X7M+7dq3RUd+e9QRacYnM+6B+kSucwQgj5VC5Eo/f+CIr2NyPBumxsViI+wzfokkgop/3x3KfHxNyJw=="], - "@inquirer/number": ["@inquirer/number@4.2.6", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-22LnGGCDm1M/pKXxxF8n6ppr/1IztdsxqeqeBRUMTTNnJTkjIBiAkewiDM4u/gjtazj/FvZS+nk9AbO/vEcBFQ=="], + "@inquirer/number": ["@inquirer/number@4.3.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-xYkX4sPVgox0F7yQwpz/MByWjOGdLEf1pdjH+Lji2gAzSs2xezz5bN5YgS1n0tx9wo0mRhGvq1KJGtvDZ9XXcQ=="], - "@inquirer/password": ["@inquirer/password@5.2.5", "", { "dependencies": { "@inquirer/ansi": "^2.0.10", "@inquirer/core": "^12.0.6", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-0v0wLQA4uhWbybmdH6oPl7ooxCiymNylkvi2gCSc+mA5ZQB6QoJLVhoHq12T82lhozpp9fpMJnJkC1nJrU/A+A=="], + "@inquirer/password": ["@inquirer/password@5.3.0", "", { "dependencies": { "@inquirer/ansi": "^2.1.0", "@inquirer/core": "^12.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-KVqW4G/UbMK06uBN76xF89JKYC9YBWU7v+Kc2tUwMCO8pg3ASBr0HVabl1KaSqF94O2KiRu8aKx4EicN78PK+A=="], - "@inquirer/prompts": ["@inquirer/prompts@8.7.5", "", { "dependencies": { "@inquirer/checkbox": "^5.2.8", "@inquirer/confirm": "^6.3.5", "@inquirer/editor": "^5.3.6", "@inquirer/expand": "^5.1.8", "@inquirer/input": "^5.1.9", "@inquirer/number": "^4.2.6", "@inquirer/password": "^5.2.5", "@inquirer/rawlist": "^5.3.8", "@inquirer/search": "^4.3.6", "@inquirer/select": "^5.2.8" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-l/IWwC+QhOyXgxkZloOh+n5quGzc1m5ZawyzBmoizCZaxbJeLRdS3pStoqg/JVInJRXaG5aHMhjK6H6oYiBC9A=="], + "@inquirer/prompts": ["@inquirer/prompts@8.8.0", "", { "dependencies": { "@inquirer/checkbox": "^5.3.0", "@inquirer/confirm": "^6.4.0", "@inquirer/editor": "^5.4.0", "@inquirer/expand": "^5.2.0", "@inquirer/input": "^5.2.0", "@inquirer/number": "^4.3.0", "@inquirer/password": "^5.3.0", "@inquirer/rawlist": "^5.4.0", "@inquirer/search": "^4.4.0", "@inquirer/select": "^5.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-yYVT2Eo3mafb9tnU2Mr3+wh5wLCWyspExqVoPSMCIfBIn3ZUTE4IDfbCMbMgXaOH0tH+JZEhOtfczQhDzOjIGg=="], - "@inquirer/rawlist": ["@inquirer/rawlist@5.3.8", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-h+6Y4pPvYvuRbksn1kIBdD9tCYD+E468W5sIcVfLmoLP5IasnY0r33N+r+46ej/P8b2PCREjyKR+MnnfPGdTzg=="], + "@inquirer/rawlist": ["@inquirer/rawlist@5.4.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-x42wcy465GM5/mHNKBFdAJbLlLyzmYqr/DEa6F49nHpI+03EFwRCRKeLGQakx5XqZ4unc2yFuS78qAD4Rb0iFA=="], - "@inquirer/search": ["@inquirer/search@4.3.6", "", { "dependencies": { "@inquirer/core": "^12.0.6", "@inquirer/figures": "^2.0.10", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-JZj9ttkIvuaFQIc2oxsyqC1ad05WL02ku6W/INVKTCzNaVq1KkhP3AfTRC0m7OWlKZyw+EWwPBFZfYiG9jF6Yw=="], + "@inquirer/search": ["@inquirer/search@4.4.0", "", { "dependencies": { "@inquirer/core": "^12.1.0", "@inquirer/figures": "^2.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-UJ+9tkzPT1AjnvjuPFYcOdO3BVeN28bfSXajYRFZTRgA9OiNl4k2Nn2cHHPwiIDyPHlvOnmE9ZOHyXhPHtvb+A=="], - "@inquirer/select": ["@inquirer/select@5.2.8", "", { "dependencies": { "@inquirer/ansi": "^2.0.10", "@inquirer/core": "^12.0.6", "@inquirer/figures": "^2.0.10", "@inquirer/type": "4.2.1" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-BklkkAAOpjdCfuQw5fVGcDuhKxA7T1iBpn6b2JUvDDdkIsO3Ftlg+WnWUCVpkUBFagL2o036OFW+xL4lC9wIPw=="], + "@inquirer/select": ["@inquirer/select@5.3.0", "", { "dependencies": { "@inquirer/ansi": "^2.1.0", "@inquirer/core": "^12.1.0", "@inquirer/figures": "^2.1.0", "@inquirer/type": "4.3.0" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-Fmgfl0qjqCQo+/tjQpgnRXKh5N7/VpYcJh+AlYU2eHmHZLMGUBDzo+Gwc2ODzWJfXNRZmgaMhz4qULcO/C/rXg=="], - "@inquirer/type": ["@inquirer/type@4.2.1", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-lDkPsnv5M5CcYB2T1qTc3dobNTPkVr4DU3Ic2Q6SW8/qVRHgvzdRdmVZ6YqG9Ag1aJTeMsLU0s0WPRh3CZWDQQ=="], + "@inquirer/type": ["@inquirer/type@4.3.0", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-/IA8q2nyjgyl0NGSjqiRXB8gh3We7Pzx9C0c+6Zoolu905jFc79anerrUG7+n65+qs310DRK43yi2WDI8nY59A=="], "@isaacs/cliui": ["@isaacs/cliui@8.0.2", "", { "dependencies": { "string-width": "^5.1.2", "string-width-cjs": "npm:string-width@^4.2.0", "strip-ansi": "^7.0.1", "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", "wrap-ansi": "^8.1.0", "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" } }, "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA=="], @@ -690,7 +690,7 @@ "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], - "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.3", "", {}, "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g=="], "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], @@ -854,9 +854,9 @@ "@tanstack/angular-table": ["@tanstack/angular-table@8.21.4", "", { "dependencies": { "@tanstack/table-core": "8.21.3", "tslib": "^2.6.2" }, "peerDependencies": { "@angular/core": ">=17" } }, "sha512-djyuJFvIB/pBuBIqny8b7+5ozeXJSElaxYRZyyKLpYrXn4xQSysBT//X51eDT/mi3kS0spcjIHhoObjk3iCjcQ=="], - "@tanstack/query-core": ["@tanstack/query-core@5.105.0", "", {}, "sha512-7p56vRmT/z4UJ6sctGIdl5WRUQyUv53IUpUwEKi2g97zMbO7zh8ZsCLffGAvCPBR4xD72e3VXsDyLwXHhoNTMQ=="], + "@tanstack/query-core": ["@tanstack/query-core@5.107.1", "", {}, "sha512-PSyAik11oQBEVOiVy5hjZWHmoUqOXqK1WYy4v55mcxozEfKaQgpUMsgnXhWjuESzSht8JfzqMS1m6M/9CpNgvg=="], - "@tanstack/react-query": ["@tanstack/react-query@5.105.0", "", { "dependencies": { "@tanstack/query-core": "5.105.0" }, "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-y+hMuDERvgg6ay1da0V1a6ZC0ZONt7dELxSFkqRZuwm7p1TTZs0MoXrPlBRflIpRoYjvzQVYxycnLImpFLhWrw=="], + "@tanstack/react-query": ["@tanstack/react-query@5.107.1", "", { "dependencies": { "@tanstack/query-core": "5.107.1" }, "peerDependencies": { "@types/react": "^18 || ^19", "react": "^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-udCOOLp3ZAheUrIHLCe+ZZge6nr2ZUrGMSWcCuXsjY1Bf2JeeE09oxst97PILiCY6N8xo/7bIo3Hvz13zh06FA=="], "@tanstack/react-table": ["@tanstack/react-table@8.21.3", "", { "dependencies": { "@tanstack/table-core": "8.21.3" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww=="], @@ -974,7 +974,7 @@ "async": ["async@3.2.6", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="], - "async-lock": ["async-lock@1.4.1", "", {}, "sha512-Az2ZTpuytrtqENulXwO3GGv1Bztugx6TT37NIo7imr/Qo0gsYiGtSdBa2B6fsXhTpVZDNfu1Qn3pk531e3q+nQ=="], + "async-lock": ["async-lock@1.5.0", "", {}, "sha512-JgULma1mWaHlyJ67lvicyel5Cq+k55bXafE0gyvJBdHkH0vdE/IGGDF1glNyRInisNS6pZL2oho96S6Hw68kfQ=="], "atomic-sleep": ["atomic-sleep@1.0.0", "", {}, "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ=="], @@ -986,19 +986,21 @@ "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "bare-buffer": ["bare-buffer@3.7.2", "", {}, "sha512-kI35SYpVg0JCk+a+gkUEJZY39mt+g71y1NRwBrEj7SbxLnwngYYMf0T/kouYIujlJwelvPZ9TTbBCbCSPw059Q=="], + "bare-events": ["bare-events@2.9.2", "", { "peerDependencies": { "bare-abort-controller": "*" }, "optionalPeers": ["bare-abort-controller"] }, "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA=="], "bare-fs": ["bare-fs@4.8.4", "", { "dependencies": { "bare-events": "^2.5.4", "bare-path": "^3.0.0", "bare-stream": "^2.6.4", "bare-url": "^2.2.2", "fast-fifo": "^1.3.2" }, "peerDependencies": { "bare-buffer": "*" }, "optionalPeers": ["bare-buffer"] }, "sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ=="], - "bare-path": ["bare-path@3.1.2", "", {}, "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw=="], + "bare-path": ["bare-path@3.1.3", "", {}, "sha512-8r+FVU/o4zcFmpCDqbqAYhHHbtXPP+cyZKo7DRGRWc7OLlNs4TMaSQEpXL/sIdzyEG0M7RHw4B7xYMGrTc+qrg=="], "bare-stream": ["bare-stream@2.13.4", "", { "dependencies": { "b4a": "^1.8.1", "streamx": "^2.25.0", "teex": "^1.0.1" }, "peerDependencies": { "bare-abort-controller": "*", "bare-buffer": "*", "bare-events": "*" }, "optionalPeers": ["bare-abort-controller", "bare-buffer", "bare-events"] }, "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA=="], - "bare-url": ["bare-url@2.5.5", "", { "dependencies": { "bare-path": "^3.0.0" } }, "sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q=="], + "bare-url": ["bare-url@2.5.7", "", { "dependencies": { "bare-buffer": "^3.0.0", "bare-path": "^3.0.0" } }, "sha512-pWAiECRdNYPJAXYKVOb4HuTQedQyRjtGBUu86kO/vOt4GM7e45PghHXQ/Erm5NumaDSWNBzehIfpc768esW7gA=="], "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], - "baseline-browser-mapping": ["baseline-browser-mapping@2.11.34", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Aqr8mA1kIvyJ3UY5YAY7ib8LSo1DmDMbMnVqGPtsKW1LxaFQFwn9Eb3yvq2fUKJsRvaXjnAV7R5osqETapzNiA=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.37", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ=="], "bcrypt-pbkdf": ["bcrypt-pbkdf@1.0.2", "", { "dependencies": { "tweetnacl": "^0.14.3" } }, "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w=="], @@ -1008,7 +1010,7 @@ "bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="], - "brace-expansion": ["brace-expansion@5.0.12", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ=="], + "brace-expansion": ["brace-expansion@5.0.13", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ=="], "browserslist": ["browserslist@4.29.5", "", { "dependencies": { "baseline-browser-mapping": "^2.11.33", "caniuse-lite": "^1.0.30001819", "electron-to-chromium": "^1.5.464", "node-releases": "^2.0.60", "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" } }, "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ=="], @@ -1030,7 +1032,7 @@ "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], - "caniuse-lite": ["caniuse-lite@1.0.30001820", "", {}, "sha512-gfWD6MxqVCqAOwmODfZf7DchWvlrA+SRdNX7ceLfg3xRqe5ssjjpF7EgslC/0tiLiNTajdaNN/q8c/5u/7Gz8w=="], + "caniuse-lite": ["caniuse-lite@1.0.30001826", "", {}, "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA=="], "chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], @@ -1062,7 +1064,7 @@ "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], - "cookie": ["cookie@2.0.1", "", {}, "sha512-yuToqVvRrj6pfDXREyQAAv8SkAEk/8GS3jQRTiUMm66TVtBYmqQeoEjL2Lmq8Rpo6271vH76InTChTitEAm65w=="], + "cookie": ["cookie@2.0.2", "", {}, "sha512-SL0cVuEdETEp7pN0FuZb01toc3vnODEfVUCooxG1SJN0yIirh7JMb9X9bvfCFf0vzzbT68RdbKDHYTiWy7a7iw=="], "core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="], @@ -1090,7 +1092,7 @@ "d3-interpolate": ["d3-interpolate@3.0.1", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="], - "d3-path": ["d3-path@3.1.0", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="], + "d3-path": ["d3-path@3.1.1", "", {}, "sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg=="], "d3-scale": ["d3-scale@4.0.2", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="], @@ -1148,7 +1150,7 @@ "effect": ["effect@3.20.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw=="], - "electron-to-chromium": ["electron-to-chromium@1.5.468", "", {}, "sha512-8XdEp3sIqO+PzmVPxhzqHq/3+yCxp44m27cm2WY1sRn3ZhwKyKmqSi2hx6gEhmnOXmh8NUuYE00z6Onzn5m6DA=="], + "electron-to-chromium": ["electron-to-chromium@1.5.485", "", {}, "sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw=="], "elkjs": ["elkjs@0.11.1", "", {}, "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg=="], @@ -1158,7 +1160,7 @@ "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], - "entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="], + "entities": ["entities@9.0.0", "", {}, "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg=="], "env-paths": ["env-paths@3.0.0", "", {}, "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A=="], @@ -1192,7 +1194,7 @@ "fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="], - "fast-json-stringify": ["fast-json-stringify@7.2.0", "", { "dependencies": { "@fastify/merge-json-schemas": "^0.2.0", "ajv": "^8.12.0", "ajv-formats": "^3.0.1", "fast-uri": "^4.0.0", "json-schema-ref-resolver": "^3.0.0", "rfdc": "^1.2.0" } }, "sha512-q18imgm9fEdQVfvJbRJALE9VP/A5HGme0+NUnWcmFYM9rbQbLkZZk20FyIp1LQ8gDOauQKwqMc52YozqFaQyOw=="], + "fast-json-stringify": ["fast-json-stringify@7.3.5", "", { "dependencies": { "@fastify/merge-json-schemas": "^0.2.0", "ajv": "^8.12.0", "ajv-formats": "^3.0.1", "fast-uri": "^4.0.0", "json-schema-ref-resolver": "^3.0.0", "rfdc": "^1.2.0" } }, "sha512-g7H3xqJmdH9aWLWh8S3CqrRZFZ321yaeNHZp3QUDl3wtXDWjPChDXCDDTwA4M/zsU42nOhE+z5KmpCzgBaaCgw=="], "fast-querystring": ["fast-querystring@1.1.2", "", { "dependencies": { "fast-decode-uri-component": "^1.0.1" } }, "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg=="], @@ -1204,7 +1206,7 @@ "fast-wrap-ansi": ["fast-wrap-ansi@0.2.2", "", { "dependencies": { "fast-string-width": "^3.0.2" } }, "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q=="], - "fastify": ["fastify@5.12.7", "", { "dependencies": { "@fastify/ajv-compiler": "^4.0.5", "@fastify/error": "^4.0.0", "@fastify/fast-json-stringify-compiler": "^5.0.0", "@fastify/proxy-addr": "^5.0.0", "abstract-logging": "^2.0.1", "avvio": "^9.0.0", "fast-json-stringify": "^7.0.0", "find-my-way": "^9.6.0", "light-my-request": "^6.0.0", "pino": "^9.14.0 || ^10.1.0", "process-warning": "^5.1.0", "rfdc": "^1.3.1", "secure-json-parse": "^4.0.0", "semver": "^7.6.0", "toad-cache": "^3.7.0" } }, "sha512-v4pEPsTRPuqlDIYiQFB+BHjVN4SdHX9u0ABk0ZDUKbbdY1vsNryUd1j4Z+jQEZajvYIVk047Kimva9/AJ79GYw=="], + "fastify": ["fastify@5.12.8", "", { "dependencies": { "@fastify/ajv-compiler": "^4.0.5", "@fastify/error": "^4.0.0", "@fastify/fast-json-stringify-compiler": "^5.0.0", "@fastify/proxy-addr": "^5.0.0", "abstract-logging": "^2.0.1", "avvio": "^9.0.0", "fast-json-stringify": "^7.0.0", "find-my-way": "^9.10.0", "light-my-request": "^6.0.0", "pino": "^9.14.0 || ^10.1.0", "process-warning": "^5.1.0", "rfdc": "^1.3.1", "secure-json-parse": "^4.0.0", "semver": "^7.6.0", "toad-cache": "^3.7.0" } }, "sha512-moP8exb2sCHLUbJkwp+I6C0padhy4D8lp0SdmzY7HhSdZuqm7O/u3o2aq7u8okaQ//33QDzj3G/u+FsSdB8Qzw=="], "fastq": ["fastq@1.20.3", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw=="], @@ -1212,7 +1214,7 @@ "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], - "find-my-way": ["find-my-way@9.7.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ=="], + "find-my-way": ["find-my-way@9.10.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q=="], "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], @@ -1248,7 +1250,7 @@ "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], - "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + "graceful-fs": ["graceful-fs@4.2.12", "", {}, "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw=="], "grammex": ["grammex@3.1.13", "", {}, "sha512-LnPnhOBLEJEVKS8WFDVaA397L9Kq55Q9oSITJiVLHVdhAclfUkWzQv74KhvZHKL2Q09Pb1XdsrOsZ4LfTFFTEg=="], @@ -1262,7 +1264,7 @@ "highlight.js": ["highlight.js@11.12.0", "", {}, "sha512-nbfWpyRMcMrPMmDwJB+dhX/eiaPKtc2RB+0QZskqJ3WjRA/FDS0e9hZrx8EC/lbEv8gXy98FcDbNa/dspAaJMg=="], - "hono": ["hono@4.13.14", "", {}, "sha512-yhRLQ21U6qa9Hsu2N7Qcbh8tE+WKEcoErjIo56LeSGiGXGp9sA7UpE86Ui9uexb61KakiGwuHMn2QdV7w6i6kQ=="], + "hono": ["hono@4.13.18", "", {}, "sha512-H9q/E1XizaWstJxUW881dmLxEj+t/TrGGnyxINkm4+sK0qUwsMtFdo2BWI9Vs3cIS19MU6b6iCijoUoEf4f3DA=="], "html-encoding-sniffer": ["html-encoding-sniffer@6.0.0", "", { "dependencies": { "@exodus/bytes": "^1.6.0" } }, "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg=="], @@ -1302,7 +1304,7 @@ "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], - "js-base64": ["js-base64@3.9.5", "", {}, "sha512-u0CFDUca8BbBRkMkF/fDcuoLCx9nTNbXdVtbjVnBqySA9E221u0uYKbACiYGOEk1heY69qM4caeX3OwjSyxevw=="], + "js-base64": ["js-base64@3.9.6", "", {}, "sha512-LjkzbLtU6Lx6fjXMYGEACEB7rdtqZtxkBe9aS1ZpDNUyWgUivw3yBEIhQ37OVygJYRt+C+9e9fVT8PpFzH2Hww=="], "js-md4": ["js-md4@0.3.2", "", {}, "sha512-/GDnfQYsltsjRswQhN9fhv3EMw2sCpUdrdxyWDOUK7eyD++r3gRhzgiQgc/x4MAv2i1iuQ4lxO5mvqM3vj4bwA=="], @@ -1350,7 +1352,7 @@ "lz-string": ["lz-string@1.5.0", "", { "bin": { "lz-string": "bin/bin.js" } }, "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ=="], - "marked": ["marked@18.1.2", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-DfOnvLAQ6WYeWxWO1u4RyFOeqyHup6dks5PPqnoFiooU7ipRvidO/2j8plhAHIiZg574E9ZlzSjUiPMLAzFkgg=="], + "marked": ["marked@18.2.0", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-KaeL+tAbtvI930q7HE2PN5lYXYdT8EiSmxHlN6F3rsfb57wd5mp5W5TLazpdj4inTQBJdgjYwbs40W/0VUGU+Q=="], "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], @@ -1384,7 +1386,7 @@ "mutation-testing-report-schema": ["mutation-testing-report-schema@3.7.3", "", {}, "sha512-BHm3MYq+ckO+t5CtlG8zpqxc75rdJCkxVlE+fGuGJM3F7tNCQ/OW2N+TQVHN3BHsYa84+BFc6g3AwDYkUsw2MA=="], - "mute-stream": ["mute-stream@3.0.0", "", {}, "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw=="], + "mute-stream": ["mute-stream@4.0.0", "", {}, "sha512-gSrprq0fJ3EiOErzjdIZrjysVVmJ4uu1QWfCDss5LypA5OXvrMje5Ym5z6V6RLyJ2eF87lasX7t6a0AnFvZblg=="], "mysql2": ["mysql2@3.24.6", "", { "dependencies": { "aws-ssl-profiles": "^1.1.2", "generate-function": "^2.3.1", "iconv-lite": "^0.7.3", "long": "^5.3.2", "lru.min": "^1.1.4", "named-placeholders": "^1.1.6", "sql-escaper": "^1.5.1" }, "peerDependencies": { "@types/node": ">= 8" } }, "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ=="], @@ -1398,7 +1400,7 @@ "node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="], - "node-releases": ["node-releases@2.0.61", "", {}, "sha512-5NUN6QCxNFrS9oEA9RPS+d0AP+ooGBzzovY2JhIpDRHacPvOhHjXjUsUMX9qp4nLHZ+5jVgXB2jj/P4arGOE/g=="], + "node-releases": ["node-releases@2.0.64", "", {}, "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw=="], "normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="], @@ -1424,7 +1426,7 @@ "parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="], - "parse5": ["parse5@8.0.1", "", { "dependencies": { "entities": "^8.0.0" } }, "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw=="], + "parse5": ["parse5@8.1.1", "", { "dependencies": { "entities": "^9.0.0" } }, "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w=="], "path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], @@ -1516,9 +1518,9 @@ "react-dom": ["react-dom@19.3.1", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="], - "react-easy-crop": ["react-easy-crop@6.2.4", "", { "dependencies": { "normalize-wheel": "^1.0.1" }, "peerDependencies": { "react": ">=16.4.0", "react-dom": ">=16.4.0" } }, "sha512-OWdnFYctzUNlekjob+bQfloG9wyhIBkkmeISnM5XVE4Byqn0jmVxDF7oz85ovUF+EIPQyj0yAHbBEFtnxwGv4g=="], + "react-easy-crop": ["react-easy-crop@6.2.5", "", { "dependencies": { "normalize-wheel": "^1.0.1" }, "peerDependencies": { "@types/react": "*", "react": ">=16.4.0", "react-dom": ">=16.4.0" }, "optionalPeers": ["@types/react"] }, "sha512-NoJ+mtq7vNu6b77VDT1g4D3GXrhp5N4zKR0r63yUbQzbUkr6/aPibFXAOEzxZcHfUB2/R4KwxOU8g3eB7hnKjQ=="], - "react-hook-form": ["react-hook-form@7.91.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-5BEBUnCBwa28AFXYTYmOaB/+CSpJ/+CWVASHEvIGUzFdHyUiPHeRhG7r5hOZ8nZi0yP7pbHdFNXO/p31EKTJFQ=="], + "react-hook-form": ["react-hook-form@7.92.0", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-O5ILyY5fYHN7N13Pfxpe55KboyNFsJdM03BHpshQkClJd8raugiAUGY7VjifITrfhVxyx81ko25azXCoayhf1w=="], "react-is": ["react-is@17.0.2", "", {}, "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w=="], @@ -1562,9 +1564,9 @@ "secure-json-parse": ["secure-json-parse@4.1.1", "", {}, "sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw=="], - "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + "semver": ["semver@7.8.6", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw=="], - "set-cookie-parser": ["set-cookie-parser@3.2.1", "", {}, "sha512-Npd1Pt+4zb3BrSZDPd2qFwRpS6b1EUEasRrO8xS0zMJi0fApXXK5YuzP0minyJnxwnFHoVoJwA55q0A0cu63gQ=="], + "set-cookie-parser": ["set-cookie-parser@3.2.2", "", {}, "sha512-df017qMeYuXo4emL09nlyMpi2i2MtEIKS/6jtXH3vmjFgIRsOi852/5RmhJ4EkvN3ZF8jXadM/EkTPXgc8yPIw=="], "set-function-length": ["set-function-length@1.2.2", "", { "dependencies": { "define-data-property": "^1.1.4", "es-errors": "^1.3.0", "function-bind": "^1.1.2", "get-intrinsic": "^1.2.4", "gopd": "^1.0.1", "has-property-descriptors": "^1.0.2" } }, "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg=="], @@ -1634,17 +1636,17 @@ "text-decoder": ["text-decoder@1.2.7", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ=="], - "thread-stream": ["thread-stream@4.2.0", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ=="], + "thread-stream": ["thread-stream@4.2.1", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ=="], - "tldts": ["tldts@7.4.19", "", { "dependencies": { "tldts-core": "^7.4.19" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q=="], + "tldts": ["tldts@7.5.2", "", { "dependencies": { "tldts-core": "^7.5.2" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-p+JwEdxIWQx033pMvW9ULBbyC1Eg6JtWo2Mo0jbC8TVSjp2QrHFE+WKs8JpMGc3ECMsmBpU2RH/25NgX3k1ulg=="], - "tldts-core": ["tldts-core@7.4.20", "", {}, "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A=="], + "tldts-core": ["tldts-core@7.5.2", "", {}, "sha512-8W1topazDwhMKbm2I83IPa57Ow5VUxFgLbXv42+vSILnv8FY5OHvdEY/tS6WoWeMbxkHZQhra5cmeFHriKptSQ=="], "tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="], "toad-cache": ["toad-cache@3.7.4", "", {}, "sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg=="], - "tough-cookie": ["tough-cookie@6.0.2", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA=="], + "tough-cookie": ["tough-cookie@6.1.0", "", { "dependencies": { "tldts": "^7.0.5" } }, "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w=="], "tr46": ["tr46@6.0.0", "", { "dependencies": { "punycode": "^2.3.1" } }, "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw=="], @@ -1652,7 +1654,7 @@ "ts-poet": ["ts-poet@6.12.0", "", { "dependencies": { "dprint-node": "^1.0.8" } }, "sha512-xo+iRNMWqyvXpFTaOAvLPA5QAWO6TZrSUs5s4Odaya3epqofBu/fMLHEWl8jPmjhA0s9sgj9sNvF1BmaQlmQkA=="], - "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "tslib": ["tslib@2.9.1", "", {}, "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA=="], "tunnel": ["tunnel@0.0.6", "", {}, "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg=="], @@ -1734,15 +1736,15 @@ "zone.js": ["zone.js@0.15.1", "", {}, "sha512-XE96n56IQpJM7NAoXswY3XRLcWFW83xe0BiAOeMD7K5k5xecOeul3Qcpx6GqEeeHNkW5DWL5zOyTbEfB4eti8w=="], - "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/core/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], "@babel/generator/@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], "@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], - "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/helper-compilation-targets/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], - "@babel/helper-create-class-features-plugin/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + "@babel/helper-create-class-features-plugin/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], "@electric-sql/pglite-socket/@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="], @@ -1774,6 +1776,8 @@ "@prisma/dev/@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="], + "@prisma/dev/find-my-way": ["find-my-way@9.7.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ=="], + "@prisma/engines/@prisma/get-platform": ["@prisma/get-platform@7.10.1", "", { "dependencies": { "@prisma/debug": "7.10.1" } }, "sha512-iVnghHne5vcaobBjPVCMEjh5r/1UCj394EIGTUclasFRatpR/MQwcM2veLv5kgoFSyYP54nch/lNFCQRYcDxvg=="], "@prisma/fetch-engine/@prisma/get-platform": ["@prisma/get-platform@7.10.1", "", { "dependencies": { "@prisma/debug": "7.10.1" } }, "sha512-iVnghHne5vcaobBjPVCMEjh5r/1UCj394EIGTUclasFRatpR/MQwcM2veLv5kgoFSyYP54nch/lNFCQRYcDxvg=="], @@ -1782,10 +1786,18 @@ "@prisma/streams-local/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + "@stryker-mutator/api/tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "@stryker-mutator/core/tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@stryker-mutator/instrumenter/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="], + "@stryker-mutator/instrumenter/tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@visx/vendor/d3-array": ["d3-array@3.2.1", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-gUY/qeHq/yNqqoCKNq4vtpFLdoCdvyNpWoC/KNjhGbhDuQpAM9sIQQKkXSNpXa9h5KySs/gzm7R88WkUutgwWQ=="], + "@visx/vendor/d3-path": ["d3-path@3.1.0", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="], + "ajv/fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], "ajv-formats/ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], @@ -1816,7 +1828,7 @@ "jsdom/lru-cache": ["lru-cache@11.5.3", "", {}, "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg=="], - "jsdom/undici": ["undici@7.30.1", "", {}, "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg=="], + "jsdom/undici": ["undici@7.30.2", "", {}, "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA=="], "lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="], @@ -1858,7 +1870,7 @@ "@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="], - "@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.5.0", "", {}, "sha512-zhvbbbdt1kbw7EJ9OQoxmQcuaNR9P5kTj7e/YdmOSU10aHWbycofJxA6jKfoEy3vlLdctOF9ZHaxLtmSm998wQ=="], + "@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.6.0", "", {}, "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g=="], "@isaacs/cliui/wrap-ansi/ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], @@ -1880,7 +1892,7 @@ "fast-json-stringify/ajv/fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], - "glob/minimatch/brace-expansion": ["brace-expansion@2.1.7", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g=="], + "glob/minimatch/brace-expansion": ["brace-expansion@2.1.8", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-BnlDzDYQoplTsZSvPi86CNzmbcb07X8ufR8fk1zivaiEJlXJkiq1MQyDCVmlWcsWbj6aWXqHnrwwevbrm/Saig=="], "lazystream/readable-stream/isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="], @@ -1888,7 +1900,7 @@ "lazystream/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="], - "readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.7", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g=="], + "readdir-glob/minimatch/brace-expansion": ["brace-expansion@2.1.8", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-BnlDzDYQoplTsZSvPi86CNzmbcb07X8ufR8fk1zivaiEJlXJkiq1MQyDCVmlWcsWbj6aWXqHnrwwevbrm/Saig=="], "@libsql/kysely-libsql/@libsql/client/@libsql/hrana-client/@libsql/isomorphic-fetch": ["@libsql/isomorphic-fetch@0.2.5", "", {}, "sha512-8s/B2TClEHms2yb+JGpsVRTPBfy1ih/Pq6h6gvyaNcYnMVJvgQRY7wAa8U2nD0dppbCuDU5evTNMEhrQ17ZKKg=="], From 66f9601d271968d143fce8b709dbf64cf61df7a1 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 16:27:07 -0500 Subject: [PATCH 226/267] test(csharp): the 1.2.2 server-owned create tests find package-keyed files and the global:: List ServerOwnedCreateInputTests came from 1.2.2, where a generated file's path is its bare name. On this line a path is package-keyed (R39), and the merged M:N reset is spelled global::System.Collections.Generic.List, as every other emitted System reference here is. Co-Authored-By: Claude Opus 5.5 --- .../ServerOwnedCreateInputTests.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs index aba045fa26..1be5fb693e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs @@ -105,6 +105,11 @@ public class ServerOwnedCreateInputTests ]}} """; + // A generated file's path is package-keyed (R39: `acme/input/PostRoutes.g.cs`), so a file is + // found by its name, wherever its package puts it. + private static bool IsFile(string path, string file) => + path == file || path.EndsWith("/" + file, StringComparison.Ordinal); + private static string Emit(string model, string generator, string file) { var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "input.json")]); @@ -116,7 +121,7 @@ private static string Emit(string model, string generator, string file) Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal }, }; IGenerator g = generator == "routes" ? new RoutesGenerator() : new EntityGenerator(); - return g.Generate(ctx).Single(f => f.Path == file).Content; + return g.Generate(ctx).Single(f => IsFile(f.Path, file)).Content; } [Fact] @@ -125,7 +130,7 @@ public void Create_resets_a_generated_key_and_empties_navigations_before_Add() var src = Emit(PlainModel, "routes", "PostRoutes.g.cs"); var post = src[src.IndexOf("app.MapPost(", StringComparison.Ordinal)..]; var reset = post.IndexOf("input.Id = default!;", StringComparison.Ordinal); - var tags = post.IndexOf("input.Tags = new System.Collections.Generic.List();", StringComparison.Ordinal); + var tags = post.IndexOf("input.Tags = new global::System.Collections.Generic.List();", StringComparison.Ordinal); var add = post.IndexOf("db.Posts.Add(input);", StringComparison.Ordinal); Assert.True(reset >= 0 && tags >= 0 && add > reset && add > tags, post); } @@ -205,7 +210,7 @@ public void A_readOnly_key_and_readOnly_discriminator_get_no_reset_and_the_model .Concat(new FilterAllowlistGenerator().Generate(ctx)) .Concat(new RoutesGenerator().Generate(ctx)) .ToList(); - var routes = sources.Single(f => f.Path == "SealRoutes.g.cs").Content; + var routes = sources.Single(f => IsFile(f.Path, "SealRoutes.g.cs")).Content; var post = routes[routes.IndexOf("app.MapPost(", StringComparison.Ordinal)..]; Assert.DoesNotContain("input.Id = default!;", post); Assert.DoesNotContain("input.Kind = default!;", post); From de59161f5beb23dab1b6392dd3e58290b2d01bb7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 16:36:34 -0500 Subject: [PATCH 227/267] test(contract): the contract corpus follows 1.2.2's input rules Regenerated with gen:contract-conformance. 1.2.2's update schema leaves out every primary-key field, so the m2m junctions' update schemas are empty and openapi.json drops those properties; the secret-fields model gained a readOnly role, which is on the read schema and on neither write schema. Co-Authored-By: Claude Opus 5.5 --- .../m2m/expected/openapi.json | 77 ++----------------- .../acme/social/AccountTag.update.schema.json | 11 +-- .../acme/social/Follow.update.schema.json | 11 +-- .../acme/social/Friendship.update.schema.json | 11 +-- .../MemberAccountTag.update.schema.json | 11 +-- .../social/PostReviewer.update.schema.json | 11 +-- .../acme/social/PostTag.update.schema.json | 11 +-- .../ScopedAccountTag.update.schema.json | 11 +-- .../secret-fields/expected/openapi.json | 10 ++- .../schemas/acme/secrets/Account.schema.json | 10 ++- .../test/contract/contract-behaviours.test.ts | 3 +- 11 files changed, 34 insertions(+), 143 deletions(-) diff --git a/fixtures/contract-conformance/m2m/expected/openapi.json b/fixtures/contract-conformance/m2m/expected/openapi.json index 28d59f6255..813d6036ee 100644 --- a/fixtures/contract-conformance/m2m/expected/openapi.json +++ b/fixtures/contract-conformance/m2m/expected/openapi.json @@ -5030,16 +5030,7 @@ "AccountTagUpdate": { "title": "AccountTagUpdate", "type": "object", - "properties": { - "accountId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "ApiError": { "title": "ApiError", @@ -5126,16 +5117,7 @@ "FollowUpdate": { "title": "FollowUpdate", "type": "object", - "properties": { - "followerId": { - "type": "integer", - "format": "int64" - }, - "followeeId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "Friendship": { "title": "Friendship", @@ -5202,16 +5184,7 @@ "FriendshipUpdate": { "title": "FriendshipUpdate", "type": "object", - "properties": { - "personAId": { - "type": "integer", - "format": "int64" - }, - "personBId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "GuestAccount": { "title": "GuestAccount", @@ -5444,16 +5417,7 @@ "MemberAccountTagUpdate": { "title": "MemberAccountTagUpdate", "type": "object", - "properties": { - "accountId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "MemberAccountUpdate": { "title": "MemberAccountUpdate", @@ -5734,16 +5698,7 @@ "PostReviewerUpdate": { "title": "PostReviewerUpdate", "type": "object", - "properties": { - "postId": { - "type": "integer", - "format": "int64" - }, - "accountId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "PostTag": { "title": "PostTag", @@ -5810,16 +5765,7 @@ "PostTagUpdate": { "title": "PostTagUpdate", "type": "object", - "properties": { - "postId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "PostUpdate": { "title": "PostUpdate", @@ -5897,16 +5843,7 @@ "ScopedAccountTagUpdate": { "title": "ScopedAccountTagUpdate", "type": "object", - "properties": { - "accountId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} }, "Tag": { "title": "Tag", diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json index 8b7cec3207..b1176800e4 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/AccountTag.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/AccountTag.update.schema.json", "title": "AccountTag.update", "type": "object", - "properties": { - "accountId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json index bafa370de5..301ee27b86 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Follow.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/Follow.update.schema.json", "title": "Follow.update", "type": "object", - "properties": { - "followerId": { - "type": "integer", - "format": "int64" - }, - "followeeId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json index b7afbad306..f3fce52a55 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/Friendship.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/Friendship.update.schema.json", "title": "Friendship.update", "type": "object", - "properties": { - "personAId": { - "type": "integer", - "format": "int64" - }, - "personBId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json index 3ab529a36e..9f43d28345 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/MemberAccountTag.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/MemberAccountTag.update.schema.json", "title": "MemberAccountTag.update", "type": "object", - "properties": { - "accountId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json index 851406cef3..962ddd08a5 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostReviewer.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/PostReviewer.update.schema.json", "title": "PostReviewer.update", "type": "object", - "properties": { - "postId": { - "type": "integer", - "format": "int64" - }, - "accountId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json index 1eaac8f6fc..7387ae2891 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/PostTag.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/PostTag.update.schema.json", "title": "PostTag.update", "type": "object", - "properties": { - "postId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json index 28422b417b..fe3409645e 100644 --- a/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json +++ b/fixtures/contract-conformance/m2m/expected/schemas/acme/social/ScopedAccountTag.update.schema.json @@ -3,14 +3,5 @@ "$id": "schemas/acme/social/ScopedAccountTag.update.schema.json", "title": "ScopedAccountTag.update", "type": "object", - "properties": { - "accountId": { - "type": "integer", - "format": "int64" - }, - "tagId": { - "type": "integer", - "format": "int64" - } - } + "properties": {} } diff --git a/fixtures/contract-conformance/secret-fields/expected/openapi.json b/fixtures/contract-conformance/secret-fields/expected/openapi.json index b2cd08f362..5be082d05d 100644 --- a/fixtures/contract-conformance/secret-fields/expected/openapi.json +++ b/fixtures/contract-conformance/secret-fields/expected/openapi.json @@ -459,12 +459,20 @@ "null" ], "maxLength": 100 + }, + "role": { + "type": [ + "string", + "null" + ], + "maxLength": 20 } }, "required": [ "id", "name", - "tokenHash" + "tokenHash", + "role" ] }, "AccountCreate": { diff --git a/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json b/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json index e66a8f1d5b..0250ddfb7b 100644 --- a/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json +++ b/fixtures/contract-conformance/secret-fields/expected/schemas/acme/secrets/Account.schema.json @@ -18,11 +18,19 @@ "null" ], "maxLength": 100 + }, + "role": { + "type": [ + "string", + "null" + ], + "maxLength": 20 } }, "required": [ "id", "name", - "tokenHash" + "tokenHash", + "role" ] } diff --git a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts index 1a38ceee98..b771df0bd5 100644 --- a/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts +++ b/server/typescript/packages/codegen-ts/test/contract/contract-behaviours.test.ts @@ -249,7 +249,8 @@ describe("the three shapes", () => { const tree = await contractTree(corpusCase("secret-fields")); const keysOf = (path: string): string[] => Object.keys(jsonAt(tree, path)["properties"] as JsonDoc); const account = "schemas/acme/secrets/Account"; - expect(keysOf(`${account}.schema.json`)).toEqual(["id", "name", "tokenHash"]); + // `role` is the corpus's readOnly field (1.2.2): on the read, on neither write shape. + expect(keysOf(`${account}.schema.json`)).toEqual(["id", "name", "tokenHash", "role"]); expect(keysOf(`${account}.create.schema.json`)).toEqual(["name"]); expect(keysOf(`${account}.update.schema.json`)).toEqual(["name"]); expect(tree.get("openapi.json")).not.toContain("pinHash"); From 10f1f447448b57e3c7efd01f70423b9cb4a2144f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 14 Nov 2026 17:53:24 -0500 Subject: [PATCH 228/267] ci: mutate only the changed files in the gate's mutation step (#583) The ts-fast lane (and so --quick, --only ts and the no-mistakes Test step) ran the full Stryker pass over all six metadata files on every run: 10-45 minutes of CPU per gate round on a loaded host, most of that step's wall time. The step now diffs the stryker.conf.mjs `mutate` list against the merge base with the base branch (MO_CI_MUTATION_BASE, else origin/$GITHUB_BASE_REF, else whichever of origin/main and origin/release/* HEAD is closest to) and runs `stryker run --mutate` on only the changed files. When none changed it prints a SKIP naming the base. When no base resolves, or stryker.conf.mjs itself changed, it says so and runs the full pass. Thresholds and concurrency are unchanged; the list stays in stryker.conf.mjs only. The full pass stays: the flagless run's mutation lane, a new `--only mutation` section for release prep and on demand, and conformance.yml (tags, nightly, dispatch) via MO_CI_MUTATION_SCOPE=full. Stryker's sandbox goes under DEV_SCRATCH when that names a directory, and is removed afterwards. --- .github/workflows/conformance.yml | 4 + .github/workflows/local-ci.yml | 5 +- .no-mistakes.yaml | 8 +- scripts/ci-local.sh | 124 +++++++++++++++++++++++++++--- 4 files changed, 126 insertions(+), 15 deletions(-) diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml index e610f455df..d25a080c2c 100644 --- a/.github/workflows/conformance.yml +++ b/.github/workflows/conformance.yml @@ -18,6 +18,7 @@ name: conformance # gates — fixture-lint, doc-template drift, embedded-library drift, leak scan and # the other offline repo gates (`--only gates`) # ts-fast — workspace build + typecheck, TS conformance, completeness (mutation) gate +# (the FULL pass here: MO_CI_MUTATION_SCOPE=full on that job) # csharp / java-fast (java + kotlin) / python — each port's conformance corpora # java-reactor — full-reactor `mvn clean install`, tests on (`--only java-slow`) # The Java lanes point the script's Maven repository at ~/.m2/repository so setup-java's @@ -129,6 +130,9 @@ jobs: - name: Conformance (${{ matrix.lane }}) env: LANE: ${{ matrix.lane }} + # Tag, nightly and dispatch runs mutate EVERY stryker.conf.mjs file, not only the + # changed ones ts-fast mutates elsewhere (see gate_completeness_diff). + MO_CI_MUTATION_SCOPE: full run: | METAOBJECTS_CI_M2_REPO="$HOME/.m2/repository" \ scripts/ci-local.sh --only "$LANE" --no-integration --strict-toolchains diff --git a/.github/workflows/local-ci.yml b/.github/workflows/local-ci.yml index a7b82e8e11..490ba50626 100644 --- a/.github/workflows/local-ci.yml +++ b/.github/workflows/local-ci.yml @@ -116,8 +116,9 @@ jobs: # gate runs only named conformance FILES, so the rest of those suites ran nowhere # and a regression could sit red on `main` under a green ts lane. # Deliberately separate from ts-fast rather than folded into it: ts-fast carries - # the 30-min mutation gate, which flakes under runner contention, and a mutation - # flake must not mask a unit-test failure. The suites total ~5s, so this lane is + # the mutation gate (diff-scoped: on a push to main it mutates nothing new and + # SKIPs; the full pass runs in conformance.yml), which flaked under runner + # contention, and a mutation flake must not mask a unit-test failure. The suites total ~5s, so this lane is # nearly free and gives an independent, fast signal. ts-unit: needs: detect diff --git a/.no-mistakes.yaml b/.no-mistakes.yaml index 40c6045951..4653976392 100644 --- a/.no-mistakes.yaml +++ b/.no-mistakes.yaml @@ -11,8 +11,12 @@ # along the script's own `--only` section boundaries so neither step repeats the other. # `scripts/ci-local.sh --help` enumerates what each section contains, and # `MO_CI_LIST_ONLY=1 scripts/ci-local.sh --only
    ` prints its exact step list. -# Measured green on a warm tree 2026-09-18: test 256s (it carries the mutation gate and is -# almost all of the cost), lint 23s. +# Measured green on a warm tree 2026-09-18: test 256s, lint 23s. The test step's mutation +# gate is DIFF-SCOPED (gate_completeness_diff in the script): it mutates only the +# stryker.conf.mjs `mutate` files the branch changed against its base, and SKIPs when it +# changed none. Before 2026-11-14 it ran the full pass every round, 10-45 min under load +# and most of this step's wall time. The full pass is `--only mutation`, the flagless +# run's mutation lane, and conformance.yml (tags, nightly, dispatch). # # ORDER IS LOAD-BEARING, and it is why the work is split this way round rather than one # `--quick` in `test`. The pipeline runs test BEFORE lint. The `gates` section contains diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index 4e3a92a4c4..b23e236a52 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -21,7 +21,8 @@ # scripts/ci-local.sh --quick # FAST inner-loop tier: the cheap TS-centric # # gates only (leak-scan, pom parity, fixture- # # lint, ts build+typecheck, ts conformance, -# # completeness, drift). Skips the other- +# # completeness on the CHANGED files only, drift). +# # Skips the other- # # language ports, the reactor, and docker. # scripts/ci-local.sh --only
    [--only
    ...] # # Run one or more named sections. Mutually @@ -31,10 +32,23 @@ # # leak-scan → the public-repo leak scan ALONE # # (hygiene.yml's PR gate; also in gates) # # ts → ts build+typecheck, ts conformance, -# # completeness-gate, full unit suites +# # completeness-gate (changed files), +# # full unit suites # # (ts-unit), integration-tests ts # # ts-fast → build+typecheck, conformance, -# # completeness (the pure-code signal) +# # completeness (the pure-code signal). +# # Its mutation step mutates only the +# # stryker.conf.mjs `mutate` files this +# # change touches vs the base branch, and +# # prints a SKIP when it touches none +# # (MO_CI_MUTATION_SCOPE=full forces all; +# # MO_CI_MUTATION_BASE sets the base ref) +# # mutation → the FULL mutation pass over every +# # `mutate` file (~10-45 min). For release +# # prep and on demand; the flagless run +# # and conformance.yml also run it. It +# # replaces ts-fast's diff-scoped step +# # when both are selected # # ts-unit → full per-package unit suites for # # metadata/render/runtime-ts + the # # client/web packages — runs in @@ -136,8 +150,8 @@ while [ $# -gt 0 ]; do --no-integration) NO_INTEG=1 ;; --integration-only) INTEG_ONLY=1 ;; --only) shift; case "${1:-}" in - gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|java|java-fast|java-slow|python|csharp|cube) ONLY="$ONLY ${1}" ;; - *) echo "--only expects gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|java|java-fast|java-slow|python|csharp|cube, got '${1:-}'" >&2; exit 2 ;; + gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|mutation|java|java-fast|java-slow|python|csharp|cube) ONLY="$ONLY ${1}" ;; + *) echo "--only expects gates|leak-scan|ts|ts-fast|ts-unit|ts-slow|mutation|java|java-fast|java-slow|python|csharp|cube, got '${1:-}'" >&2; exit 2 ;; esac ;; -h|--help) awk 'NR==1{next} /^set -uo/{exit} {sub(/^# ?/,""); print}' "$0"; exit 0 ;; *) echo "unknown arg: $1 (see --help)" >&2; exit 2 ;; @@ -621,8 +635,9 @@ gate_conf_ts() { # conformance gate runs only NAMED conformance files in metadata/render, so the rest # of those suites (and runtime-ts + the client/web packages) ran nowhere — which is # how a @formExclude regression sat red on `main`. Deliberately its OWN lane rather -# than folded into ts-fast: ts-fast carries the 30-min mutation gate, which flakes -# under runner contention, and a mutation flake must not mask a unit-test failure. +# than folded into ts-fast: ts-fast carries the mutation gate (diff-scoped since +# 2026-11; the full pass took up to ~45 min and flaked under runner contention), and a +# mutation flake must not mask a unit-test failure. # Measured ~5s total, so the independent signal is nearly free. # NOTE: per-package `bun test` only — a bare root `bun test` walks java/python/ # csharp/fixtures and takes many minutes. @@ -769,7 +784,87 @@ gate_java_reactor() { # themselves (two concurrent `mvn install`s clobber the shared module jars). When the reactor # step is not selected — `--integration-only` — this installs it without its tests. gate_java_install() { ( cd server/java && mvn -q -DskipTests -Djacoco.skip=true install ); } -gate_completeness() { ( cd server/typescript/packages/metadata && bun run conformance:mutation ); } +# ── The mutation (completeness) gate: two scopes over ONE file list ─────────── +# Stryker mutates the files listed in `mutate` in server/typescript/packages/metadata/ +# stryker.conf.mjs — the ONLY copy of that list; both scopes read it from there. +# +# FULL (gate_completeness): every listed file. ~10–45 min of CPU on a contended host. +# Runs in the flagless full run's `mutation` lane, in `--only mutation` (release prep +# and on demand), and wherever MO_CI_MUTATION_SCOPE=full is set — conformance.yml does, +# so its tag (`v*`, the release gate), nightly and dispatch runs mutate everything. +# DIFF (gate_completeness_diff): only the listed files this change touches. This is +# the step in ts-fast / --quick / --only ts, and so in the no-mistakes gate's Test +# step (.no-mistakes.yaml). It used to run the full pass on every gate round, which +# was most of that step's wall time and most of the machine's load. +# +# "Touches" = differs between the merge base with the base branch and the working tree. +# The base is MO_CI_MUTATION_BASE when set, else origin/$GITHUB_BASE_REF on a GitHub PR, +# else whichever of origin/main and origin/release/* HEAD is fewest commits ahead of (a +# branch cut from release/1.2 diffs against release/1.2, not main). When no base resolves +# (a shallow checkout, no remote refs) the step says so and runs the FULL pass — it never +# guesses a smaller scope. A change to stryker.conf.mjs itself also runs the full pass. +# When none of the listed files changed it prints a SKIP banner naming the base and the +# reason, and passes: there is nothing new to mutate, and the full lane still covers the +# whole list. Thresholds and concurrency come from stryker.conf.mjs unchanged. +# +# Why --mutate on the diff rather than Stryker's incremental mode: incremental keeps a +# results file between runs, and a cache shared across branches and worktrees can report +# a mutant killed by tests another branch has. The diff scope keeps no state at all. +# +# Sandboxes: when DEV_SCRATCH names a directory (a RAM scratch area), Stryker's sandbox +# goes there instead of the package's .stryker-tmp/, and is removed when the step ends. +MUTATION_PKG="server/typescript/packages/metadata" +stryker_run() { # stryker_run [stryker args...] — in the metadata package, sandbox in DEV_SCRATCH when set + local tmp="" rc + if [ -n "${DEV_SCRATCH:-}" ] && [ -d "${DEV_SCRATCH}" ]; then + tmp="${DEV_SCRATCH%/}/stryker/metaobjects-$(printf '%s' "$ROOT" | cksum | cut -d' ' -f1)-$$" + mkdir -p "$tmp" || return 1 + fi + ( cd "$MUTATION_PKG" && bun run conformance:mutation ${tmp:+--tempDirName "$tmp"} "$@" ); rc=$? + [ -n "$tmp" ] && rm -rf "$tmp" + return "$rc" +} +gate_completeness() { bun_install || return 1; stryker_run; } +mutation_base() { # prints the base ref the diff scope compares against; empty when none resolves + local ref best="" best_n="" mb n + if [ -n "${MO_CI_MUTATION_BASE:-}" ]; then echo "$MO_CI_MUTATION_BASE"; return 0; fi + if [ -n "${GITHUB_BASE_REF:-}" ]; then echo "origin/$GITHUB_BASE_REF"; return 0; fi + for ref in origin/main $(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/release/*'); do + git rev-parse --verify -q "$ref^{commit}" >/dev/null 2>&1 || continue + mb="$(git merge-base HEAD "$ref" 2>/dev/null)" || continue + n="$(git rev-list --count "$mb..HEAD")" + if [ -z "$best_n" ] || [ "$n" -lt "$best_n" ]; then best="$ref"; best_n="$n"; fi + done + echo "$best" +} +gate_completeness_diff() { + if [ "${MO_CI_MUTATION_SCOPE:-diff}" = "full" ]; then + echo " mutation scope: FULL (MO_CI_MUTATION_SCOPE=full)"; gate_completeness; return + fi + local base mb files changed + base="$(mutation_base)" + if [ -z "$base" ] || ! mb="$(git merge-base HEAD "$base" 2>/dev/null)"; then + echo " mutation scope: FULL — no merge base with '${base:-origin/main or origin/release/*}' resolves here (shallow checkout or no remote refs), so the changed files cannot be computed" + gate_completeness; return + fi + files="$(cd "$MUTATION_PKG" && bun -e 'const c = (await import("./stryker.conf.mjs")).default; console.log(c.mutate.join("\n"))')" || { + echo " ✖ could not read the mutate list from $MUTATION_PKG/stryker.conf.mjs" >&2; return 1; } + if ! git diff --quiet "$mb" -- "$MUTATION_PKG/stryker.conf.mjs"; then + echo " mutation scope: FULL — stryker.conf.mjs changed since $base (merge base ${mb:0:12})" + gate_completeness; return + fi + # shellcheck disable=SC2086 # the mutate entries are plain paths, one per line + changed="$(cd "$MUTATION_PKG" && git diff --name-only --relative "$mb" -- $files)" + if [ -z "$changed" ]; then + echo "" + echo " ⊘ SKIP mutation: none of the $(echo "$files" | wc -l | tr -d ' ') files in stryker.conf.mjs 'mutate' changed since $base (merge base ${mb:0:12})." + echo " The full pass runs in the flagless run's mutation lane, in --only mutation, and in conformance.yml." + return 0 + fi + echo " mutation scope: changed files only, vs $base (merge base ${mb:0:12}):" + echo "$changed" | sed 's/^/ /' + stryker_run --mutate "$(echo "$changed" | paste -sd, -)" +} gate_doc_template_drift() { bash scripts/sync-doc-templates.sh \ && git diff --exit-code -- \ @@ -1090,7 +1185,8 @@ lane_ts() { if want ts; then step_if bun "conformance: typescript" gate_conf_ts; fi if want ts; then step_if bun "ts unit suites" gate_ts_unit; fi } -lane_mutation() { if want ts; then step_if bun "completeness-gate (mutation)" gate_completeness; fi; } +# The full run's mutation lane is the FULL pass over every file stryker.conf.mjs lists. +lane_mutation() { if want ts; then step_if bun "completeness-gate (mutation, full)" gate_completeness; fi; } # ts-slow's half: the two real-PG suites plus the TS integration suite. lane_ts_integ() { integ_ready || return 0 @@ -1188,13 +1284,19 @@ if [ "$PARALLEL" -eq 0 ]; then run_gates_bun # The ts port is split into two lanes so CI can run them as separate jobs (see # .github/workflows/local-ci.yml): a FAST lane (build+typecheck, conformance, - # completeness — the pure-code correctness signal, no docker) and a SLOW lane + # completeness on the changed files — the pure-code correctness signal, no docker) and a SLOW lane # (docker/sidecar integration). Isolating integration means a docker/sidecar # hiccup no longer fails the code signal, and vice versa. `--only ts` still runs both. if want_any ts ts-fast; then step_if bun "ts build + typecheck" gate_ts_build_typecheck; fi if want_any ts ts-fast; then step_if bun "conformance: typescript" gate_conf_ts; fi if want_any ts ts-unit; then step_if bun "ts unit suites" gate_ts_unit; fi - if want_any ts ts-fast; then step_if bun "completeness-gate (mutation)" gate_completeness; fi + # The DIFF-scoped mutation step (see gate_completeness_diff); `--only mutation` asks for + # the full pass instead, and gets it in place of this step rather than as well. + if [ -n "$ONLY" ] && want mutation; then + step_if bun "completeness-gate (mutation, full)" gate_completeness + elif want_any ts ts-fast; then + step_if bun "completeness-gate (mutation, changed files)" gate_completeness_diff + fi run_drift_gates if [ "$QUICK" -eq 1 ]; then From b9bc9c733228fa43a36fd8c8de7ac0142b747061 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sat, 14 Nov 2026 20:47:51 -0500 Subject: [PATCH 229/267] feat(codegen): skip gen when nothing changed, in every port (#585) * feat(codegen): skip gen when nothing changed, in every port (ADR-0062) - gen builds a key from the loaded model (each root node in canonical effective form, rolled up per package) plus the generators' identity (built engine code, config, owned generators, templates, declared extra inputs, project config, output-changing flags), before anything renders. When it matches the last successful run and every generated file still holds that run's bytes, gen renders and writes nothing. --force (Maven: -Dmetaobjects.force=true) turns it off; a generator that cannot declare its inputs opts out (cache: false or the port's equivalent). - verify --codegen always renders in CI; locally it may answer "no drift" from the key and the manifest, --full forces a render. When it renders, every port compares in memory: no rendered temp tree (Java/Kotlin now capture through GeneratedFileWriter). - The hash manifest is loaded once and written once per run, only when it changed (TypeScript, Python, C#). Identical bytes are never rewritten in any port. Python gen no longer reports unchanged files as written. - TypeScript runs git merge-file only for a file edited by hand, and deletes its temporaries in a finally, under $DEV_SCRATCH when set. - fixtures/codegen-skip-conformance/cases.json: 25 shared cases run by every port. * test(python): non-prompt targets rewrite nothing and save no manifest when unchanged Two targets, four generators: a forced run over unchanged output keeps every mtime and saves no manifest; a first run saves it once. Also corrects a stale comment in verify --codegen, which renders in memory. * no-mistakes(review): apply reviewer inline fixes * no-mistakes(review): Track unrecorded outputs in the skip key * no-mistakes(review): Track outside-root outputs in TS skip key * no-mistakes(review): Store no skip key after refused orphan sweep * no-mistakes(review): Hash YAML sources when docs-site is wired * no-mistakes(document): document gen skip and in-memory verify * no-mistakes(document): document gen skip in llms mirror * no-mistakes(lint): Update corpora count to 35 in site payload and AGENTS.md * test(agent-context): regenerate conformance expected copies The skill references in agent-context/ now describe verify --codegen as rendering in memory. Refresh the byte-for-byte expected mirrors to match. --- AGENTS.md | 2 +- CHANGELOG.md | 27 + .../metaobjects-audit/references/csharp.md | 2 +- .../metaobjects-audit/references/java.md | 2 +- .../metaobjects-audit/references/kotlin.md | 2 +- .../metaobjects-audit/references/python.md | 2 +- .../references/typescript.md | 2 +- .../metaobjects-codegen/references/python.md | 2 +- .../references/typescript.md | 4 +- .../references/capability-sheet.md | 2 +- docs/CONFORMANCE.md | 5 +- docs/features/cli.md | 30 +- docs/features/cube-export.md | 4 +- docs/features/own-your-codegen.md | 2 +- docs/llms/llms-full.txt | 9 +- docs/ports/csharp.md | 2 +- docs/ports/java.md | 2 +- .../generators/java/JsonSchemaGenerator.java | 2 +- docs/recipes/write-your-own-generator.md | 23 +- examples/showcase/site-payload.json | 2 +- .../metaobjects-audit/references/java.md | 2 +- .../metaobjects-audit/references/kotlin.md | 2 +- .../metaobjects-audit/references/java.md | 2 +- .../metaobjects-audit/references/python.md | 2 +- .../metaobjects-codegen/references/python.md | 2 +- .../references/typescript.md | 2 +- .../references/typescript.md | 4 +- .../references/typescript.md | 2 +- .../references/typescript.md | 4 +- fixtures/codegen-skip-conformance/README.md | 25 + fixtures/codegen-skip-conformance/cases.json | 156 +++++ .../GenSkipConformanceTests.cs | 269 +++++++++ .../OneGeneratorListTests.cs | 2 +- server/csharp/MetaObjects.Cli/Program.cs | 18 +- .../CodegenDriftTests.cs | 20 +- .../GenFingerprintUntrackedTests.cs | 46 ++ .../OrphanSweepTests.cs | 5 +- .../OverwriteHashManifestTests.cs | 31 + .../csharp/MetaObjects.Codegen/CodegenCli.cs | 59 +- .../MetaObjects.Codegen/CodegenDrift.cs | 105 ++-- .../MetaObjects.Codegen/CodegenRunner.cs | 150 +++-- .../MetaObjects.Codegen/GenFingerprint.cs | 352 ++++++++++++ .../csharp/MetaObjects.Codegen/Generator.cs | 20 + .../MetaObjects.Codegen/HashManifest.cs | 67 +++ .../csharp/MetaObjects.Codegen/ModelHash.cs | 62 ++ .../TemplateCodegen/TemplateSpecGenerator.cs | 4 + .../generator/FileEmittingGenerator.java | 3 +- .../com/metaobjects/generator/Generator.java | 20 + .../direct/MultiFileDirectGeneratorBase.java | 12 +- .../direct/SingleFileDirectGeneratorBase.java | 13 +- .../html/SingleHtmlDirectGeneratorBase.java | 4 +- .../json/SingleJsonDirectGeneratorBase.java | 4 +- .../javacode/JavaObjectCodeGenerator.java | 2 +- .../template/TemplateScopeGenerator.java | 7 +- .../generator/util/GeneratedFileWriter.java | 73 ++- .../util/GeneratedFileWriterTest.java | 88 +++ .../kotlin/KotlinRenderHelperGenerator.kt | 4 + .../mustache/MustacheTemplateGenerator.java | 15 +- .../spring/SpringRenderHelperGenerator.java | 6 + .../mojo/AbstractMetaDataMojo.java | 405 +++++++++++-- .../com/metaobjects/mojo/GenFingerprint.java | 225 ++++++++ .../mojo/MetaDataGeneratorMojo.java | 44 +- .../metaobjects/mojo/MetaDataVerifyMojo.java | 92 ++- .../java/com/metaobjects/mojo/ModelKey.java | 53 ++ .../DeclaresNothingWritesNothingTest.java | 2 + .../mojo/GenSkipConformanceTest.java | 398 +++++++++++++ .../mojo/RefusedOrphanSkipTest.java | 108 ++++ .../mojo/UnrecordedOutputSkipTest.java | 101 ++++ server/python/src/metaobjects/cli.py | 543 ++++++++++++++---- .../python/src/metaobjects/codegen/config.py | 10 + .../src/metaobjects/codegen/generator.py | 22 + .../src/metaobjects/codegen/model_key.py | 63 ++ .../metaobjects/codegen/overwrite_policy.py | 107 +++- .../python/src/metaobjects/codegen/runner.py | 54 +- server/python/src/metaobjects/codegen/skip.py | 428 ++++++++++++++ .../codegen/test_cli_verify_requirements.py | 7 +- .../tests/codegen/test_gen_unchanged.py | 231 ++++++++ .../python/tests/test_gen_skip_conformance.py | 350 +++++++++++ server/typescript/packages/cli/README.md | 1 + .../packages/cli/src/commands/gen.ts | 53 +- .../packages/cli/src/commands/verify.ts | 21 + server/typescript/packages/cli/src/index.ts | 10 + .../typescript/packages/cli/src/lib/args.ts | 11 + .../packages/cli/src/lib/codegen-drift.ts | 114 +--- .../packages/cli/src/lib/gen-collection.ts | 97 ++++ .../packages/cli/src/lib/gen-fingerprint.ts | 509 ++++++++++++++++ .../packages/cli/src/lib/gen-skip.ts | 38 ++ .../cli/src/lib/load-metaobjects-config.ts | 88 +-- .../packages/cli/test/gen-docs-site.test.ts | 18 + .../cli/test/gen-skip-conformance.test.ts | 370 ++++++++++++ .../advanced-modeling-drift.test.ts | 2 +- .../integration/eject-shared-model.test.ts | 16 +- .../packages/cli/test/unit/args-gen.test.ts | 5 + .../cli/test/unit/args-verify.test.ts | 10 +- .../cli/test/unit/config-resolver.test.ts | 4 +- .../packages/codegen-ts/src/generator.ts | 21 + .../src/generators/docs-site-file.ts | 4 + .../packages/codegen-ts/src/index.ts | 1 + .../packages/codegen-ts/src/model-hash.ts | 69 +++ .../codegen-ts/src/overwrite-policy.ts | 134 ++++- .../packages/codegen-ts/src/owned-runtime.ts | 5 +- .../packages/codegen-ts/src/runner.ts | 95 ++- .../overwrite-policy/manifest-once.test.ts | 123 ++++ server/typescript/packages/sdk/package.json | 5 + ...-0062-skip-codegen-when-nothing-changed.md | 119 ++++ spec/decisions/README.md | 1 + 106 files changed, 6381 insertions(+), 598 deletions(-) create mode 100644 fixtures/codegen-skip-conformance/README.md create mode 100644 fixtures/codegen-skip-conformance/cases.json create mode 100644 server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/GenFingerprintUntrackedTests.cs create mode 100644 server/csharp/MetaObjects.Codegen/GenFingerprint.cs create mode 100644 server/csharp/MetaObjects.Codegen/ModelHash.cs create mode 100644 server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java create mode 100644 server/java/maven-plugin/src/main/java/com/metaobjects/mojo/ModelKey.java create mode 100644 server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java create mode 100644 server/java/maven-plugin/src/test/java/com/metaobjects/mojo/RefusedOrphanSkipTest.java create mode 100644 server/java/maven-plugin/src/test/java/com/metaobjects/mojo/UnrecordedOutputSkipTest.java create mode 100644 server/python/src/metaobjects/codegen/model_key.py create mode 100644 server/python/src/metaobjects/codegen/skip.py create mode 100644 server/python/tests/codegen/test_gen_unchanged.py create mode 100644 server/python/tests/test_gen_skip_conformance.py create mode 100644 server/typescript/packages/cli/src/lib/gen-collection.ts create mode 100644 server/typescript/packages/cli/src/lib/gen-fingerprint.ts create mode 100644 server/typescript/packages/cli/src/lib/gen-skip.ts create mode 100644 server/typescript/packages/cli/test/gen-skip-conformance.test.ts create mode 100644 server/typescript/packages/codegen-ts/src/model-hash.ts create mode 100644 server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts create mode 100644 spec/decisions/ADR-0062-skip-codegen-when-nothing-changed.md diff --git a/AGENTS.md b/AGENTS.md index afc42a1358..def70bffcd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. - **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres. **Cross-port conformance corpora** (every port runs the shared corpus): -- Metamodel: `fixtures/conformance/` (421 fixtures; 34 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. +- Metamodel: `fixtures/conformance/` (421 fixtures; 35 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green. - Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical. - Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".) - API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f23c0356c..bbc93cadb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,33 @@ here.** ## [Unreleased] +### Changed + +- **`gen` skips rendering when nothing it is built from changed, in every port (ADR-0062).** + The skip key is computed after the metadata loads and before anything renders. Its model half + hashes each loaded root-level node in its canonical effective form (`extends` and overlays + applied), rolled up per package and for the model, so reformatting or splitting a metadata file + changes nothing while an edit to an inherited parent changes every child. Its generator half + hashes the built engine code, the codegen config and every owned generator, the template + roots, declared extra inputs, the project config and the output-changing flags. `gen` skips + when the key matches the last successful run and every generated file still has the bytes + that run left; a skipped run renders and writes nothing. The key is stored, uncommitted, in + `.metaobjects/.gen-state/.fingerprint-.json`. `--force` (`meta gen`, `metaobjects gen`, + `dotnet meta gen`; `-Dmetaobjects.force=true` on Maven) renders everything, and a generator + that cannot declare what it reads opts out with `cache: false` (or its port's equivalent). +- **`verify --codegen` may answer locally without rendering, and never writes a temp tree.** In + CI (`CI` set) it always renders and compares everything. Locally it answers "no drift" when the + key matches and every generated file still hashes to its record; `--full` + (`-Dmetaobjects.verify.full=true` on Maven) renders. When it renders, every port compares the + rendered bytes with disk in memory. +- **The hash manifest is written once per run, and only when an entry changed** (TypeScript, + Python and C#, matching Java and Kotlin). A file whose fresh bytes equal what is on disk is never + rewritten in any port, so its timestamp stays. Python `gen` no longer reports unchanged files + as written. +- **TypeScript runs `git merge-file` only for a file edited by hand since it was generated**, and + deletes the merge's temporary files in every case, under `$DEV_SCRATCH` when set. An untouched + file is overwritten directly. + ## [1.2.2] — 2026-11-13 _npm `1.2.2` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ diff --git a/agent-context/skills/metaobjects-audit/references/csharp.md b/agent-context/skills/metaobjects-audit/references/csharp.md index 0021f5894f..9d2168ca04 100644 --- a/agent-context/skills/metaobjects-audit/references/csharp.md +++ b/agent-context/skills/metaobjects-audit/references/csharp.md @@ -40,7 +40,7 @@ dotnet meta gen metaobjects --out Generated --namespace Acme.Generated dotnet meta gen --list # list all registered generators dotnet meta gen metaobjects --out Generated --generators entity # narrow to declared entries -dotnet meta verify --codegen # regenerate to temp, diff vs committed output +dotnet meta verify --codegen # regenerate in memory, diff vs committed output dotnet meta verify --templates # check {{field}} refs vs payload VO (bare default) ``` diff --git a/agent-context/skills/metaobjects-audit/references/java.md b/agent-context/skills/metaobjects-audit/references/java.md index fcd3818604..3aaa5b4ebc 100644 --- a/agent-context/skills/metaobjects-audit/references/java.md +++ b/agent-context/skills/metaobjects-audit/references/java.md @@ -36,7 +36,7 @@ goal bound to `generate-sources` in `pom.xml`. ```bash mvn metaobjects:generate # codegen goal directly mvn compile # also runs it (bound to generate-sources) -mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen to temp, diff vs committed output +mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen in memory, diff vs committed output mvn metaobjects:verify -Dmeta.verify.mode=templates # {{field}} refs vs payload VO ``` diff --git a/agent-context/skills/metaobjects-audit/references/kotlin.md b/agent-context/skills/metaobjects-audit/references/kotlin.md index 1928e36878..ee44432105 100644 --- a/agent-context/skills/metaobjects-audit/references/kotlin.md +++ b/agent-context/skills/metaobjects-audit/references/kotlin.md @@ -40,7 +40,7 @@ committed — confirm the plugin is wired and the goal bound to `generate-source ```bash mvn metaobjects:generate # codegen goal directly mvn compile # also runs it (bound to generate-sources) -mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen to temp, diff vs committed output +mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen in memory, diff vs committed output mvn metaobjects:verify -Dmeta.verify.mode=templates # {{field}} refs vs payload VO ``` diff --git a/agent-context/skills/metaobjects-audit/references/python.md b/agent-context/skills/metaobjects-audit/references/python.md index 47beec1afb..bb110ec191 100644 --- a/agent-context/skills/metaobjects-audit/references/python.md +++ b/agent-context/skills/metaobjects-audit/references/python.md @@ -38,7 +38,7 @@ directory structure beyond the target's `outDir`. ```bash metaobjects gen # run every target's generators (metaobjects.config.yaml) metaobjects gen --generators entity # narrow to declared entries -metaobjects verify --codegen # regenerate to temp, diff vs each committed outDir (bare default) +metaobjects verify --codegen # regenerate in memory, diff vs each committed outDir (bare default) metaobjects verify --templates # {{field}} refs vs payload VO ``` diff --git a/agent-context/skills/metaobjects-audit/references/typescript.md b/agent-context/skills/metaobjects-audit/references/typescript.md index 3fc99245c4..ecb64ba2cb 100644 --- a/agent-context/skills/metaobjects-audit/references/typescript.md +++ b/agent-context/skills/metaobjects-audit/references/typescript.md @@ -40,7 +40,7 @@ the default single-target config, generated files land at the one configured meta gen # render → 3-way merge → write (overwrites @generated files only) meta gen --dry-run # preview without writing meta gen Author Post # scope to named entities -meta verify --codegen # regenerate to temp, diff vs committed output +meta verify --codegen # regenerate in memory, diff vs committed output meta verify --templates # check {{field}} refs vs payload VO (a bare `meta verify` runs this and `--codegen`) meta verify --db # schema drift — live DB vs metadata (requires DB connection) meta verify --codegen --templates --db # all three drift checks in one pass diff --git a/agent-context/skills/metaobjects-codegen/references/python.md b/agent-context/skills/metaobjects-codegen/references/python.md index cb785d6624..9c73346741 100644 --- a/agent-context/skills/metaobjects-codegen/references/python.md +++ b/agent-context/skills/metaobjects-codegen/references/python.md @@ -61,7 +61,7 @@ the config's `templates` is refused. ```bash metaobjects gen # runs every target's generators into its outDir metaobjects gen --generators entity # narrow to declared entries (never adds one) -metaobjects verify --codegen # regenerate the same list into a temp dir + diff +metaobjects verify --codegen # regenerate the same list in memory + diff ``` With no `metaobjects.config.yaml`, `gen` and `verify --codegen` exit 2 and write nothing. diff --git a/agent-context/skills/metaobjects-codegen/references/typescript.md b/agent-context/skills/metaobjects-codegen/references/typescript.md index 0765fafc56..e9eccf9687 100644 --- a/agent-context/skills/metaobjects-codegen/references/typescript.md +++ b/agent-context/skills/metaobjects-codegen/references/typescript.md @@ -162,8 +162,8 @@ Some ejectable entries behave differently from the rest: every consumer. In an owned generator, read the project's own files through `ctx.inputRoot`. Under -`meta verify --codegen` the run writes into a temporary tree and `ctx.projectRoot` is that -tree; under a plain `meta gen` it is the directory that holds `metaobjects.config.ts`. +`meta verify --codegen` the run renders in memory; `ctx.projectRoot` is the real project root, +the directory that holds `metaobjects.config.ts`, as it is under a plain `meta gen`. **`requirementTests()` — one test stub per requirement the model claims.** A recommended approach, not a contract: a `live` or `partial` requirement gets a stub that fails until diff --git a/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md b/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md index 8d355c0077..1c10c527ae 100644 --- a/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md +++ b/agent-context/skills/metaobjects-fit-assessment/references/capability-sheet.md @@ -25,7 +25,7 @@ building block. Every generator is a reference helper an adopter selects, ejects type and nothing else: no table, no migration, no routes (#248; `docs/features/libraries.md`). A TypeScript model of only value objects and sourceless projections needs no `dialect` (`server/typescript/packages/codegen-ts/src/db-emitting.ts`). -- **The drift gate per port** — regenerate into a temp tree and diff: `meta verify --codegen` +- **The drift gate per port** — regenerate in memory and diff: `meta verify --codegen` (TS); `mvn metaobjects:verify` (Java/Kotlin; `codegen` is the default mode); `dotnet meta verify --codegen` (C#; bare `verify` runs it when `csharp.outDir` (or `--out`) and `codegen/Generators.cs` are present); `metaobjects verify` (Python; `--codegen` is part of the default). Source: `docs/features/cli.md`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index b464a464a5..bef8055dfb 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -1,6 +1,6 @@ # Conformance coverage -The MetaObjects standard ships **34 shared conformance corpora** under +The MetaObjects standard ships **35 shared conformance corpora** under [`fixtures/`](../fixtures/). Every port runs every corpus that is *applicable to it* and asserts the same expected behaviour against the same fixtures. **This page is the inverse index**: fixture → feature doc + per-port pass status, and it is the @@ -58,6 +58,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/requirement-test-identity-conformance/`](../fixtures/requirement-test-identity-conformance/) (the identity, skip state and digest of each generated requirement test, and the filter seam, ADR-0057) | 26 cases | ✓ (reference) | ✓ | identity function inherits via Java; emitted names asserted by its own generator test | ✓ | ✓ | | [`fixtures/naming-conformance/`](../fixtures/naming-conformance/) | 8 cases | ✓ | ✓ | inherits via Java (`RouteNaming.pluralize`) | ✓ | ✓ | | [`fixtures/wire-conformance/`](../fixtures/wire-conformance/) (the `wire` setting, ADR-0019 Amendment 2) | 6 cases + 8 refusals | ✓ | ✓ | inherits via Java (one config reader) | ✓ | ✓ | +| [`fixtures/codegen-skip-conformance/`](../fixtures/codegen-skip-conformance/) (when `gen` may skip and what a local `verify --codegen` may answer, ADR-0062) | one case table in `cases.json` | ✓ | ✓ | ✓ (through the Java runner) | ✓ | ✓ | | [`fixtures/codegen-noop/`](../fixtures/codegen-noop/) (FR-044 — reporting vocabulary: what is lowered, what stays inert) | 1 model pair (`reporting/with` vs `reporting/without`) | ✓ (codegen + migrate) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/cube-model/`](../fixtures/cube-model/) (FR-044 Plan 4 — the `cube-model` generator's golden Cube files, plus the canonical model's golden) | 46 cases (36 trees + 10 errors) + 1 canonical golden | ✓ (the exporter is TypeScript-only, spec R6; its `cube` lane also loads the files into a real Cube) | — | — | — | — | @@ -87,7 +88,7 @@ the corpora above do two different jobs. Only the first is a promise to adopters (the canonical serializer, surfaced per-file — ADR-0034's "canonical format" is core), `field-lint-conformance/` (the advisory field lint every port's `verify` prints) and `requirement-check-conformance/` (the requirement gate every port's `verify` runs; a - drift gate is core, and it is not ejectable in any port). + drift gate is core, and it is not ejectable in any port). `codegen-skip-conformance/` (ADR-0062: which changes make `gen` render, and what a local `verify --codegen` may answer from the stored key) is core for the same reason. A red cell here is a MetaObjects bug. - **Template quality checks — not a promise.** The generated lane of `api-contract-conformance/`, `generator-registry-conformance/` (stable generator names), diff --git a/docs/features/cli.md b/docs/features/cli.md index e2b68fc18f..767944a0a4 100644 --- a/docs/features/cli.md +++ b/docs/features/cli.md @@ -52,7 +52,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 --codegen` | **Codegen drift** — regenerate from metadata into a temp dir 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 is NOT drift — `meta gen` three-way-merges hand edits by design, so the gate compares the *generated contribution* against the committed `.gen-state/.hashes.json` rather than the file byte-for-byte. It still LISTS every generated file carrying a hand edit (count + paths, and how to see the edit) as a notice that does not change the exit code; `--forbid-hand-edits` makes any hand edit fail the build, for teams that want generated code untouchable (Node `meta` only). | no | +| `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 is NOT drift — `meta gen` three-way-merges hand edits by design, so the gate compares the *generated contribution* against the committed `.gen-state/.hashes.json` rather than the file byte-for-byte. It still LISTS every generated file carrying a hand edit (count + paths, and how to see the edit) as a notice that does not change the exit code; `--forbid-hand-edits` makes any hand edit fail the build, for teams that want generated code untouchable (Node `meta` only). | 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. | — | | `verify --deps` | **Dependency drift** (FR-023) — re-resolves each declared dependency (its `path`, or its installed `npm` / `python` package) and compares its installed artifact's hash against `.metaobjects/deps.lock.json`, same comparison as `meta deps check`. Needs the publisher reachable, so it is never part of the bare-`verify` default. A `drifted` or `unresolved` dependency fails with `ERR_DEPENDENCY_UPSTREAM_DRIFT`. **Node `meta` only.** See [`metadata-dependencies.md`](metadata-dependencies.md). | no | @@ -211,7 +211,7 @@ ADR-0015"). Bare `verify` runs `--codegen` and `--templates` (the template gate with a note when the run names no config and no `--prompts`). The **C# `dotnet meta`** port likewise ships the codegen-side subverbs: `verify --templates` (its historical template/prompt drift gate), `verify ---codegen` (regenerate the configured generators to a temp dir and diff against +--codegen` (regenerate the configured generators in memory and diff against the committed `--out` tree, never touching it), and a **clean `--db` rejection (exit 2)** — bare `dotnet meta verify` runs `--templates` and, when an output directory and `codegen/Generators.cs` are present, `--codegen`. The output directory is @@ -253,6 +253,30 @@ that differs refuses the whole call and removes nothing. It never edits your gen edit that points each entry back at the shipped generator. `--strict` exits 1 and writes nothing. No port has a `doctor` command: `eject --list` (or the matching goal) is the report. +## `gen` skips a run when nothing changed — and `--force` runs it anyway (ADR-0062) + +Every port's `gen` loads the metadata, then computes a key before it renders anything: the +loaded model (each node in its canonical effective form, so reformatting or splitting a metadata +file changes nothing) plus everything the generators are built from (the engine's built code, +the codegen config and every owned generator, the template roots, declared extra inputs, the +project config, the output-changing flags). When the key matches the last successful run and +every generated file still holds the bytes that run left, `gen` says so and renders and writes +nothing. The key lives in `.metaobjects/.gen-state/.fingerprint-.json`, which is not +committed. + +| flag | ports | what it does | +|---|---|---| +| `gen --force` | `meta`, `metaobjects`, `dotnet meta` | render everything, even when nothing changed | +| `-Dmetaobjects.force=true` / `true` | Maven (Java, Kotlin) | the same | +| `verify --codegen --full` | `meta`, `metaobjects`, `dotnet meta` | render and compare, even when a local run could answer from the key | +| `-Dmetaobjects.verify.full=true` | Maven (Java, Kotlin) | the same | + +A generator that reads something the key does not cover declares it (`inputs: [...]` in +TypeScript, its port's equivalent elsewhere); one that cannot say what it reads sets +`cache: false`, and a run that includes it never skips. In CI (`CI` set) `verify --codegen` +always renders and compares everything, so a key that missed an input is caught before it +ships. When `verify` renders, it compares in memory: no temp tree is written. + ## `gen` refuses rather than guesses — and `--baseline` is how you answer it Every port's `gen` decides per file whether it may overwrite, from a committed hash @@ -434,7 +458,7 @@ targets: the declared entries named (an owned entry matches its registry name too) and refuses a name no target declares. A target whose `generators` is empty writes nothing and says so. - **`metaobjects verify --codegen`** — also run by bare `verify`, which adds `--templates` - (see above) — regenerates the same list into a temp tree (the exact `gen` + (see above) — regenerates the same list in memory (the exact `gen` pipeline, including the cross-target duplicate-output-path guard) and diffs each **unique `outDir`** against the union of the co-resident targets' regen, aggregating the exit code (non-zero if *any* outDir has drifted). Targets sharing an `outDir` are verified together, diff --git a/docs/features/cube-export.md b/docs/features/cube-export.md index 8c4d9cbfd6..89684aeeef 100644 --- a/docs/features/cube-export.md +++ b/docs/features/cube-export.md @@ -576,8 +576,8 @@ there. ## Checking it -**`meta verify --codegen`** regenerates the configured output into a temporary directory and -compares it with the committed files. The Cube project is a target, so its files are checked +**`meta verify --codegen`** regenerates the configured output in memory and compares it with the +committed files. The Cube project is a target, so its files are checked like any other generated output: a changed model that was not regenerated, a missing cube file and a stale one are drift. A hand edit to a generated file is not drift, but the gate lists it, and `meta verify --codegen --forbid-hand-edits` makes it fail. diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 1ae5208fa7..051799da8a 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -361,7 +361,7 @@ a consumer is the one that checks them: the selection, the closure, the bytes, t the manifest. Change what they do and you have stopped agreeing with every consumer of the artifact. Read the project's own files through `ctx.inputRoot`, as the copy does for the version: under -`meta verify --codegen` the run writes into a temporary tree and `ctx.projectRoot` is that +`meta verify --codegen` the run renders in memory and `ctx.projectRoot` is the real project root, tree. The docs generators read your template overrides and site theme through it too. ## What `meta eject` hands over, and what stays core (TypeScript) diff --git a/docs/llms/llms-full.txt b/docs/llms/llms-full.txt index a7db61dfcb..00b6b7f782 100644 --- a/docs/llms/llms-full.txt +++ b/docs/llms/llms-full.txt @@ -65,7 +65,9 @@ Reference generators you own, ejectable in every port. They emit per-language co - C#: EF Core + ASP.NET (.NET 8). **Keep your EF model:** an object declared with no `source.rdb` generates a POCO with DataAnnotations and no EF mapping, a contract separate from your entities - Python: Pydantic + FastAPI (Python 3.11+). **Keep your ORM:** the `entity` generator writes Pydantic models with no ORM of any kind -Hand-edit-preserving regeneration is **TypeScript-only**: `meta gen` three-way-merges your edits into regenerated output on the machine that generated the file. C#, Python, Java and Kotlin do not merge. Each decides from a committed hash manifest (`.metaobjects/.gen-state/.hashes.json`): a file that still matches what the generator wrote is overwritten, an edited one is refused by name (Java and Kotlin can be told to replace it with `handEdits=overwrite`), and `eject` hands you the generator to own instead. M:N relationship codegen (FR-018) ships in all five ports: entity navigation, idiomatic ORM wiring (Drizzle m2m / EF Core `UsingEntity` / Spring repo interface / Exposed / Pydantic), and REST traversal (`GET //{id}/`). +Hand-edit-preserving regeneration is **TypeScript-only**: `meta gen` three-way-merges your edits into regenerated output on the machine that generated the file. C#, Python, Java and Kotlin do not merge. Each decides from a committed hash manifest (`.metaobjects/.gen-state/.hashes.json`): a file that still matches what the generator wrote is overwritten, an edited one is refused by name (Java and Kotlin can be told to replace it with `handEdits=overwrite`), and `eject` hands you the generator to own instead. + +`gen` skips a run when nothing changed (ADR-0062). Before it renders anything, it computes a key from the loaded model and everything the generators are built from. When the key matches the last successful run and every generated file still holds the bytes that run left, `gen` says so and writes nothing. `gen --force` (Maven: `-Dmetaobjects.force=true`) renders everything anyway. In CI, `verify --codegen` always renders and compares everything, so a key that missed an input is caught before it ships. A generator that reads something the key does not cover declares it (`inputs` in TypeScript), or sets `cache: false` so a run that includes it never skips. The skip rules are gated by the `codegen-skip-conformance` corpus (`fixtures/codegen-skip-conformance/`) in every port. M:N relationship codegen (FR-018) ships in all five ports: entity navigation, idiomatic ORM wiring (Drizzle m2m / EF Core `UsingEntity` / Spring repo interface / Exposed / Pydantic), and REST traversal (`GET //{id}/`). ### Runtime metadata @@ -83,7 +85,7 @@ Runtime use cases include CRUD scaffolding, validation rules, relationship trave Catch divergence between code and metadata. `verify` is one verb with three explicit subverbs (ADR-0021): -- `verify --codegen` — regenerate from metadata into a temp dir and fail if it differs from the committed generated output (catches "metadata changed but codegen wasn't re-run" and hand-edited generated files). +- `verify --codegen` — regenerate from metadata in memory and fail if it differs from the committed generated output (catches "metadata changed but codegen wasn't re-run" and hand-edited generated files). - `verify --templates` — check each `template.*` node's `{{field}}` references (Mustache, or Jinja in Python and TypeScript) against its payload VO (prompt-to-payload drift). - `verify --db` — live-DB schema drift; Node `meta` only (it is part of the schema toolchain, ADR-0015). @@ -131,7 +133,7 @@ Today the TypeScript toolchain publishes and TypeScript and Python projects cons | C# | NuGet `1.2.2` (.NET tool) | Loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. `dotnet meta` tool. | | Python | PyPI `1.2.1` | Loader + serializer + render + verify + codegen + `ObjectManager` runtime. Fully green across all corpora. | -Conformance fixtures live at [`fixtures/`](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures). Every port runs the shared corpus byte-identically: metamodel (`conformance/`, 314 fixtures), render, persistence (Testcontainers Postgres, with an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), api-contract (core REST contract + filter operators, plus TPH / M:N / jsonb / write-through and the other sub-corpora — two lanes: a reference server AND each port's generated API booted over HTTP), registry (byte-matched metamodel-vocabulary manifest, live + green in all five ports), and yaml/verify. +Conformance fixtures live at [`fixtures/`](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures). Every port runs the shared corpus byte-identically: metamodel (`conformance/`, 314 fixtures), render, persistence (Testcontainers Postgres, with an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), api-contract (core REST contract + filter operators, plus TPH / M:N / jsonb / write-through and the other sub-corpora — two lanes: a reference server AND each port's generated API booted over HTTP), registry (byte-matched metamodel-vocabulary manifest, live + green in all five ports), `codegen-skip-conformance/` (when `gen` may skip a run, ADR-0062), and yaml/verify. --- @@ -305,6 +307,7 @@ $ meta eject routes # Generate code from exactly what you wired $ meta gen +$ meta gen --force # render everything, even when nothing changed # Optional positional filter $ meta gen Subscriber Order --dry-run diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index 8c73e423c6..c3fd09a53e 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -183,7 +183,7 @@ in `.metaobjects/config.json`, below). # Run the list: EF Core entities + AppDbContext + CRUD minimal-API routes dotnet meta gen ./metaobjects --out ./Generated -# The drift gate: regenerate into a temp tree and fail (exit 1, naming the files) if the +# The drift gate: regenerate in memory and fail (exit 1, naming the files) if the # committed ./Generated differs. Run it in CI. dotnet meta verify ./metaobjects --codegen --out ./Generated ``` diff --git a/docs/ports/java.md b/docs/ports/java.md index e4f14b9f02..9330f69ed4 100644 --- a/docs/ports/java.md +++ b/docs/ports/java.md @@ -270,7 +270,7 @@ allowlist under `target/generated-sources/java`, which Maven compiles with your mvn metaobjects:verify # fails with the stale files named when the model moved and nobody regenerated ``` -It regenerates into a temporary directory and compares: change `src/main/metaobjects/` without +It regenerates in memory and compares: change `src/main/metaobjects/` without regenerating and the build exits 1 with `generated code is stale` and a `[content-differs]` line per file; `mvn metaobjects:generate` (or `mvn compile`) and it is green again. The same goal also runs the requirement gate. Add it to your CI after `mvn compile`. diff --git a/docs/recipes/generators/java/JsonSchemaGenerator.java b/docs/recipes/generators/java/JsonSchemaGenerator.java index 9dfcc7ec2a..1b0d9f0b0d 100644 --- a/docs/recipes/generators/java/JsonSchemaGenerator.java +++ b/docs/recipes/generators/java/JsonSchemaGenerator.java @@ -7,7 +7,7 @@ // com.acme.codegen.JsonSchemaGenerator // ${project.basedir}/src/main/resources/schemas // -// `mvn metaobjects:verify` re-runs it into a temp dir and fails on drift; nothing to register. +// `mvn metaobjects:verify` re-runs it in memory and fails on drift; nothing to register. // // Emits .schema.json (JSON Schema 2020-12) per concrete object. package com.acme.codegen; diff --git a/docs/recipes/write-your-own-generator.md b/docs/recipes/write-your-own-generator.md index ff5591da9e..4c8faa2353 100644 --- a/docs/recipes/write-your-own-generator.md +++ b/docs/recipes/write-your-own-generator.md @@ -259,7 +259,7 @@ public class FieldListGenerator extends FileEmittingGenerator { ``` -`mvn metaobjects:generate` runs it; `mvn metaobjects:verify` regenerates into a temp dir +`mvn metaobjects:generate` runs it; `mvn metaobjects:verify` regenerates in memory and diffs. Extra `` reach the generator through `getArg(name, default)`. Three JVM traps `ModelWalk` exists to close: `getName()` is the fully-qualified `shop::Customer` (use `ModelWalk.name`), `isArray()` is the own flag (use `ModelWalk.isArray`), and @@ -293,6 +293,27 @@ class KtFieldListGenerator : FileEmittingGenerator() { Wire it with `com.acme.codegen.KtFieldListGenerator` from a module built with `kotlin-maven-plugin`. +## Reads outside the model: declare them, or `meta gen` may skip your output + +`meta gen` skips a run when nothing it is built from has changed ([ADR-0062](../../spec/decisions/ADR-0062-skip-codegen-when-nothing-changed.md)). +That key covers the loaded model, the engine, the config, the owned generator files and the +template roots. Anything else your generator reads has to be declared, or a change to it will +not regenerate. In TypeScript, on the `Generator` object: + +- a file or directory under the project it reads: `inputs: ["prompts"]` (relative to the project root; a directory counts every file under it); +- the raw metadata source files beside the loaded model, for their comments: `readsMetadataSources: true`; +- something the key cannot name in advance (the network, an environment variable): `cache: false`. A run that includes that generator never skips. + +```ts +generators: [entityFile(), { ...redactionGenerator(), inputs: ["prompts"] }], +``` + +Java and Kotlin (`cacheable()` and `extraInputs()`) and C# (`Cacheable`, `ExtraInputs`) carry +the same declarations on their `Generator` interface; Python reads a `cacheable` attribute and +`declared_extra_inputs`. A declaration that over-counts costs one +extra render; a missing one can skip a change, so when in doubt declare it. `meta gen --force` +renders everything, and CI's `verify --codegen` renders everything regardless of the key. + ## Safety-relevant output: set `handEdits: "overwrite"` A generator whose output enforces something (a redaction rule, an audit log, an auth check) diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 6667d82a4f..69bf2716b9 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -8,7 +8,7 @@ }, "counts": { "fixtures": 421, - "corpora": 34, + "corpora": 35, "baseTypes": 17 }, "snippets": { diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md index fcd3818604..3aaa5b4ebc 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/java.md @@ -36,7 +36,7 @@ goal bound to `generate-sources` in `pom.xml`. ```bash mvn metaobjects:generate # codegen goal directly mvn compile # also runs it (bound to generate-sources) -mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen to temp, diff vs committed output +mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen in memory, diff vs committed output mvn metaobjects:verify -Dmeta.verify.mode=templates # {{field}} refs vs payload VO ``` diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md index 1928e36878..ee44432105 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-audit/references/kotlin.md @@ -40,7 +40,7 @@ committed — confirm the plugin is wired and the goal bound to `generate-source ```bash mvn metaobjects:generate # codegen goal directly mvn compile # also runs it (bound to generate-sources) -mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen to temp, diff vs committed output +mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen in memory, diff vs committed output mvn metaobjects:verify -Dmeta.verify.mode=templates # {{field}} refs vs payload VO ``` diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md index fcd3818604..3aaa5b4ebc 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-audit/references/java.md @@ -36,7 +36,7 @@ goal bound to `generate-sources` in `pom.xml`. ```bash mvn metaobjects:generate # codegen goal directly mvn compile # also runs it (bound to generate-sources) -mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen to temp, diff vs committed output +mvn metaobjects:verify -Dmeta.verify.mode=codegen # regen in memory, diff vs committed output mvn metaobjects:verify -Dmeta.verify.mode=templates # {{field}} refs vs payload VO ``` diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md index 47beec1afb..bb110ec191 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-audit/references/python.md @@ -38,7 +38,7 @@ directory structure beyond the target's `outDir`. ```bash metaobjects gen # run every target's generators (metaobjects.config.yaml) metaobjects gen --generators entity # narrow to declared entries -metaobjects verify --codegen # regenerate to temp, diff vs each committed outDir (bare default) +metaobjects verify --codegen # regenerate in memory, diff vs each committed outDir (bare default) metaobjects verify --templates # {{field}} refs vs payload VO ``` diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/python.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/python.md index cb785d6624..9c73346741 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/python.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-codegen/references/python.md @@ -61,7 +61,7 @@ the config's `templates` is refused. ```bash metaobjects gen # runs every target's generators into its outDir metaobjects gen --generators entity # narrow to declared entries (never adds one) -metaobjects verify --codegen # regenerate the same list into a temp dir + diff +metaobjects verify --codegen # regenerate the same list in memory + diff ``` With no `metaobjects.config.yaml`, `gen` and `verify --codegen` exit 2 and write nothing. diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md index 3fc99245c4..ecb64ba2cb 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-audit/references/typescript.md @@ -40,7 +40,7 @@ the default single-target config, generated files land at the one configured meta gen # render → 3-way merge → write (overwrites @generated files only) meta gen --dry-run # preview without writing meta gen Author Post # scope to named entities -meta verify --codegen # regenerate to temp, diff vs committed output +meta verify --codegen # regenerate in memory, diff vs committed output meta verify --templates # check {{field}} refs vs payload VO (a bare `meta verify` runs this and `--codegen`) meta verify --db # schema drift — live DB vs metadata (requires DB connection) meta verify --codegen --templates --db # all three drift checks in one pass diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md index 0765fafc56..e9eccf9687 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-codegen/references/typescript.md @@ -162,8 +162,8 @@ Some ejectable entries behave differently from the rest: every consumer. In an owned generator, read the project's own files through `ctx.inputRoot`. Under -`meta verify --codegen` the run writes into a temporary tree and `ctx.projectRoot` is that -tree; under a plain `meta gen` it is the directory that holds `metaobjects.config.ts`. +`meta verify --codegen` the run renders in memory; `ctx.projectRoot` is the real project root, +the directory that holds `metaobjects.config.ts`, as it is under a plain `meta gen`. **`requirementTests()` — one test stub per requirement the model claims.** A recommended approach, not a contract: a `live` or `partial` requirement gets a stub that fails until diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/typescript.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/typescript.md index 3fc99245c4..ecb64ba2cb 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-audit/references/typescript.md @@ -40,7 +40,7 @@ the default single-target config, generated files land at the one configured meta gen # render → 3-way merge → write (overwrites @generated files only) meta gen --dry-run # preview without writing meta gen Author Post # scope to named entities -meta verify --codegen # regenerate to temp, diff vs committed output +meta verify --codegen # regenerate in memory, diff vs committed output meta verify --templates # check {{field}} refs vs payload VO (a bare `meta verify` runs this and `--codegen`) meta verify --db # schema drift — live DB vs metadata (requires DB connection) meta verify --codegen --templates --db # all three drift checks in one pass diff --git a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript.md b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript.md index 0765fafc56..e9eccf9687 100644 --- a/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript.md +++ b/fixtures/agent-context-conformance/ts-requirements/expected/.claude/skills/metaobjects-codegen/references/typescript.md @@ -162,8 +162,8 @@ Some ejectable entries behave differently from the rest: every consumer. In an owned generator, read the project's own files through `ctx.inputRoot`. Under -`meta verify --codegen` the run writes into a temporary tree and `ctx.projectRoot` is that -tree; under a plain `meta gen` it is the directory that holds `metaobjects.config.ts`. +`meta verify --codegen` the run renders in memory; `ctx.projectRoot` is the real project root, +the directory that holds `metaobjects.config.ts`, as it is under a plain `meta gen`. **`requirementTests()` — one test stub per requirement the model claims.** A recommended approach, not a contract: a `live` or `partial` requirement gets a stub that fails until diff --git a/fixtures/codegen-skip-conformance/README.md b/fixtures/codegen-skip-conformance/README.md new file mode 100644 index 0000000000..d778eca78a --- /dev/null +++ b/fixtures/codegen-skip-conformance/README.md @@ -0,0 +1,25 @@ +# codegen-skip-conformance + +The shared table of cases for [ADR-0062](../../spec/decisions/ADR-0062-skip-codegen-when-nothing-changed.md): +which changes must make `gen` regenerate, which may let it skip, and what a local +`verify --codegen` may do after each. + +`cases.json` is the whole corpus. It holds no project: each port builds a small project of its +own shape (its own config file, generator wiring and template roots), runs `gen` once, applies +each case's change, and asks its skip decision. A runner fails on a case id it does not know, so +adding a case here reaches every port at once. + +| Port | Runner | +|---|---| +| TypeScript | `server/typescript/packages/cli/test/gen-skip-conformance.test.ts` | +| Python | `server/python/tests/test_gen_skip_conformance.py` | +| C# | `server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs` | +| Java | `server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java` | +| Kotlin | the Java runner, with a Kotlin generator configured (Kotlin generators run through `metaobjects:generate`) | + +The values: + +- `gen`: `skip` (the next `gen` may load the metadata to compute its key, but must render nothing and write nothing) or `regenerate` (it must run + in full). +- `verify`: `may-answer-no-drift` (a local `verify --codegen` may answer from the stored key and + the manifest without rendering) or `must-render` (it must render and compare). diff --git a/fixtures/codegen-skip-conformance/cases.json b/fixtures/codegen-skip-conformance/cases.json new file mode 100644 index 0000000000..bf39390872 --- /dev/null +++ b/fixtures/codegen-skip-conformance/cases.json @@ -0,0 +1,156 @@ +{ + "$comment": "ADR-0062. Every port runs every case against its own project shape: run gen once (it must write and store a key), apply the change, then ask the port's skip decision. 'gen' is what the next gen must do ('skip' = render nothing and write nothing); 'verify' is what a LOCAL verify --codegen (CI unset, no --full) may do. A port that meets an id it does not know fails, so a new case reaches every port.", + "version": 1, + "cases": [ + { + "id": "no-change", + "change": "Nothing changes between the two runs.", + "gen": "skip", + "verify": "may-answer-no-drift" + }, + { + "id": "metadata-touched", + "change": "A metadata file is rewritten with identical content (its timestamp moves, its bytes do not).", + "gen": "skip", + "verify": "may-answer-no-drift" + }, + { + "id": "unrelated-file-edited", + "change": "A file that is no input (a README beside the project) is edited.", + "gen": "skip", + "verify": "may-answer-no-drift" + }, + { + "id": "metadata-reformatted", + "change": "A metadata file is rewritten with different whitespace and key order but the same content, so the loaded model is identical.", + "gen": "skip", + "verify": "may-answer-no-drift" + }, + { + "id": "metadata-moved", + "change": "An object moves from one metadata file to a new file in the same package; the loaded model is identical.", + "gen": "skip", + "verify": "may-answer-no-drift" + }, + { + "id": "metadata-edited", + "change": "One metadata file's content changes (an attribute added to one object).", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "metadata-added", + "change": "A new metadata file is added where the loader reads.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "metadata-removed", + "change": "A metadata file the loader read is deleted.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "parent-edited", + "change": "An abstract object that another object extends gains a field; only the parent's file changes, the child's effective form changes with it.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "config-edited", + "change": "The port's codegen config changes (a generator added or removed, or one generator's options changed).", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "project-config-edited", + "change": ".metaobjects/config.json changes.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "template-edited", + "change": "A file under a declared template root changes.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "template-added", + "change": "A file is added under a declared template root.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "owned-generator-edited", + "change": "A source file of an owned (ejected) generator changes.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "engine-changed", + "change": "The engine identity changes (a new version, or different content in a linked checkout).", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "selection-changed", + "change": "An output-changing flag differs from the stored run: entity or generator selection, strict, or the baseline mode.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "declared-extra-edited", + "change": "A file a generator declared as an extra input changes.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "uncacheable-generator", + "change": "The run includes a generator marked not cacheable; nothing else changes.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "generated-file-deleted", + "change": "A file the manifest records is deleted.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "generated-file-edited", + "change": "A file the manifest records is edited by hand after the last run (its bytes differ from what that run left). gen renders, so it puts the file back or merges the edit, as verify tells the user it will.", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "hand-edit-kept", + "change": "A hand edit is made, and a gen run keeps it (merges it); nothing changes after that run. The file still differs from its manifest record, but not from what the last run left.", + "gen": "skip", + "verify": "must-render" + }, + { + "id": "fingerprint-missing", + "change": "The stored fingerprint file is deleted (a fresh clone).", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "force", + "change": "The next run passes --force (or the port's equivalent).", + "gen": "regenerate", + "verify": "must-render" + }, + { + "id": "ci", + "change": "Nothing changes, but verify runs with CI=true.", + "gen": "skip", + "verify": "must-render" + }, + { + "id": "failed-run", + "change": "A run that started after an input change failed; the input is then restored to what the last successful run saw.", + "gen": "regenerate", + "verify": "must-render" + } + ] +} diff --git a/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs new file mode 100644 index 0000000000..c6383de1bc --- /dev/null +++ b/server/csharp/MetaObjects.Cli.Tests/GenSkipConformanceTests.cs @@ -0,0 +1,269 @@ +// ADR-0062 — the shared table of skip cases (fixtures/codegen-skip-conformance/cases.json), run +// against this port's project shape: a codegen/ project (the generator list, an owned generator, a +// project reference to a linked engine checkout), a metadata directory with an abstract parent and +// a child, a template root and .metaobjects/config.json. +// +// Each case runs the owned runner's `gen` once (it must store a key), applies the case's change, +// then asks the two real decisions: a local `verify --codegen` first (it changes nothing) and +// `gen` second. The decisions are made inside the codegen process, after the load, so both are +// read from what that process prints. + +using System.Text.Json; +using MetaObjects.Codegen; +using Xunit; + +namespace MetaObjects.Cli.Tests; + +[Collection(OwnedRunnerCollection.Name)] +public sealed class GenSkipConformanceTests : IDisposable +{ + private readonly string _tmp = Path.Combine(Path.GetTempPath(), "meta-skip-" + Guid.NewGuid().ToString("N")); + private readonly string? _ci = Environment.GetEnvironmentVariable("CI"); + private string MetaDir => Path.Combine(_tmp, "metaobjects"); + private string OutDir => Path.Combine(_tmp, "generated"); + private string P(string rel) => Path.Combine(_tmp, rel); + + private const string Parent = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Base", "abstract": true, "children": [ + { "field.string": { "name": "tag" } } + ]}} + ]}} + """; + + private const string Child = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Sub", "extends": "Base", "children": [ + { "source.rdb": { "@table": "subs" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + private const string Order = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + /// A generator that declares an extra input and can mark itself uncacheable. + private sealed class Custom(bool cacheable) : IGenerator + { + public string Name => "custom"; + public bool Cacheable => cacheable; + public IReadOnlyList ExtraInputs => ["extra/data.txt"]; + public IEnumerable Generate(GenContext ctx) => + [new EmittedFile("Custom.g.cs", "// " + File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "extra", "data.txt")))]; + } + + public GenSkipConformanceTests() + { + Environment.SetEnvironmentVariable("CI", null); + Directory.CreateDirectory(MetaDir); + File.WriteAllText(P("metaobjects/meta.base.json"), Parent); + File.WriteAllText(P("metaobjects/meta.sub.json"), Child); + File.WriteAllText(P("metaobjects/meta.order.json"), Order); + Directory.CreateDirectory(P(".metaobjects")); + File.WriteAllText(P(".metaobjects/config.json"), """{ "schema_version": 1 }"""); + Directory.CreateDirectory(P("codegen/generators")); + File.WriteAllText(P("codegen/Generators.cs"), "// the list v1\n"); + File.WriteAllText(P("codegen/generators/Own.cs"), "// an owned generator v1\n"); + Directory.CreateDirectory(P("engine")); + File.WriteAllText(P("engine/Engine.csproj"), "\n"); + File.WriteAllText(P("engine/Engine.cs"), "// engine v1\n"); + File.WriteAllText(P("codegen/Codegen.csproj"), + "\n"); + Directory.CreateDirectory(P("prompts")); + File.WriteAllText(P("prompts/greeting.mustache"), "hello\n"); + Directory.CreateDirectory(P("extra")); + File.WriteAllText(P("extra/data.txt"), "one"); + File.WriteAllText(P("README.md"), "readme v1\n"); + } + + public void Dispose() + { + Environment.SetEnvironmentVariable("CI", _ci); + try { Directory.Delete(_tmp, recursive: true); } catch { } + } + + private string[] GenArgs(params string[] more) => + ["gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", .. more]; + + private IReadOnlyList Declared(bool uncacheable = false) => + [.. OwnedRunner.Declared(_tmp, "entity"), new Custom(!uncacheable)]; + + private (int Exit, string Out, string Err) RunGen(IReadOnlyList declared, params string[] more) => + Wrap(OwnedRunner.Run(_tmp, declared, GenArgs(more))); + + private static (int Exit, string Out, string Err) Wrap((int ExitCode, string Stdout, string Stderr) r) => (r.ExitCode, r.Stdout, r.Stderr); + + private const string GenSkipped = "nothing changed since the last run; skipped"; + private const string VerifyAnswered = "nothing changed since the last gen"; + + /// What a local `verify --codegen` does, from what the codegen process prints. It changes nothing. + private string VerifyDecision(IReadOnlyList declared, string[] more, string? ci) + { + Environment.SetEnvironmentVariable("CI", ci); + var full = more.Contains("--force") ? new[] { "--full" } : []; + string[] gen = more.Where(m => m != "--force").ToArray(); + var r = OwnedRunner.Run(_tmp, declared, + ["verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", .. gen, .. full]); + Environment.SetEnvironmentVariable("CI", null); + return r.Stdout.Contains(VerifyAnswered) ? "may-answer-no-drift" : "must-render"; + } + + /// What `gen` does: skip (renders and writes nothing) or regenerate. + private string GenDecision(IReadOnlyList declared, string[] more) + { + var r = RunGen(declared, more); + return r.Out.Contains(GenSkipped) ? "skip" : "regenerate"; + } + + private static string CasesPath() + { + for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) + { + var p = Path.Combine(dir.FullName, "fixtures", "codegen-skip-conformance", "cases.json"); + if (File.Exists(p)) return p; + } + throw new InvalidOperationException("fixtures/codegen-skip-conformance/cases.json not found above " + AppContext.BaseDirectory); + } + + public static IEnumerable Cases() + { + using var doc = JsonDocument.Parse(File.ReadAllText(CasesPath())); + foreach (var c in doc.RootElement.GetProperty("cases").EnumerateArray()) + yield return [c.GetProperty("id").GetString()!, c.GetProperty("gen").GetString()!, c.GetProperty("verify").GetString()!]; + } + + private string FingerprintPath() => P(".metaobjects/.gen-state/" + GenFingerprint.FileName); + + [Theory] + [MemberData(nameof(Cases))] + public void The_case_table_decides_gen_and_verify(string id, string gen, string verify) + { + var declared = Declared(); + var first = RunGen(declared); + Assert.True(first.Exit == 0, first.Out + first.Err); + Assert.NotNull(GenFingerprint.Read(_tmp)); + + string[] more = []; + string? ci = null; + switch (id) + { + case "no-change": break; + case "metadata-touched": + File.WriteAllText(P("metaobjects/meta.order.json"), Order); + File.SetLastWriteTimeUtc(P("metaobjects/meta.order.json"), DateTime.UtcNow.AddHours(1)); + break; + case "unrelated-file-edited": File.WriteAllText(P("README.md"), "readme v2\n"); break; + case "metadata-reformatted": + // Same content: different whitespace and object-key order (child order is meaningful and kept). + File.WriteAllText(P("metaobjects/meta.order.json"), + """ + { "metadata.root": { "children": [ + { "object.entity": { "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } ], + "name": "Order" } } ], + "package": "acme" } } + """); + break; + case "metadata-moved": + File.Delete(P("metaobjects/meta.order.json")); + File.WriteAllText(P("metaobjects/meta.moved.json"), Order); + break; + case "metadata-edited": + File.WriteAllText(P("metaobjects/meta.order.json"), Order.Replace("orders", "orders2")); + break; + case "metadata-added": File.WriteAllText(P("metaobjects/meta.extra.json"), Order.Replace("Order", "Extra")); break; + case "metadata-removed": File.Delete(P("metaobjects/meta.order.json")); break; + case "parent-edited": + File.WriteAllText(P("metaobjects/meta.base.json"), Parent.Replace( + """{ "field.string": { "name": "tag" } }""", + """{ "field.string": { "name": "tag" } }, { "field.string": { "name": "note" } }""")); + break; + case "config-edited": File.WriteAllText(P("codegen/Generators.cs"), "// the list v2\n"); break; + case "project-config-edited": + File.WriteAllText(P(".metaobjects/config.json"), """{ "schema_version": 1, "csharp": { "namespace": "Other" } }"""); + break; + case "template-edited": File.WriteAllText(P("prompts/greeting.mustache"), "hello again\n"); break; + case "template-added": File.WriteAllText(P("prompts/farewell.mustache"), "bye\n"); break; + case "owned-generator-edited": File.WriteAllText(P("codegen/generators/Own.cs"), "// an owned generator v2\n"); break; + case "engine-changed": File.WriteAllText(P("engine/Engine.cs"), "// engine v2\n"); break; + case "selection-changed": more = ["--generators", "entity"]; break; + case "declared-extra-edited": File.WriteAllText(P("extra/data.txt"), "two"); break; + case "uncacheable-generator": declared = Declared(uncacheable: true); break; + case "hand-edit-kept": + // The C# runner refuses (never merges) a hand edit, so the "run that kept it" is simulated: + // edit, then store the key the way a successful run would, over the file as it now is. + File.AppendAllText(Directory.GetFiles(OutDir).First(), "// hand edit\n"); + var stored = GenFingerprint.Read(_tmp)!; + GenFingerprint.Write(_tmp, stored.Model, stored.Identity, stored.Untracked); + break; + case "generated-file-deleted": File.Delete(Directory.GetFiles(OutDir).First()); break; + case "generated-file-edited": File.AppendAllText(Directory.GetFiles(OutDir).First(), "// hand edit\n"); break; + case "fingerprint-missing": File.Delete(FingerprintPath()); break; + case "force": more = ["--force"]; break; + case "ci": ci = "true"; break; + case "failed-run": + var good = File.ReadAllText(P("metaobjects/meta.order.json")); + File.WriteAllText(P("metaobjects/meta.order.json"), "{ not json"); + var bad = RunGen(declared); + Assert.NotEqual(0, bad.Exit); + File.WriteAllText(P("metaobjects/meta.order.json"), good); + break; + default: Assert.Fail($"unknown case id '{id}': add it to this runner"); break; + } + + // verify first: it changes nothing. gen second: a regenerate stores a new key. + Assert.Equal(verify, VerifyDecision(declared, more, ci)); + Assert.Equal(gen, GenDecision(declared, more)); + } + + [Fact] + public void A_skipped_gen_renders_nothing_and_leaves_every_file_and_the_key_untouched() + { + Assert.Equal(0, RunGen(Declared()).Exit); + var manifest = P(".metaobjects/.gen-state/.hashes.json"); + var files = Directory.GetFiles(OutDir).Append(manifest).Append(FingerprintPath()).ToList(); + var stamp = DateTime.UtcNow.AddHours(-2); + foreach (var f in files) File.SetLastWriteTimeUtc(f, stamp); + + var again = RunGen(Declared()); + + Assert.Contains(GenSkipped, again.Out); + Assert.DoesNotContain("unchanged:", again.Out); + foreach (var f in files) Assert.Equal(stamp, File.GetLastWriteTimeUtc(f)); + } + + [Fact] + public void An_edit_regenerates_and_the_next_run_skips_again() + { + Assert.Equal(0, RunGen(Declared()).Exit); + File.WriteAllText(P("metaobjects/meta.order.json"), Order.Replace("orders", "orders2")); + Assert.Equal("regenerate", GenDecision(Declared(), [])); + Assert.Equal("skip", GenDecision(Declared(), [])); + } + + [Fact] + public void The_model_hash_is_a_tree_whose_node_and_package_hashes_move_with_the_node() + { + var load = () => MetaObjects.Config.MetadataLocation.Resolve(MetaDir, _tmp).Load(); + var before = ModelHash.Of(load().Root); + Assert.Contains(before.Nodes, n => n is { Package: "acme", Name: "Order" }); + File.WriteAllText(P("metaobjects/meta.order.json"), Order.Replace("orders", "orders2")); + var after = ModelHash.Of(load().Root); + + Assert.NotEqual(before.Model, after.Model); + Assert.NotEqual(before.Packages["acme"], after.Packages["acme"]); + Assert.Equal(before.Nodes.Single(n => n.Name == "Sub").Hash, after.Nodes.Single(n => n.Name == "Sub").Hash); + Assert.NotEqual(before.Nodes.Single(n => n.Name == "Order").Hash, after.Nodes.Single(n => n.Name == "Order").Hash); + } +} diff --git a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs index 22666e80e2..e9cfadf747 100644 --- a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs @@ -501,7 +501,7 @@ public void A_declared_template_spec_entry_renders_its_templates_and_verifies_cl Assert.Equal(["Subscriber.summary.txt"], FilesUnder(OutDir)); Assert.Equal("name=Subscriber\n", File.ReadAllText(Path.Combine(OutDir, "Subscriber.summary.txt"))); - var (verifyExit, verifyOut, verifyErr) = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated"); + var (verifyExit, verifyOut, verifyErr) = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", "--full"); Assert.True(verifyExit == 0, $"exit={verifyExit}\nstdout={verifyOut}\nstderr={verifyErr}"); Assert.Contains("OK (generated output is in sync)", verifyOut); } diff --git a/server/csharp/MetaObjects.Cli/Program.cs b/server/csharp/MetaObjects.Cli/Program.cs index 236ddd5f3c..c636ca3d1e 100644 --- a/server/csharp/MetaObjects.Cli/Program.cs +++ b/server/csharp/MetaObjects.Cli/Program.cs @@ -31,7 +31,7 @@ " codegen/Program.cs and codegen/Codegen.csproj;\n" + " --with-docs lists the api-docs generator in it\n" + " gen [] --out [--namespace ] [--emit-abstract-shapes]\n" + - " [--generators ] [--template-root ] [--strict]\n" + + " [--generators ] [--template-root ] [--strict] [--force]\n" + " run the generator list in codegen/Generators.cs;\n" + " --generators narrows it to the entries named;\n" + " --strict rejects an unknown @attr before writing\n" + @@ -384,7 +384,7 @@ static int RunVerify(string[] rest) string? generatorsCsv = null; string? templateRoot = null; string? columnNamingRaw = null; - bool templates = false, codegen = false, db = false, lax = false, noFieldLint = false, requireImplementers = false; + bool templates = false, codegen = false, db = false, lax = false, noFieldLint = false, requireImplementers = false, full = false; for (int i = 0; i < rest.Length; i++) { @@ -406,6 +406,8 @@ static int RunVerify(string[] rest) else if (a == "--prompts" && i + 1 < rest.Length) templatesRoot = rest[++i]; else if (a == "--codegen") codegen = true; else if (a == "--db") db = true; + // ADR-0062: render and compare even when a local run could answer from the stored key. + else if (a == "--full") full = true; // --lax (#96 / ADR-0023): restore the legacy open-attr load. verify is // strict-by-default — an undeclared/typo'd own @attr is ERR_UNKNOWN_ATTR. else if (a == "--lax") lax = true; @@ -511,6 +513,7 @@ static int RunVerify(string[] rest) if (generatorsCsv is not null) codegenArgs.AddRange(["--generators", generatorsCsv]); if (templateRoot is not null) codegenArgs.AddRange(["--template-root", templateRoot]); if (lax) codegenArgs.Add("--lax"); + if (full) codegenArgs.Add("--full"); codegenHandedOff = CodegenHandoff.TryRun(projectRoot, codegenArgs.ToArray(), out codegenHandoffExit); } } @@ -623,25 +626,28 @@ partial class Program { static readonly string[] GenValueFlags = ["--out", "--namespace", "--generators", "--template-root", "--template-spec", "--column-naming", "--baseline"]; - static readonly string[] GenBoolFlags = ["--list", "--emit-abstract-shapes", "--strict"]; + static readonly string[] GenBoolFlags = ["--list", "--emit-abstract-shapes", "--strict", "--force"]; static readonly string[] VerifyValueFlags = ["--prompts", "--out", "--namespace", "--generators", "--template-root", "--column-naming"]; - static readonly string[] VerifyBoolFlags = ["--templates", "--codegen", "--db", "--lax", "--no-field-lint", "--require-implementers"]; + static readonly string[] VerifyBoolFlags = ["--templates", "--codegen", "--db", "--lax", "--no-field-lint", "--require-implementers", "--full"]; /// Each command's usage, printed by dotnet meta <command> --help. static readonly Dictionary CommandUsage = new() { - ["gen"] = "usage: dotnet meta gen [] --out [--namespace ] [--generators ] [--template-root ] [--emit-abstract-shapes] [--baseline default|adopt] [--strict]\n" + + ["gen"] = "usage: dotnet meta gen [] --out [--namespace ] [--generators ] [--template-root ] [--emit-abstract-shapes] [--baseline default|adopt] [--strict] [--force]\n" + " dotnet meta gen --list\n" + " runs the generator list in codegen/Generators.cs (`dotnet meta init` writes it);\n" + " --generators narrows that list to the entries named, and never adds one.\n" + + " --force: render even when the model and the generators are unchanged since the last run\n" + + " (ADR-0062: otherwise an unchanged run renders and writes nothing and says so);\n" + " --strict: an unknown @attr is an error (exit 1, nothing written), as in verify (ADR-0023);\n" + " without it gen warns and generates. Owned copies identical to the shipped generators\n" + " get one advisory line naming `dotnet meta eject --undo`.\n" + " column/table naming: \"naming\" in .metaobjects/config.json (ADR-0058), not a flag here", ["init"] = "usage: dotnet meta init [--root ] [--with-docs]\n" + " --with-docs lists the api-docs generator in codegen/Generators.cs (written to docs/csharp)", - ["verify"] = "usage: dotnet meta verify [--templates [--prompts ]] [--codegen --out [--namespace ] [--generators ] [--template-root ]] [--db] [--lax] [--no-field-lint] [--require-implementers]", + ["verify"] = "usage: dotnet meta verify [--templates [--prompts ]] [--codegen --out [--namespace ] [--generators ] [--template-root ]] [--db] [--lax] [--no-field-lint] [--require-implementers] [--full]\n" + + " --full: render and compare even when a local run could answer from the stored key (CI always renders)", ["fmt"] = "usage: dotnet meta fmt [] [--check]", ["eject"] = "usage: dotnet meta eject ... [--force] [--root ]\n" + " dotnet meta eject --undo [...] [--force] [--root ]\n" + diff --git a/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs index 6fa7a1e2ae..75e68ef7cb 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CodegenDriftTests.cs @@ -7,10 +7,10 @@ namespace MetaObjects.Codegen.Tests; /// /// `dotnet meta verify --codegen` drift logic (ADR-0021 D2, C# port of the TS -/// codegen-drift reference). Regenerates the default suite into a TEMP tree and +/// codegen-drift reference). Regenerates the default suite IN MEMORY (no temp tree) and /// diffs it against the committed output under the real out dir. A fresh regen /// that matches is clean; a mutated / missing / extra committed file is drift. -/// Crucially: the real out dir is never touched (we only write to temp). +/// Crucially: the real out dir is never touched, and nothing is written anywhere. /// public sealed class CodegenDriftTests : IDisposable { @@ -151,6 +151,22 @@ public void Drift_run_never_writes_to_the_real_out_dir() Assert.NotEqual(before, afterMutation); } + [Fact] + public void Verify_renders_in_memory_and_leaves_no_temp_files_behind() + { + // ADR-0062 / drive wear: the drift gate compares rendered bytes with disk in memory. It must + // never create a rendered tree (or any meta-verify-codegen-* directory) under the temp dir. + Gen(); + var tempRoot = Path.GetTempPath(); + var before = Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*").ToHashSet(); + var result = RunDrift(); + var after = Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*").ToHashSet(); + Assert.True(result.Clean); + Assert.Equal(before, after); + Assert.Empty(Directory.EnumerateFileSystemEntries(tempRoot, "meta-verify-codegen-*") + .Except(before)); + } + private static Dictionary SnapshotDir(string dir) { var snap = new Dictionary(StringComparer.Ordinal); diff --git a/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintUntrackedTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintUntrackedTests.cs new file mode 100644 index 0000000000..cda2475b2e --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintUntrackedTests.cs @@ -0,0 +1,46 @@ +// ADR-0062: a file the manifest does not record (one written outside the project root) is part of +// the stored outputs, so a skip needs it to exist. + +#nullable enable + +using MetaObjects.Codegen; +using Xunit; + +public sealed class GenFingerprintUntrackedTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "meta-untracked-" + Guid.NewGuid().ToString("N")); + private readonly string _outside = Path.Combine(Path.GetTempPath(), "meta-untracked-out-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + if (Directory.Exists(_outside)) Directory.Delete(_outside, true); + } + + private string Prepare() + { + Directory.CreateDirectory(Path.Combine(_root, "gen")); + Directory.CreateDirectory(_outside); + const string content = "// generated\n"; + File.WriteAllText(Path.Combine(_root, "gen", "A.cs"), content); + var outside = Path.Combine(_outside, "B.cs"); + File.WriteAllText(outside, content); + HashManifest.Save(Path.Combine(_root, ".metaobjects", ".gen-state"), + new Dictionary { ["gen/A.cs"] = HashManifest.ContentHash(content) }); + GenFingerprint.Write(_root, "model", "identity", [outside]); + return outside; + } + + [Fact] + public void AMissingOutputOutsideTheProjectBlocksTheSkipAndTheLocalNoDriftAnswer() + { + var outside = Prepare(); + Assert.True(GenFingerprint.CanSkipGen(_root, "model", "identity")); + Assert.True(GenFingerprint.MayAnswerNoDrift(_root, "model", "identity", full: false, _ => null)); + + File.Delete(outside); + + Assert.False(GenFingerprint.CanSkipGen(_root, "model", "identity")); + Assert.False(GenFingerprint.MayAnswerNoDrift(_root, "model", "identity", full: false, _ => null)); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs index 0dbbca4ddf..76a3f73685 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs @@ -307,7 +307,8 @@ public void Keep_refuses_to_replace_an_edited_file() var file = Path.Combine(Out, "Telemetry.g.cs"); File.AppendAllText(file, "// mine\n"); - var gen = Gen(); + // A hand edit makes gen render (ADR-0062 Amendment A); --force keeps the rerun explicit. + var gen = Gen("--force"); Assert.EndsWith("// mine\n", File.ReadAllText(file)); Assert.Contains("Refused to overwrite", gen.Out + gen.Err); Assert.DoesNotContain("handEdits", gen.Out + gen.Err); @@ -328,7 +329,7 @@ public void Overwrite_replaces_an_edited_file_and_rebaselines_it() Assert.Contains("edited by hand; its generator sets handEdits: Overwrite", drift.Err); Assert.Contains("to regenerate", drift.Err); - var gen = Gen(); + var gen = Gen("--force"); // explicit; an edited output would regenerate anyway Assert.Equal(0, gen.Code); Assert.Equal(fresh, File.ReadAllText(file)); Assert.Contains("overwrote hand-edited Telemetry.g.cs", gen.Out + gen.Err); diff --git a/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs index 541472b5f4..038afc290e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OverwriteHashManifestTests.cs @@ -334,6 +334,37 @@ public void OutputOutsideTheProject_IsWrittenButNotRecorded() Assert.Contains(result.Warnings, w => w.Contains("outside the project", StringComparison.Ordinal)); } + // ADR-0062 items 1 and 2: a rerun that changes nothing leaves the generated file AND the + // manifest untouched (timestamps kept), and a changed run saves the manifest once. + [Fact] + public void RerunWithNoChange_KeepsGeneratedFileAndManifestTimestamps() + { + const string content = "// \nv1\n"; + RunIn(OutDir, content, _root); + var manifest = Path.Combine(StateDir, ".hashes.json"); + var bytes = File.ReadAllBytes(manifest); + var stamp = DateTime.UtcNow.AddHours(-2); + File.SetLastWriteTimeUtc(TargetPath, stamp); + File.SetLastWriteTimeUtc(manifest, stamp); + + var again = RunIn(OutDir, content, _root); + + Assert.Equal("unchanged", again.Files[0].Status); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(TargetPath)); + Assert.Equal(stamp, File.GetLastWriteTimeUtc(manifest)); + Assert.Equal(bytes, File.ReadAllBytes(manifest)); + } + + [Fact] + public void ChangedRun_RewritesTheManifestWithTheNewHash() + { + RunIn(OutDir, "// \nv1\n", _root); + var second = RunIn(OutDir, "// \nv2\n", _root); + + Assert.Equal("written", second.Files[0].Status); + Assert.Equal(HashManifest.ContentHash("// \nv2\n"), Manifest()[Path.Combine("generated", "A.cs")]); + } + [Fact] public void TwoOutDirsUnderOneProject_GetDistinctKeys() { diff --git a/server/csharp/MetaObjects.Codegen/CodegenCli.cs b/server/csharp/MetaObjects.Codegen/CodegenCli.cs index 8bb057b73a..0363765229 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenCli.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenCli.cs @@ -529,10 +529,10 @@ public static IReadOnlyList ComposeGenerators( private static readonly string[] GenValueFlags = ["--out", "--namespace", "--generators", "--template-root", "--template-spec", "--column-naming", "--baseline"]; - private static readonly string[] GenBoolFlags = ["--emit-abstract-shapes", "--strict"]; + private static readonly string[] GenBoolFlags = ["--emit-abstract-shapes", "--strict", "--force"]; private static readonly string[] VerifyValueFlags = ["--out", "--namespace", "--generators", "--template-root", "--column-naming"]; - private static readonly string[] VerifyBoolFlags = ["--codegen", "--lax"]; + private static readonly string[] VerifyBoolFlags = ["--codegen", "--lax", "--full"]; /// The flags both commands share, parsed once. private sealed class OwnedArgs @@ -540,7 +540,7 @@ private sealed class OwnedArgs public string? MetadataDir, OutDir, TemplateRoot, TemplateSpecPath, ColumnNamingRaw, GeneratorsCsv; public string? Namespace; public string Baseline = "default"; - public bool EmitAbstractShapes, Codegen, Lax, Strict; + public bool EmitAbstractShapes, Codegen, Lax, Strict, Force, Full; /// 1.0 docs flags given (), in order. public List LegacyDocs = []; /// The usage error the arguments earn, or null. @@ -590,6 +590,8 @@ public static OwnedArgs Parse(string[] rest, string command, string[] valueFlags else if (flag == "--codegen") a.Codegen = true; else if (flag == "--lax") a.Lax = true; else if (flag == "--strict") a.Strict = true; + else if (flag == "--force") a.Force = true; // ADR-0062: render even when nothing changed + else if (flag == "--full") a.Full = true; // ADR-0062: verify renders even when it could answer from the key } else { @@ -647,7 +649,26 @@ private static bool TryConfiguredOutDir(string? metadataDir, out string? outDir) private const string GenCommandName = "dotnet meta gen"; private const string VerifyCommandName = "dotnet meta verify --codegen"; + /// ADR-0062: the stored key is forgotten by any run that gets as far as the project's + /// metadata and does not skip or store a new key, so a failed run never leaves one that + /// vouches for the output. + private sealed class KeyGate { public string? ProjectRoot; public bool Keep; } + private static int RunGenArgs(string[] rest, IReadOnlyList declared) + { + var gate = new KeyGate(); + try { return RunGenCore(rest, declared, gate); } + finally { if (gate.ProjectRoot is { } root && !gate.Keep) GenFingerprint.Delete(root); } + } + + /// The generator-identity options of a run: the output-changing flags, as resolved. + private static GenFingerprint.Options KeyOptions(OwnedArgs a, string outDir, string? ns) => new() + { + OutDir = outDir, Namespace = ns, Generators = a.GeneratorsCsv, TemplateRoot = a.TemplateRoot, + TemplateSpec = a.TemplateSpecPath, EmitAbstractShapes = a.EmitAbstractShapes, Strict = a.Strict, Baseline = a.Baseline, + }; + + private static int RunGenCore(string[] rest, IReadOnlyList declared, KeyGate gate) { var a = OwnedArgs.Parse(rest, GenCommandName, GenValueFlags, GenBoolFlags); if (a.Refusal is not null) @@ -701,6 +722,7 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) if (ResolveOrReport(a.MetadataDir) is not { } meta) return 2; var projectRoot = a.MetadataDir is not null ? ProjectRootFor(a.MetadataDir) : Directory.GetCurrentDirectory(); + gate.ProjectRoot = projectRoot; if (LegacyTemplateSpecFound(declared, a.TemplateSpecPath, projectRoot) is { } legacySpec) { Console.Error.WriteLine(LegacyTemplateSpec(GenCommandName, legacySpec)); @@ -753,6 +775,20 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) WarnUnknownAttrs(meta); genLoad = meta.Load(); } + // ADR-0062: the key is the LOADED model plus what generates, both read before anything renders. + // A match, with every file the manifest records still on disk, skips the render and writes nothing. + var cwd = Directory.GetCurrentDirectory(); + var modelHash = ModelHash.Of(genLoad.Root).Model; + var identity = GenFingerprint.Key(GenFingerprint.IdentityEntries( + projectRoot, cwd, KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), suite.SelectMany(g => g.ExtraInputs))); + if (!a.Force && suite.All(g => g.Cacheable) && GenFingerprint.CanSkipGen(projectRoot, modelHash, identity)) + { + gate.Keep = true; + Console.WriteLine($"{GenCommandName}: nothing changed since the last run; skipped (use --force to regenerate)"); + return 0; + } + GenFingerprint.Delete(projectRoot); + var outcome = RunGen(genLoad, a.OutDir, a.Namespace ?? meta.Namespace, a.EmitAbstractShapes, suite, projectRoot, a.Baseline, includeNames: declared.Any(g => g.Name == "names"), // Only a run of the whole declared list can tell a stale file from one the @@ -773,6 +809,11 @@ private static int RunGenArgs(string[] rest, IReadOnlyList declared) // A refusal is a FAILED gate, matching TypeScript's `meta gen` (exit 1): an adopter // wiring gen into CI as a drift gate must not be green while codegen refused to write. var refusedCount = outcome.Result!.Files.Count(f => f.Status == "refused"); + if (refusedCount == 0 && outcome.Result!.Complete && suite.All(g => g.Cacheable)) + { + GenFingerprint.Write(projectRoot, modelHash, identity, outcome.Result!.OutsidePaths); + gate.Keep = true; + } if (refusedCount > 0) { Console.Error.WriteLine( @@ -960,6 +1001,18 @@ private static int RunVerifyArgs(string[] rest, IReadOnlyList declar GenStateDir = Path.Combine(projectRoot, ".metaobjects", ".gen-state"), ProjectRoot = projectRoot, }; + // ADR-0062: locally, an unchanged key and output that still hashes to what gen recorded answer + // "no drift" without rendering. CI and --full always render. + if (suite.All(g => g.Cacheable) && GenFingerprint.MayAnswerNoDrift( + projectRoot, ModelHash.Of(load.Root).Model, + GenFingerprint.Key(GenFingerprint.IdentityEntries( + projectRoot, Directory.GetCurrentDirectory(), KeyOptions(a, a.OutDir, a.Namespace ?? meta.Namespace), + suite.SelectMany(g => g.ExtraInputs))), + a.Full)) + { + Console.WriteLine($"{VerifyCommandName}: OK (nothing changed since the last gen; --full renders and compares)"); + return 0; + } var result = CodegenDrift.Compute(config, load.Root, suite, narrowed: a.Selection is { Count: > 0 }); if (result.Error is not null) { diff --git a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs index 29711710e4..cfd125fc3d 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs @@ -81,75 +81,72 @@ public static Result Compute(GenConfig config, MetaRoot root, IReadOnlyList Path.Combine(virtualRoot, i.ToString())).ToList(); + // No manifest and no sweep for the throwaway regen: it records nothing and deletes nothing. + var tempConfig = config with { OutDir = temps[0], GenStateDir = null, ProjectRoot = null, SweepOrphans = false }; + var rendered = new Dictionary(StringComparer.Ordinal); + CodegenRunner.RunResult regen; try { - // Regenerate the SAME suite into the temp tree, each directory into a temp - // directory of its own. A fresh temp dir means every file is written (no - // @generated-marker skip), so the temp tree is the canonical "what gen would - // produce right now". - var temps = roots.Select((_, i) => Path.Combine(tempRoot, i.ToString())).ToList(); - // No manifest and no sweep for the throwaway regen: it records nothing and deletes - // nothing, and a fresh temp tree writes every file either way. - var tempConfig = config with { OutDir = temps[0], GenStateDir = null, ProjectRoot = null, SweepOrphans = false }; - CodegenRunner.RunResult regen; - try - { - regen = CodegenRunner.Run(tempConfig, root, generators, - g => temps[roots.FindIndex(r => r.Committed == Path.GetFullPath(realRootFor(g)))]); - } - catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) - { - return new Result { Clean = false, Error = $"verify --codegen: {ex.Message}" }; - } - var overwriteDirs = CodegenRunner.OverwriteDirs(generators, realRootFor, config.OutDir); - - var drifted = new SortedSet(StringComparer.Ordinal); - var lines = new List(); - var editedOrphans = new SortedSet(StringComparer.Ordinal); - // The manifest gen wrote, when the caller names the project. With write records, an - // extra file is convicted only when gen recorded writing it, the jurisdiction gen's - // orphan sweep deletes in; with none, a stale file cannot be told from a stranger's, - // and every extra file is reported as before. - var manifest = config.GenStateDir is { } gs && config.ProjectRoot is not null - ? HashManifest.Load(gs) : null; - var orphans = manifest is { Count: > 0 } ? new OrphanContext(manifest, config.ProjectRoot!) : null; - var handEdits = new HandEditsContext(regen.OverwritePaths, overwriteDirs); - for (var i = 0; i < roots.Count; i++) - { - // A directory nested in this one is another entry's, and is compared as its own. - var nested = roots.Where((r, j) => j != i && IsUnder(r.Committed, roots[i].Committed)) - .Select(r => r.Committed).ToList(); - Diff(roots[i].Committed, nested, temps[i], roots[i].Label, !narrowed, orphans, handEdits, - drifted, lines, editedOrphans); - } - - return new Result - { - Clean = drifted.Count == 0, - DriftedFiles = drifted.ToList(), - Lines = lines, - EditedOrphans = editedOrphans.ToList(), - }; + regen = CodegenRunner.Run(tempConfig, root, generators, + g => temps[roots.FindIndex(r => r.Committed == Path.GetFullPath(realRootFor(g)))], rendered); } - finally + catch (Exception ex) when (ex is ArgumentException or InvalidOperationException) { - try { if (Directory.Exists(tempRoot)) Directory.Delete(tempRoot, recursive: true); } - catch { /* best effort */ } + return new Result { Clean = false, Error = $"verify --codegen: {ex.Message}" }; } + var overwriteDirs = CodegenRunner.OverwriteDirs(generators, realRootFor, config.OutDir); + + var drifted = new SortedSet(StringComparer.Ordinal); + var lines = new List(); + var editedOrphans = new SortedSet(StringComparer.Ordinal); + // The manifest gen wrote, when the caller names the project. With write records, an + // extra file is convicted only when gen recorded writing it, the jurisdiction gen's + // orphan sweep deletes in; with none, a stale file cannot be told from a stranger's, + // and every extra file is reported as before. + var manifest = config.GenStateDir is { } gs && config.ProjectRoot is not null + ? HashManifest.Load(gs) : null; + var orphans = manifest is { Count: > 0 } ? new OrphanContext(manifest, config.ProjectRoot!) : null; + var handEdits = new HandEditsContext(regen.OverwritePaths, overwriteDirs); + for (var i = 0; i < roots.Count; i++) + { + // A directory nested in this one is another entry's, and is compared as its own. + var nested = roots.Where((r, j) => j != i && IsUnder(r.Committed, roots[i].Committed)) + .Select(r => r.Committed).ToList(); + var fresh = rendered + .Where(kv => IsUnder(kv.Key, temps[i])) + .ToDictionary(kv => Path.GetRelativePath(temps[i], kv.Key).Replace(Path.DirectorySeparatorChar, '/'), + kv => kv.Value, StringComparer.Ordinal); + Diff(roots[i].Committed, nested, temps[i], fresh, roots[i].Label, !narrowed, orphans, handEdits, + drifted, lines, editedOrphans); + } + + return new Result + { + Clean = drifted.Count == 0, + DriftedFiles = drifted.ToList(), + Lines = lines, + EditedOrphans = editedOrphans.ToList(), + }; } /// Compare one committed directory, less the directories, with its /// fresh regen, adding each difference. A committed file the regen does not emit is reported only when /// . private static void Diff( - string committed, IReadOnlyList nested, string fresh, string label, bool reportExtra, + string committed, IReadOnlyList nested, string fresh, IReadOnlyDictionary freshContent, + string label, bool reportExtra, OrphanContext? orphans, HandEditsContext handEdits, SortedSet drifted, List lines, SortedSet editedOrphans) { var committedFiles = ListFiles(committed); committedFiles.RemoveWhere(rel => nested.Any(n => IsUnder(Path.Combine(committed, rel), n))); - var freshFiles = ListFiles(fresh); + var freshFiles = freshContent.Keys.ToHashSet(StringComparer.Ordinal); foreach (var rel in committedFiles.Union(freshFiles).OrderBy(s => s, StringComparer.Ordinal)) { var shown = label + rel; @@ -197,7 +194,7 @@ private static void Diff( else { var a = File.ReadAllText(Path.Combine(committed, rel)); - var b = File.ReadAllText(Path.Combine(fresh, rel)); + var b = freshContent[rel]; if (!string.Equals(a, b, StringComparison.Ordinal)) { drifted.Add(shown); diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index 4aa2ffa2f9..a9191be706 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -11,6 +11,7 @@ // (it needs a full snapshot of prior content plus `git merge-file`). Here the outcome // for a diverged file is a refusal rather than a merge — see HashManifest. +#nullable enable using MetaObjects.Meta; namespace MetaObjects.Codegen; @@ -27,6 +28,14 @@ public sealed record RunResult(IReadOnlyList Files, IReadOnlyListAbsolute paths emitted by an entry declaring : /// verify --codegen reads it to tell that gen replaces an edit to one of them. public IReadOnlySet OverwritePaths { get; init; } = new HashSet(); + + /// ADR-0062: false when a file was refused, adopted, or an edited orphan was kept. + /// Only a complete run may store a key. + public bool Complete { get; init; } = true; + + /// ADR-0062: absolute paths written outside the project root. The manifest records no + /// file there, so the stored key lists them and a skip needs each to exist. + public IReadOnlyList OutsidePaths { get; init; } = []; } public static RunResult Run(GenConfig config, MetaRoot root, IReadOnlyList generators) @@ -43,7 +52,8 @@ internal static Func OutRootFor(GenConfig config) => /// directory of each generator chosen by : the drift gate points /// every entry at a temporary tree of its own. internal static RunResult Run( - GenConfig config, MetaRoot root, IReadOnlyList generators, Func outRoot) + GenConfig config, MetaRoot root, IReadOnlyList generators, Func outRoot, + IDictionary? capture = null) { config = PackageBindingResolver.WithDerivedHome(config, root); var warnings = new List(); @@ -76,7 +86,8 @@ internal static RunResult Run( CSharpNaming.AssertNoCollectionNameCollisions( [.. ctx.Entities, .. root.Objects().Where(o => ReportRows.IsViewBacked(o) && root.InScope(o))]); - Directory.CreateDirectory(config.OutDir); + // With a capture sink nothing touches the disk: the drift gate renders into memory and compares. + if (capture is null) Directory.CreateDirectory(config.OutDir); var results = new List(); // Two generators (or a name collision between an entity and a value-object // POCO) writing the same path would silently clobber each other; error @@ -86,62 +97,78 @@ internal static RunResult Run( var adopted = new List(); var overwritePaths = new HashSet(StringComparer.Ordinal); var untracked = 0; + var outsidePaths = new List(); + var sweepRefused = false; // Captured BEFORE any write, because the first write creates the manifest — // read it afterwards and every project looks migrated. var hadManifest = config.GenStateDir is null || HashManifest.Exists(config.GenStateDir); + // ADR-0062 — loaded once, saved once and only when it changed (see HashManifest.Session). + var manifest = config.GenStateDir is { } stateDir ? new HashManifest.Session(stateDir) : null; - foreach (var generator in generators) + // Saved even when a generator throws, so the manifest keeps matching the files already written. + try { - var genRoot = outRoot(generator); - // An entry with its own directory reports its files by that directory, so a reader - // can tell the api reference's README.md from one under --out. - var shown = generator.OutDir is { Length: > 0 } own ? own.TrimEnd('/', '\\') + "/" : ""; - foreach (var file in generator.Generate(ctx)) + foreach (var generator in generators) { - var full = Path.GetFullPath(Path.Combine(genRoot, file.Path)); - if (!emitted.TryAdd(full, generator.Name)) - throw new InvalidOperationException( - $"duplicate generated output path \"{file.Path}\" — emitted by both " + - $"\"{emitted[full]}\" and \"{generator.Name}\"."); - if (generator.HandEdits == HandEdits.Overwrite) overwritePaths.Add(full); - // The manifest key. Project-root-relative when the caller names a project, - // so two runs with different --out cannot collide on one entry inside the - // single manifest that is anchored on that project. `file.Path` rides - // along as the legacy spelling — it is what the manifest used to be keyed - // by, and it is still what a refusal is REPORTED as (the name the reader - // sees under --out). - // - // BOTH SIDES NORMALISED THE SAME WAY. `full` and ProjectRoot both come - // from Path.GetFullPath — normalised, NOT link-resolved — so the relative - // path between them is the path between the two directories. Resolving - // only one side would, under a directory symlink, walk every key out of - // the project; nothing would then match and a drift gate would report - // "in sync" over stale output. - var key = config.ProjectRoot is { } projectRoot - ? Path.GetRelativePath(Path.GetFullPath(projectRoot), full) - : file.Path; - // A file written OUTSIDE the project has no place in the project's - // manifest: its key would be `../`-relative and committed into - // .hashes.json. It gets the manifest-less rule a run with no project gets. - var outside = config.ProjectRoot is not null - && (key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key)); - if (outside) untracked++; - var status = WriteOne( - outside ? config with { GenStateDir = null } : config, - full, file.Path, key, file.Content, warnings, - overwriteEdits: generator.HandEdits == HandEdits.Overwrite); - var reported = shown + file.Path; - if (status == OverwroteEdit) + var genRoot = outRoot(generator); + // An entry with its own directory reports its files by that directory, so a reader + // can tell the api reference's README.md from one under --out. + var shown = generator.OutDir is { Length: > 0 } own ? own.TrimEnd('/', '\\') + "/" : ""; + foreach (var file in generator.Generate(ctx)) { - warnings.Add( - $"overwrote hand-edited {reported} with fresh output (handEdits: Overwrite on {generator.Name})"); - status = "written"; + var full = Path.GetFullPath(Path.Combine(genRoot, file.Path)); + if (!emitted.TryAdd(full, generator.Name)) + throw new InvalidOperationException( + $"duplicate generated output path \"{file.Path}\" — emitted by both " + + $"\"{emitted[full]}\" and \"{generator.Name}\"."); + if (generator.HandEdits == HandEdits.Overwrite) overwritePaths.Add(full); + if (capture is not null) + { + capture[full] = file.Content; + results.Add(new WriteResult(shown + file.Path, "written")); + continue; + } + // The manifest key. Project-root-relative when the caller names a project, + // so two runs with different --out cannot collide on one entry inside the + // single manifest that is anchored on that project. `file.Path` rides + // along as the legacy spelling — it is what the manifest used to be keyed + // by, and it is still what a refusal is REPORTED as (the name the reader + // sees under --out). + // + // BOTH SIDES NORMALISED THE SAME WAY. `full` and ProjectRoot both come + // from Path.GetFullPath — normalised, NOT link-resolved — so the relative + // path between them is the path between the two directories. Resolving + // only one side would, under a directory symlink, walk every key out of + // the project; nothing would then match and a drift gate would report + // "in sync" over stale output. + var key = config.ProjectRoot is { } projectRoot + ? Path.GetRelativePath(Path.GetFullPath(projectRoot), full) + : file.Path; + // A file written OUTSIDE the project has no place in the project's + // manifest: its key would be `../`-relative and committed into + // .hashes.json. It gets the manifest-less rule a run with no project gets. + var outside = config.ProjectRoot is not null + && (key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key)); + if (outside) { untracked++; outsidePaths.Add(full); } + var status = WriteOne( + outside ? config with { GenStateDir = null } : config, + outside ? null : manifest, + full, file.Path, key, file.Content, warnings, + overwriteEdits: generator.HandEdits == HandEdits.Overwrite); + var reported = shown + file.Path; + if (status == OverwroteEdit) + { + warnings.Add( + $"overwrote hand-edited {reported} with fresh output (handEdits: Overwrite on {generator.Name})"); + status = "written"; + } + results.Add(new WriteResult(reported, status)); + if (status == "refused") refused.Add(reported); + else if (status == "adopted") adopted.Add(reported); } - results.Add(new WriteResult(reported, status)); - if (status == "refused") refused.Add(reported); - else if (status == "adopted") adopted.Add(reported); } } + finally { manifest?.Save(); } if (config.SweepOrphans && config.GenStateDir is { } genState && config.ProjectRoot is { } project && config.Baseline != "adopt") @@ -156,7 +183,7 @@ internal static RunResult Run( foreach (var path in swept.Removed) results.Add(new WriteResult(path, "removed")); foreach (var path in swept.Discarded) warnings.Add($"deleted hand-edited {path}, which no generator emits any more (handEdits: Overwrite)"); - if (swept.Refused.Count > 0) warnings.Add(OrphanSweep.RefusedMessage(swept.Refused)); + if (swept.Refused.Count > 0) { sweepRefused = true; warnings.Add(OrphanSweep.RefusedMessage(swept.Refused)); } } if (untracked > 0) @@ -166,7 +193,12 @@ internal static RunResult Run( "does not apply to them beyond the marker rule."); ReportRefusals(refused, hadManifest, warnings); ReportAdoptions(adopted, warnings); - return new RunResult(results, warnings) { OverwritePaths = overwritePaths }; + return new RunResult(results, warnings) + { + OverwritePaths = overwritePaths, + Complete = refused.Count == 0 && adopted.Count == 0 && !sweepRefused, + OutsidePaths = outsidePaths, + }; } /// @@ -185,7 +217,7 @@ internal static RunResult Run( /// /// private static string WriteOne( - GenConfig config, string full, string relPath, string key, string content, + GenConfig config, HashManifest.Session? manifest, string full, string relPath, string key, string content, List warnings, bool overwriteEdits = false) { // The out-dir-relative spelling this file may already be recorded under, from @@ -194,7 +226,7 @@ private static string WriteOne( var legacyKey = string.Equals(key, relPath, StringComparison.Ordinal) ? null : relPath; var exists = File.Exists(full); - if (config.GenStateDir is null) + if (config.GenStateDir is null || manifest is null) { if (exists && !File.ReadAllText(full).Contains(GeneratedMarker, StringComparison.Ordinal)) { @@ -210,7 +242,7 @@ private static string WriteOne( if (!exists) { WriteFile(full, content); - HashManifest.Record(config.GenStateDir, key, content, legacyKey); + manifest!.Record(key, content, legacyKey); // "written", not "new": this port's status vocabulary does not distinguish a // create from an overwrite, and callers key on it. The manifest ADDS // "unchanged" and "refused" without redefining what was already there — @@ -223,23 +255,23 @@ private static string WriteOne( { // Record it: a first run over already-correct output should leave the file // recognisable as ours next time. - HashManifest.Record(config.GenStateDir, key, content, legacyKey); + manifest!.Record(key, content, legacyKey); return "unchanged"; } - if (HashManifest.IsPristine(config.GenStateDir, key, current, legacyKey)) + if (manifest!.IsPristine(key, current, legacyKey)) { WriteFile(full, content); - HashManifest.Record(config.GenStateDir, key, content, legacyKey); + manifest!.Record(key, content, legacyKey); return "written"; } // Edited since we wrote it, and the entry says to discard hand edits. A file we have // no record of writing is never ours to replace, whatever the setting. - if (overwriteEdits && HashManifest.IsRecorded(config.GenStateDir, key, legacyKey)) + if (overwriteEdits && manifest!.IsRecorded(key, legacyKey)) { WriteFile(full, content); - HashManifest.Record(config.GenStateDir, key, content, legacyKey); + manifest!.Record(key, content, legacyKey); return OverwroteEdit; } @@ -252,7 +284,7 @@ private static string WriteOne( // `current`, never `content`: recording fresh output would claim we wrote a // file we did not, and the next run would read the adopter's file as edited // and refuse all over again — the loop this mode exists to end. - HashManifest.Record(config.GenStateDir, key, current, legacyKey); + manifest!.Record(key, current, legacyKey); return "adopted"; } diff --git a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs new file mode 100644 index 0000000000..fc379cb9fd --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs @@ -0,0 +1,352 @@ +// ADR-0062 — the key of a whole `gen` run and the skip decision built on it. +// +// The key has two halves, both computed AFTER the metadata loads and BEFORE any generator renders +// (this runs in the codegen project's process, where the generator list is built): +// +// model the hash of the LOADED model (ModelHash): never of the metadata source files, so a +// reformatted or re-split file that loads to the same model does not change it +// identity one key over small named entries (kind, name, sha-256) describing what generates: +// engine the built code of MetaObjects, MetaObjects.Render, MetaObjects.Codegen +// and the codegen project's own assembly (owned generators compiled in), +// plus the content of every project the codegen project references by +// path (a linked or source checkout of the engine) +// generator every source file of the codegen project (declared list, options, owned +// generators, csproj), bin/ and obj/ aside +// build-config Directory.Build.props, Directory.Packages.props, global.json, +// nuget.config above it +// config every file under the project's `.metaobjects/` (config.json, dependency +// lock and snapshots), `.gen-state` aside +// flag the output-changing flags: --out, --namespace, --generators, +// --template-root, --template-spec, --emit-abstract-shapes, --strict, baseline +// template every file under prompts/, templates/, --template-root, and the template spec +// extra every path a generator declared in IGenerator.ExtraInputs +// format this format's version +// +// Every identity input is computable in the codegen process, which is where the decision runs, so +// nothing is stored beside the two hashes. The key may be wrong only in the safe direction: +// anything in doubt is counted. Timestamps are never an input. + +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; + +namespace MetaObjects.Codegen; + +public static class GenFingerprint +{ + /// Bumped when an entry kind is added or its meaning changes, so an old file never matches. + public const int FormatVersion = 3; + + /// The stored key's file name inside .metaobjects/.gen-state/. One per port. + public const string FileName = ".fingerprint-csharp.json"; + + /// One named input: what kind it is, which one, and the SHA-256 of its content. + public sealed record Entry(string Kind, string Name, string Sha256); + + /// The flags that change what gen writes. --force and --full are not among them. + public sealed record Options + { + public string? OutDir { get; init; } + public string? Namespace { get; init; } + public string? Generators { get; init; } + public string? TemplateRoot { get; init; } + public string? TemplateSpec { get; init; } + public bool EmitAbstractShapes { get; init; } + public bool Strict { get; init; } + public string Baseline { get; init; } = "default"; + } + + // ------------------------------------------------------------------ hashing + + private static string Sha(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + private static string Sha(string text) => Sha(Encoding.UTF8.GetBytes(text)); + + private static string Rel(string projectRoot, string full) + { + var rel = Path.GetRelativePath(Path.GetFullPath(projectRoot), Path.GetFullPath(full)); + return (rel.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(rel) ? Path.GetFullPath(full) : rel) + .Replace(Path.DirectorySeparatorChar, '/'); + } + + private static bool InSkippedDir(string path, params string[] names) => + path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Any(s => names.Contains(s)); + + private static IEnumerable FilesUnder(string dir, params string[] skipDirNames) + { + if (!Directory.Exists(dir)) return []; + return Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories) + .Where(f => !InSkippedDir(Path.GetRelativePath(dir, f), skipDirNames)) + .OrderBy(f => f, StringComparer.Ordinal); + } + + private static IEnumerable FileEntries(string kind, string projectRoot, IEnumerable files) + { + foreach (var f in files) + { + string sha; + try { sha = Sha(File.ReadAllBytes(f)); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { sha = "unreadable"; } + yield return new Entry(kind, Rel(projectRoot, f), sha); + } + } + + /// The fold of a set of entries into one key: sha-256 over their sorted lines. + public static string Key(IEnumerable entries) => + Sha(string.Join("\n", entries.Select(e => $"{e.Kind}\t{e.Name}\t{e.Sha256}").Order(StringComparer.Ordinal))); + + // ------------------------------------------------------------------ the identity + + private static readonly Regex ProjectRef = new( + " + Directory.Exists(Path.Combine(dir.FullName, ".git")) || File.Exists(Path.Combine(dir.FullName, ".git")); + + /// The built code that generates: the engine assemblies and the codegen project's own. + private static IEnumerable BuiltAssemblies() + { + var assemblies = new[] + { + typeof(GenFingerprint).Assembly, typeof(MetaObjects.Meta.MetaRoot).Assembly, + typeof(MetaObjects.Render.RenderException).Assembly, Assembly.GetEntryAssembly(), + }; + return assemblies.Where(a => a is not null).Select(a => a!.Location) + .Where(l => l.Length > 0 && File.Exists(l)).Distinct(); + } + + private static IEnumerable EngineEntries(string projectRoot) + { + foreach (var e in FileEntries("engine", projectRoot, BuiltAssemblies().Order(StringComparer.Ordinal))) + yield return e; + + // A project the codegen project references by path is a linked or source checkout of the + // engine: its content is part of the identity, so it changes when its source does. + var codegen = Path.Combine(projectRoot, "codegen"); + var visited = new HashSet(StringComparer.Ordinal); + var queue = new Queue(Directory.Exists(codegen) + ? Directory.EnumerateFiles(codegen, "*.csproj", SearchOption.AllDirectories) + .Where(f => !InSkippedDir(Path.GetRelativePath(codegen, f), "bin", "obj")) + : []); + while (queue.Count > 0) + { + var csproj = queue.Dequeue(); + string text; + try { text = File.ReadAllText(csproj); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { continue; } + foreach (Match m in ProjectRef.Matches(text)) + { + var target = Path.GetFullPath(Path.Combine( + Path.GetDirectoryName(csproj)!, m.Groups[1].Value.Replace('\\', Path.DirectorySeparatorChar))); + if (!File.Exists(target) || !visited.Add(target)) continue; + foreach (var e in FileEntries("engine-source", projectRoot, + FilesUnder(Path.GetDirectoryName(target)!, "bin", "obj", ".git", "node_modules"))) + yield return e; + queue.Enqueue(target); + } + } + } + + /// The named entries of what generates: everything of a run except the model. + public static IReadOnlyList IdentityEntries( + string projectRoot, string cwd, Options o, IEnumerable extras) + { + var entries = new List { new("format", "fingerprint", Sha(FormatVersion.ToString())) }; + + void Flag(string name, string? value) => entries.Add(new Entry("flag", name, Sha(value ?? ""))); + Flag("out", o.OutDir is null ? null : Path.GetFullPath(Path.Combine(cwd, o.OutDir))); + Flag("namespace", o.Namespace); + Flag("generators", o.Generators); + Flag("template-root", o.TemplateRoot is null ? null : Path.GetFullPath(Path.Combine(cwd, o.TemplateRoot))); + Flag("template-spec", o.TemplateSpec is null ? null : Path.GetFullPath(Path.Combine(cwd, o.TemplateSpec))); + Flag("emit-abstract-shapes", o.EmitAbstractShapes ? "true" : "false"); + Flag("strict", o.Strict ? "true" : "false"); + Flag("baseline", o.Baseline); + + // The project's own config: the nearest `.metaobjects/` at or above the project. + for (var dir = new DirectoryInfo(Path.GetFullPath(projectRoot)); dir is not null; dir = dir.Parent) + { + var cfgDir = Path.Combine(dir.FullName, ".metaobjects"); + if (File.Exists(Path.Combine(cfgDir, "config.json"))) + { + entries.AddRange(FileEntries("config", projectRoot, FilesUnder(cfgDir, ".gen-state"))); + break; + } + if (IsRepoRoot(dir)) break; + } + + entries.AddRange(EngineEntries(projectRoot)); + entries.AddRange(FileEntries("generator", projectRoot, + FilesUnder(Path.Combine(projectRoot, "codegen"), "bin", "obj"))); + for (var dir = new DirectoryInfo(Path.GetFullPath(projectRoot)); dir is not null; dir = dir.Parent) + { + foreach (var name in BuildConfigFiles) + { + var f = Path.Combine(dir.FullName, name); + if (File.Exists(f)) entries.AddRange(FileEntries("build-config", projectRoot, [f])); + } + if (IsRepoRoot(dir)) break; + } + + var templateDirs = new List + { + Path.Combine(cwd, CodegenCli.DefaultPromptsDir), Path.Combine(cwd, CodegenCli.LegacyTemplatesDir), + }; + if (o.TemplateRoot is not null) templateDirs.Add(Path.GetFullPath(Path.Combine(cwd, o.TemplateRoot))); + foreach (var d in templateDirs.Select(Path.GetFullPath).Distinct()) + entries.AddRange(FileEntries("template", projectRoot, FilesUnder(d))); + var specPath = o.TemplateSpec is not null + ? Path.GetFullPath(Path.Combine(cwd, o.TemplateSpec)) + : Path.Combine(projectRoot, CodegenCli.TemplateSpecFileName); + if (File.Exists(specPath)) entries.AddRange(FileEntries("template", projectRoot, [specPath])); + + foreach (var extra in extras.Distinct(StringComparer.Ordinal)) + { + var full = Path.GetFullPath(Path.Combine(cwd, extra)); + if (Directory.Exists(full)) entries.AddRange(FileEntries("extra", projectRoot, FilesUnder(full))); + else if (File.Exists(full)) entries.AddRange(FileEntries("extra", projectRoot, [full])); + else entries.Add(new Entry("extra", Rel(projectRoot, full), "missing")); + } + return entries; + } + + // ------------------------------------------------------------------ the stored key + + /// The two halves a successful run stored. + public sealed record Stored( + string Model, string Identity, IReadOnlyDictionary Outputs, IReadOnlyList Untracked); + + private static string GenStateDir(string projectRoot) => Path.Combine(projectRoot, ".metaobjects", ".gen-state"); + private static string PathFor(string projectRoot) => Path.Combine(GenStateDir(projectRoot), FileName); + + public static Stored? Read(string projectRoot) + { + try + { + if (!File.Exists(PathFor(projectRoot))) return null; + using var doc = JsonDocument.Parse(File.ReadAllText(PathFor(projectRoot))); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object + || !root.TryGetProperty("format", out var f) || f.ValueKind != JsonValueKind.Number || f.GetInt32() != FormatVersion + || !root.TryGetProperty("model", out var m) || m.ValueKind != JsonValueKind.String + || !root.TryGetProperty("identity", out var i) || i.ValueKind != JsonValueKind.String + || !root.TryGetProperty("outputs", out var o) || o.ValueKind != JsonValueKind.Object) return null; + var outputs = new Dictionary(StringComparer.Ordinal); + foreach (var prop in o.EnumerateObject()) + { + if (prop.Value.ValueKind != JsonValueKind.String) return null; + outputs[prop.Name] = prop.Value.GetString()!; + } + var untracked = new List(); + if (root.TryGetProperty("untracked", out var u)) + { + if (u.ValueKind != JsonValueKind.Array) return null; + foreach (var item in u.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.String) return null; + untracked.Add(item.GetString()!); + } + } + return new Stored(m.GetString()!, i.GetString()!, outputs, untracked); + } + catch (Exception e) when (e is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException) + { + return null; + } + } + + /// Forget the stored key: a real run does this before it writes anything. + public static void Delete(string projectRoot) + { + try { File.Delete(PathFor(projectRoot)); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { } + } + + /// Store the key of a fully successful run. + /// + /// Amendment A: also records outputs, the hash of every manifest-recorded file as the run + /// left it on disk. When a recorded file is missing no key is stored at all. + /// + public static void Write( + string projectRoot, string model, string identity, IEnumerable? untracked = null) + { + var outputs = new SortedDictionary(StringComparer.Ordinal); + if (ManifestOf(projectRoot) is { } manifest) + foreach (var key in manifest.Keys) + { + var hash = DiskHash(projectRoot, key); + if (hash is null) return; + outputs[key] = hash; + } + Directory.CreateDirectory(GenStateDir(projectRoot)); + var json = JsonSerializer.Serialize( + new + { + format = FormatVersion, model, identity, outputs, + untracked = (untracked ?? []).Order(StringComparer.Ordinal).ToArray(), + }, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(PathFor(projectRoot), json + "\n"); + } + + private static string? DiskHash(string projectRoot, string key) + { + var path = Path.Combine(projectRoot, key); + try { return File.Exists(path) ? HashManifest.ContentHash(File.ReadAllText(path)) : null; } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; } + } + + // ------------------------------------------------------------------ the decisions + + private static Dictionary? ManifestOf(string projectRoot) => + HashManifest.Exists(GenStateDir(projectRoot)) ? HashManifest.Load(GenStateDir(projectRoot)) : null; + + private static bool MatchesStored(string projectRoot, string model, string identity) => + Read(projectRoot) is { } s && s.Model == model && s.Identity == identity; + + /// Whether gen may skip rendering: the model and identity match the stored key and + /// every file the manifest records still hashes to the value the stored run left. The caller has ruled out --force. + public static bool CanSkipGen(string projectRoot, string model, string identity) + { + if (!MatchesStored(projectRoot, model, identity)) return false; + if (ManifestOf(projectRoot) is not { } manifest) return false; + // Amendment A: every recorded file must still be what the stored run left. A missing entry is a mismatch. + var stored = Read(projectRoot)!; + return manifest.Keys.All(k => stored.Outputs.TryGetValue(k, out var h) && DiskHash(projectRoot, k) == h) + && stored.Untracked.All(File.Exists); + } + + /// Whether the CI environment variable says this is a CI run. + public static bool InCi(Func? getenv = null) + { + var v = (getenv ?? Environment.GetEnvironmentVariable)("CI"); + return !string.IsNullOrEmpty(v) && !v.Equals("0", StringComparison.Ordinal) + && !v.Equals("false", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Whether a LOCAL verify --codegen may answer "no drift" without rendering: not CI, not + /// --full, the stored key matches, and every manifest file still hashes to its record. + /// + public static bool MayAnswerNoDrift( + string projectRoot, string model, string identity, bool full, Func? getenv = null) + { + if (full || InCi(getenv)) return false; + if (!MatchesStored(projectRoot, model, identity)) return false; + if (ManifestOf(projectRoot) is not { } manifest) return false; + if (!Read(projectRoot)!.Untracked.All(File.Exists)) return false; + foreach (var (key, recorded) in manifest) + { + var path = Path.Combine(projectRoot, key); + try + { + if (!File.Exists(path) || HashManifest.ContentHash(File.ReadAllText(path)) != recorded) return false; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return false; } + } + return true; + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 748cf34fbf..cdb95a7a9f 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -399,6 +399,22 @@ public interface IGenerator /// ?format=csv|json|xml branch: see . /// int? ReportExportMaxRows => null; + + /// + /// ADR-0062 — whether a run that includes this entry may be skipped when the model and everything + /// that generates are unchanged. true, the default, claims that the output depends only on + /// the model, the project's config, this entry's own source and the files named by + /// . An entry that reads anything else (an environment variable, the + /// network, the clock) answers false: a run that includes it never skips, and never stores a key. + /// + bool Cacheable => true; + + /// + /// ADR-0062 — paths (relative to the run's directory, or absolute) of files or directories this + /// entry reads besides the metadata and its own source. Their content joins the run's identity, so + /// editing one renders again. Empty by default. + /// + IReadOnlyList ExtraInputs => []; } /// A generator entry's handEdits setting: what a run does with a hand-edited file. @@ -433,6 +449,10 @@ internal sealed class HandEditsGenerator(IGenerator inner, HandEdits handEdits) /// public int? ReportExportMaxRows => Inner.ReportExportMaxRows; /// + public bool Cacheable => Inner.Cacheable; + /// + public IReadOnlyList ExtraInputs => Inner.ExtraInputs; + /// public IEnumerable Generate(GenContext ctx) => Inner.Generate(ctx); } diff --git a/server/csharp/MetaObjects.Codegen/HashManifest.cs b/server/csharp/MetaObjects.Codegen/HashManifest.cs index 0024ffa961..2f29150eb7 100644 --- a/server/csharp/MetaObjects.Codegen/HashManifest.cs +++ b/server/csharp/MetaObjects.Codegen/HashManifest.cs @@ -158,4 +158,71 @@ public static bool IsPristine( /// Whether we recorded writing at all, whatever it holds now. public static bool IsRecorded(string genStateDir, string relPath, string? legacyRelPath = null) => Recorded(genStateDir, relPath, legacyRelPath) is not null; + + /// + /// ADR-0062 — one run's view of the manifest: loaded ONCE, updated in memory, saved ONCE and + /// only when an entry was added, changed or removed. A run that changes nothing leaves the + /// file (and its timestamp) alone, and a run over N files no longer rewrites it N times. + /// The bytes written are exactly 's. + /// + public sealed class Session + { + private readonly string _genStateDir; + private readonly Dictionary _hashes; + private bool _dirty; + + public Session(string genStateDir) + { + _genStateDir = genStateDir; + _hashes = Load(genStateDir); + } + + /// The in-memory entries, for a reader that needs the whole set. + public IReadOnlyDictionary Entries => _hashes; + + /// Record that holds , dropping the legacy key. + public void Record(string relPath, string content, string? legacyRelPath = null) + { + var hash = ContentHash(content); + if (!_hashes.TryGetValue(relPath, out var prior) || prior != hash) + { + _hashes[relPath] = hash; + _dirty = true; + } + if (legacyRelPath is not null && !string.Equals(legacyRelPath, relPath, StringComparison.Ordinal) + && _hashes.Remove(legacyRelPath)) + _dirty = true; + } + + private string? Recorded(string relPath, string? legacyRelPath) + { + if (_hashes.TryGetValue(relPath, out var recorded)) return recorded; + if (legacyRelPath is not null && _hashes.TryGetValue(legacyRelPath, out var legacy)) return legacy; + return null; + } + + /// See . + public bool IsPristine(string relPath, string current, string? legacyRelPath = null) => + Recorded(relPath, legacyRelPath) == ContentHash(current); + + /// See . + public bool IsRecorded(string relPath, string? legacyRelPath = null) => + Recorded(relPath, legacyRelPath) is not null; + + /// Write the manifest when something changed since it was loaded or last saved. + public void Save() + { + if (!_dirty) return; + HashManifest.Save(_genStateDir, _hashes); + _dirty = false; + } + + /// Re-read the manifest after something else (the orphan sweep) saved it. + public void Reload() + { + _hashes.Clear(); + foreach (var (k, v) in Load(_genStateDir)) _hashes[k] = v; + _dirty = false; + } + } } diff --git a/server/csharp/MetaObjects.Codegen/ModelHash.cs b/server/csharp/MetaObjects.Codegen/ModelHash.cs new file mode 100644 index 0000000000..86e4f432b8 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/ModelHash.cs @@ -0,0 +1,62 @@ +// ADR-0062 — the hash tree of a LOADED model: one hash per root-level node, one per package, one +// for the model. A node is hashed in its canonical EFFECTIVE form (the serializer the conformance +// runner uses for expected-effective fixtures): `extends` and overlays applied, attributes in a +// fixed order, no source positions. So reformatting a metadata file, reordering it, or moving an +// object to another file of the same package does not change a hash, and an edit to an abstract +// parent changes the hash of every node that inherits from it. +// +// The tree is exposed (not just the model hash) so a later per-object or per-package key can +// reuse the node and package hashes. + +using System.Security.Cryptography; +using System.Text; +using MetaObjects.Meta; + +namespace MetaObjects.Codegen; + +/// The node, package and model hashes of a loaded model. +public sealed class ModelHash +{ + /// One root-level node: its effective package, its type and name, and its hash. + public sealed record Node(string Package, string Type, string Name, string Hash); + + public IReadOnlyList Nodes { get; } + + /// Per package: sha-256 over the sorted type:name:hash lines of its nodes. + public IReadOnlyDictionary Packages { get; } + + /// sha-256 over the sorted package:hash lines of the packages. + public string Model { get; } + + private ModelHash(IReadOnlyList nodes, IReadOnlyDictionary packages, string model) + { + Nodes = nodes; + Packages = packages; + Model = model; + } + + private static string Sha(string text) => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))).ToLowerInvariant(); + + public static ModelHash Of(MetaRoot root) + { + var nodes = new List(); + // The root has no super, so its children are the root-level nodes, whole. + foreach (var child in root.Children()) + { + if (child.Type == MetaObjects.Shared.BaseTypes.TYPE_ATTR) continue; + // The effective package is part of the identity: the serialized body omits a package + // the node only inherits from its file. + var pkg = child.Package ?? child.FileDefaultPackage ?? root.Package ?? ""; + var body = SerializerJson.CanonicalSerializeEffective(child); + nodes.Add(new Node(pkg, child.Type + "." + child.SubType, child.Name, Sha(pkg + "\n" + body))); + } + var packages = nodes.GroupBy(n => n.Package, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => Sha(string.Join("\n", g.Select(n => $"{n.Type}:{n.Name}:{n.Hash}").Order(StringComparer.Ordinal))), + StringComparer.Ordinal); + var model = Sha(string.Join("\n", packages.Select(p => $"{p.Key}:{p.Value}").Order(StringComparer.Ordinal))); + return new ModelHash(nodes, packages, model); + } +} diff --git a/server/csharp/MetaObjects.Codegen/TemplateCodegen/TemplateSpecGenerator.cs b/server/csharp/MetaObjects.Codegen/TemplateCodegen/TemplateSpecGenerator.cs index d5bbffaabb..c61672484d 100644 --- a/server/csharp/MetaObjects.Codegen/TemplateCodegen/TemplateSpecGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/TemplateCodegen/TemplateSpecGenerator.cs @@ -23,6 +23,10 @@ public sealed class TemplateSpecGenerator : IGenerator /// public string? OutDir { get; init; } + /// ADR-0062: the spec file and the template root are read at generation time, so + /// their content is part of the run's identity. + public IReadOnlyList ExtraInputs => [Spec, TemplateRoot ?? CodegenCli.DefaultTemplateRoot()]; + /// The spec's generators, read from each time they are asked for. public IReadOnlyList Generators() { diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java index 14d79e0837..1daff71195 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/FileEmittingGenerator.java @@ -63,8 +63,7 @@ public void execute(MetaDataLoader loader) { if (GeneratedFileWriter.looksGenerated(f.content())) { GeneratedFileWriter.write(target, f.content()); } else { - if (target.getParent() != null) Files.createDirectories(target.getParent()); - Files.writeString(target, f.content(), StandardCharsets.UTF_8); + GeneratedFileWriter.writeIfChanged(target, f.content()); } } catch (IOException e) { throw new GeneratorException(getClass().getSimpleName() + ": could not write " + target + ": " + e, e); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java index cfe796d7c5..a1139e732b 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/Generator.java @@ -12,4 +12,24 @@ public interface Generator { public Generator setScripts( List scripts ); public void execute( MetaDataLoader loader ); + + /** + * Whether a run that includes this generator may be skipped when none of its inputs changed + * (ADR-0062). Return {@code false} when the output depends on anything the build cannot + * name: an environment variable, the network, a file lookup relative to the working + * directory. A run that includes such a generator always runs in full. + */ + default boolean cacheable() { + return true; + } + + /** + * Files and directories, besides the metadata and the generator's own class, whose content + * this generator reads (template roots, lookup tables). Their content is hashed into the + * run's fingerprint, so editing one makes the next run regenerate. A relative path is + * relative to the module basedir; a directory counts every file under it. + */ + default List extraInputs() { + return List.of(); + } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java index 07bad951b8..25d5e0e4b4 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/MultiFileDirectGeneratorBase.java @@ -36,6 +36,8 @@ public void execute( MetaDataLoader loader ) { String filename = null; OutputStream out = null; + java.io.ByteArrayOutputStream finalBuffer = new java.io.ByteArrayOutputStream(); + File finalFile = null; GeneratorIOWriter writer = null; parseArgs(); @@ -96,7 +98,8 @@ public void execute( MetaDataLoader loader ) { outf.createNewFile(); // Get the printwriter - out = new FileOutputStream(outf); + out = finalBuffer; // written below, and only when the bytes differ from what is on disk + finalFile = outf; writer = getFinalWriter(loader, out); if ( writer != null ) { @@ -131,6 +134,13 @@ else if ( out != null ) { log.error("Error closing output stream for file [" + filename + "]: " + e, e ); } } + if ( finalFile != null && out != null ) { + try { + GeneratedFileWriter.writeIfChanged(finalFile.toPath(), finalBuffer.toByteArray()); + } catch (IOException e) { + throw new GeneratorException( "Unable to write to file [" + filename + "]: " + e, e ); + } + } } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java index 53459ba8db..7376c52bce 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/SingleFileDirectGeneratorBase.java @@ -17,17 +17,19 @@ public void execute( MetaDataLoader loader ) { String filename = null; PrintWriter pw = null; T writer = null; + java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); + File outf = null; parseArgs(); try { // Create output file filename = getOutputFilename(); - File outf = new File(getOutputDir(), filename ); + outf = new File(getOutputDir(), filename ); outf.createNewFile(); // Get the printwriter - pw = new PrintWriter(outf); + pw = new PrintWriter(buffer); // written below, and only when the bytes differ from what is on disk writer = getWriter(loader, pw); writer.withFilters(MetaDataFilters.create( getFilters() )) @@ -48,6 +50,13 @@ public void execute( MetaDataLoader loader ) { } } else if ( pw != null ) pw.close(); + if ( outf != null && pw != null ) { + try { + com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(outf.toPath(), buffer.toByteArray()); + } catch (IOException e) { + throw new GeneratorException( "Unable to write to file [" + filename + "]: " + e, e ); + } + } } } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java index e38dbcaaf7..5b01c5186e 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/html/SingleHtmlDirectGeneratorBase.java @@ -19,6 +19,7 @@ public void execute(MetaDataLoader loader) { File outf = null; OutputStream fos = null; + java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); HtmlDirectWriter writer = null; parseArgs(); @@ -29,7 +30,7 @@ public void execute(MetaDataLoader loader) { outf.createNewFile(); // Create the HTML Writer - fos = new FileOutputStream(outf); + fos = buffer; // written below, and only when the bytes differ from what is on disk writer = getWriter(loader, fos); writer.withFilename(outf.toString()) .withFilters(MetaDataFilters.create(getFilters())); @@ -45,6 +46,7 @@ public void execute(MetaDataLoader loader) { // NOTE: This is critical as the close flushes the HTML to the outputstream if (writer != null) writer.close(); else if (fos != null) fos.close(); + if (outf != null && fos != null) com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(outf.toPath(), buffer.toByteArray()); } catch (IOException e) { log.error("Error closing HTML file [" + outf + "]: " + e, e); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java index 3b954184ca..c41be7f4e6 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/metadata/json/SingleJsonDirectGeneratorBase.java @@ -19,6 +19,7 @@ public void execute(MetaDataLoader loader) { File outf = null; OutputStream fos = null; + java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); JsonDirectWriter writer = null; parseArgs(); @@ -29,7 +30,7 @@ public void execute(MetaDataLoader loader) { outf.createNewFile(); // Create the JSON Writer - fos = new FileOutputStream(outf); + fos = buffer; // written below, and only when the bytes differ from what is on disk writer = getWriter(loader, fos); writer.withFilename(outf.toString()) .withFilters(MetaDataFilters.create(getFilters())); @@ -45,6 +46,7 @@ public void execute(MetaDataLoader loader) { // NOTE: This is critical as the close flushes the JSON to the outputstream if (writer != null) writer.close(); else if (fos != null) fos.close(); + if (outf != null && fos != null) com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(outf.toPath(), buffer.toByteArray()); } catch (IOException e) { log.error("Error closing JSON file [" + outf + "]: " + e, e); } diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java index 8c1f25cfce..e2095434fb 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/direct/object/javacode/JavaObjectCodeGenerator.java @@ -206,7 +206,7 @@ private void emitServicesRegistration() throws IOException { // content is a bare provider FQN with nowhere to carry a GENERATED marker. Guarding it // would make the FIRST run write and every run after refuse — the artifact frozen while // the build stays green, which is the failure the guard exists to prevent. - Files.write(services.toPath(), (PROVIDER_FQN + "\n").getBytes(StandardCharsets.UTF_8)); + GeneratedFileWriter.writeIfChanged(services.toPath(), (PROVIDER_FQN + "\n").getBytes(StandardCharsets.UTF_8)); } private static String escape(String s) { diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java index 06ed7635c2..e670776aaa 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/template/TemplateScopeGenerator.java @@ -46,6 +46,11 @@ public class TemplateScopeGenerator extends GeneratorBase { public static final String ARG_FORMAT = "format"; public static final String ARG_TEMPLATES_DIR = "templatesDir"; + /** The template root is an input (ADR-0062): editing a template regenerates. */ + @Override + public java.util.List extraInputs() { + return hasArg(ARG_TEMPLATES_DIR) ? java.util.List.of(getArg(ARG_TEMPLATES_DIR)) : java.util.List.of(); + } @Override public void execute(MetaDataLoader loader) { String template = getArg(ARG_TEMPLATE, true); @@ -80,7 +85,7 @@ public void execute(MetaDataLoader loader) { // // The marker floor protects output whose header WE control. User template // output is not that. - Files.writeString(target, f.content()); + com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged(target, f.content()); } catch (IOException e) { throw new GeneratorException( "Failed to write template-codegen output [" + target + "]: " + e.getMessage(), e); diff --git a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java index aa46ab1f65..6f375477be 100644 --- a/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java +++ b/server/java/codegen-base/src/main/java/com/metaobjects/generator/util/GeneratedFileWriter.java @@ -9,6 +9,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -157,9 +158,19 @@ public static final class Run implements AutoCloseable { private final List adoptedPaths = new ArrayList<>(); private final List overwrittenHandEditedPaths = new ArrayList<>(); private int untrackedCount = 0; + private int refusedCount = 0; + // Non-null for a capture run (verify, ADR-0062 §4): every write lands here, keyed by the + // normalized absolute path, and nothing is written to disk. + private Map captured; private Run() {} + /** The bytes a capture run's generators emitted, by normalized absolute path; {@code null} + * for an ordinary run. Read-only view. */ + public Map captured() { + return captured == null ? null : Collections.unmodifiableMap(captured); + } + /** Name the generator whose writes follow, with {@code handEdits=keep}. Equivalent * to {@code attributeTo(generatorName, "keep")}. */ public Run attributeTo(String generatorName) { @@ -239,6 +250,12 @@ public int untrackedCount() { return untrackedCount; } + /** How many writes this run refused (hand-written files left alone; a kept hand edit is tracked by the stored key and not counted). + * A run that refused anything is not a clean run: ADR-0062 stores no key for it. */ + public int refusedCount() { + return refusedCount; + } + private void note(Path outFile, String content) { if (currentOwner == null) return; emissions.computeIfAbsent(outFile.toAbsolutePath().normalize(), k -> new LinkedHashMap<>()) @@ -289,6 +306,18 @@ public static Run beginRun() { return run; } + /** + * Open a run that writes nothing to disk: every file a generator emits is held in memory + * ({@link Run#captured()}) instead. {@code verify --codegen} renders through one, so it + * compares the rendered bytes with the committed tree without writing a rendered tree + * (ADR-0062 §4). A capture run has no manifest, so every write takes the marker-only path. + */ + public static Run beginCaptureRun() { + Run run = beginRun(); + run.captured = new LinkedHashMap<>(); + return run; + } + /** The open run on this thread, or {@code null}. */ public static Run currentRun() { return ACTIVE_RUN.get(); @@ -385,6 +414,7 @@ public static Outcome write(Path outFile, String content) throws IOException { return Outcome.WRITTEN; } LOG.warn(refusedMessage(outFile)); + run.refusedCount++; return Outcome.REFUSED; } @@ -413,6 +443,8 @@ public static Outcome write(Path outFile, String content) throws IOException { } run.record(key, recorded); run.note(outFile, content); + // Kept, and recorded: the whole-run skip tracks the file's bytes (ADR-0062 Amendment A), + // so a kept hand edit is not an unclean run. LOG.warn(refusedHandEditedMessage(outFile)); return Outcome.REFUSED; } @@ -428,6 +460,7 @@ private static Outcome writeMarkerOnly(Path outFile, String content, Run run) th if (Files.exists(outFile) && !looksGenerated(Files.readString(outFile, StandardCharsets.UTF_8))) { LOG.warn(refusedMessage(outFile)); + if (run != null) run.refusedCount++; return Outcome.REFUSED; } performWrite(outFile, content, run); @@ -443,10 +476,44 @@ private static void performWrite(Path outFile, String content, Run run) throws I if (run != null) { run.claim(outFile, content); } - if (outFile.getParent() != null) { - Files.createDirectories(outFile.getParent()); + writeIfChanged(outFile, content); + } + + /** + * Write {@code content} (UTF-8) to {@code file}, creating parent directories, unless the file + * already holds exactly these bytes. A rewrite moves the file's timestamp and every build tool + * downstream then recompiles it (ADR-0062 §2), so identical bytes are never rewritten. + * + * @return {@code true} when the file was written, {@code false} when it was left alone + */ + public static boolean writeIfChanged(Path file, String content) throws IOException { + return writeIfChanged(file, content.getBytes(StandardCharsets.UTF_8)); + } + + /** {@link #writeIfChanged(Path, String)} for a caller that encodes with another charset. */ + public static boolean writeIfChanged(Path file, String content, java.nio.charset.Charset charset) + throws IOException { + return writeIfChanged(file, content.getBytes(charset)); + } + + /** {@link #writeIfChanged(Path, String)} for bytes already encoded. */ + public static boolean writeIfChanged(Path file, byte[] bytes) throws IOException { + Run run = ACTIVE_RUN.get(); + if (run != null) { + run.emittedPaths.add(file.toAbsolutePath().normalize()); + } + if (run != null && run.captured != null) { + run.captured.put(file.toAbsolutePath().normalize(), bytes.clone()); + return true; + } + if (Files.isRegularFile(file) && java.util.Arrays.equals(Files.readAllBytes(file), bytes)) { + return false; + } + if (file.getParent() != null) { + Files.createDirectories(file.getParent()); } - Files.writeString(outFile, content, StandardCharsets.UTF_8); + Files.write(file, bytes); + return true; } /** diff --git a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java index e09e149252..34355d6e7c 100644 --- a/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java +++ b/server/java/codegen-base/src/test/java/com/metaobjects/generator/util/GeneratedFileWriterTest.java @@ -471,4 +471,92 @@ public void untrackedPathOutsideProjectRoot_fallsBackToMarkerOnlyRule() throws E } assertEquals(GENERATED_BODY, Files.readString(outside)); } + + // ---- ADR-0062: identical bytes are never rewritten, and the manifest is written once ---- + + private static final java.nio.file.attribute.FileTime LONG_AGO = + java.nio.file.attribute.FileTime.fromMillis(1_000_000_000_000L); + + @Test + public void identicalBytes_markerOnlyRule_keepTheTimestamp() throws Exception { + Path out = tmp.getRoot().toPath().resolve("X.java"); + Files.writeString(out, GENERATED_BODY); + Files.setLastModifiedTime(out, LONG_AGO); + + GeneratedFileWriter.write(out, GENERATED_BODY); + + assertEquals(LONG_AGO, Files.getLastModifiedTime(out)); + } + + @Test + public void identicalBytes_withManifest_keepTheTimestampWhetherRecordedOrNot() throws Exception { + Path project = tmp.newFolder().toPath(); + Path genState = project.resolve(".metaobjects/.gen-state"); + Path out = project.resolve("gen/X.java"); + Files.createDirectories(out.getParent()); + Files.writeString(out, GENERATED_BODY); // on disk, never recorded: the adopt path + Files.setLastModifiedTime(out, LONG_AGO); + + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + GeneratedFileWriter.write(out, GENERATED_BODY); + } + assertEquals("adopted, not rewritten", LONG_AGO, Files.getLastModifiedTime(out)); + + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + assertEquals(GeneratedFileWriter.Outcome.UNCHANGED, GeneratedFileWriter.write(out, GENERATED_BODY)); + } + assertEquals("recorded and identical", LONG_AGO, Files.getLastModifiedTime(out)); + } + + @Test + public void aRunThatChangesNothingLeavesTheManifestAlone() throws Exception { + Path project = tmp.newFolder().toPath(); + Path genState = project.resolve(".metaobjects/.gen-state"); + Path out = project.resolve("gen/X.java"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + GeneratedFileWriter.write(out, GENERATED_BODY); + } + Path manifest = genState.resolve(".hashes.json"); + String before = Files.readString(manifest); + Files.setLastModifiedTime(manifest, LONG_AGO); + + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginRun()) { + run.configureManifest(genState, project); + GeneratedFileWriter.write(out, GENERATED_BODY); + run.flush(); + } + assertEquals(before, Files.readString(manifest)); + assertEquals("not saved when nothing changed", LONG_AGO, Files.getLastModifiedTime(manifest)); + } + + @Test + public void writeIfChanged_writesOnlyWhenTheBytesDiffer() throws Exception { + Path out = tmp.getRoot().toPath().resolve("deep/dir/f.txt"); + assertTrue(GeneratedFileWriter.writeIfChanged(out, "one")); + Files.setLastModifiedTime(out, LONG_AGO); + assertFalse(GeneratedFileWriter.writeIfChanged(out, "one")); + assertEquals(LONG_AGO, Files.getLastModifiedTime(out)); + assertTrue(GeneratedFileWriter.writeIfChanged(out, "two")); + assertEquals("two", Files.readString(out)); + } + + @Test + public void captureRun_holdsEveryWriteInMemoryAndWritesNothing() throws Exception { + Path a = tmp.getRoot().toPath().resolve("virtual/out/A.java"); + Path b = tmp.getRoot().toPath().resolve("virtual/out/sub/b.txt"); + try (GeneratedFileWriter.Run run = GeneratedFileWriter.beginCaptureRun()) { + assertEquals(GeneratedFileWriter.Outcome.WRITTEN, GeneratedFileWriter.write(a, GENERATED_BODY)); + assertTrue(GeneratedFileWriter.writeIfChanged(b, "bytes")); + assertEquals(2, run.captured().size()); + assertEquals(GENERATED_BODY, new String(run.captured().get(a.toAbsolutePath().normalize()), + java.nio.charset.StandardCharsets.UTF_8)); + assertEquals("bytes", new String(run.captured().get(b.toAbsolutePath().normalize()), + java.nio.charset.StandardCharsets.UTF_8)); + } + assertFalse("a capture run writes no file", Files.exists(tmp.getRoot().toPath().resolve("virtual"))); + assertNull(GeneratedFileWriter.currentRun()); + } } diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRenderHelperGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRenderHelperGenerator.kt index 13285e0e48..8cfeae813f 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRenderHelperGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinRenderHelperGenerator.kt @@ -76,6 +76,10 @@ open class KotlinRenderHelperGenerator : MultiFileDirectGeneratorBase = MetaObject::class.java + /** The template root is an input (ADR-0062): editing a template regenerates. */ + override fun extraInputs(): List = + if (hasArg(ARG_TEMPLATE_ROOT)) listOf(getArg(ARG_TEMPLATE_ROOT)) else emptyList() + override fun execute(loader: MetaDataLoader) { parseArgs() val outRoot = Paths.get(outDir.absolutePath) diff --git a/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java b/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java index ac2605fba4..a4997de54b 100644 --- a/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java +++ b/server/java/codegen-mustache/src/main/java/com/metaobjects/generator/mustache/MustacheTemplateGenerator.java @@ -72,6 +72,16 @@ public class MustacheTemplateGenerator implements Generator { private String targetLanguage = "java"; private String templateName = null; // If null, auto-discover templates + /** + * Not cacheable (ADR-0062): a template is looked up under {@code templatePath} relative to + * the working directory or on the classpath, and which one answers is not something the + * build can name, so a run that includes this generator always runs in full. + */ + @Override + public boolean cacheable() { + return false; + } + @Override public Generator setArgs(Map args) { this.args = args != null ? new HashMap<>(args) : new HashMap<>(); @@ -290,9 +300,8 @@ private void generateFileFromTemplate(MetaObject metaObject, TemplateDefinition // Write generated file File outputFile = outputPath.resolve(fileName).toFile(); - try (FileWriter writer = new FileWriter(outputFile)) { - writer.write(generatedCode); - } + com.metaobjects.generator.util.GeneratedFileWriter.writeIfChanged( + outputFile.toPath(), generatedCode, java.nio.charset.Charset.defaultCharset()); log.debug("Generated file: {}", outputFile.getAbsolutePath()); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java index 0d59e38ebd..ed9e5cabbb 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringRenderHelperGenerator.java @@ -99,6 +99,12 @@ public class SpringRenderHelperGenerator extends MultiFileDirectGeneratorBase extraInputs() { + return hasArg(ARG_TEMPLATE_ROOT) ? java.util.List.of(getArg(ARG_TEMPLATE_ROOT)) : java.util.List.of(); + } + @Override protected Class getFilterClass() { return MetaObject.class; diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java index 7551d86102..5585ee0b7e 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/AbstractMetaDataMojo.java @@ -429,11 +429,331 @@ public void execute() throws MojoExecutionException, MojoFailureException MetaDataLoader loader = createLoader(projectClassLoader); + // ADR-0062: the metadata is loaded (the model key is made of it), and nothing has + // rendered yet: decide from the model and the generator identity whether this run can + // change anything. + if ( planWholeRun(loader) ) { + onWholeRunSkipped(); + return; + } + List generatorImpls = buildGenerators( projectClassLoader, null ); + noteGenerators( generatorImpls ); + executeGenerators( loader, generatorImpls ); + + finishWholeRun(); + } + + // --------------------------------------------------------------------------------- + // ADR-0062: skip the whole run when none of its inputs changed + + /** Whether this goal skips a run whose fingerprint matches the stored one. */ + protected boolean skipsWhenUnchanged() { + return false; + } + + /** Whether this run was asked to run in full whatever the fingerprint says. */ + protected boolean forced() { + return false; + } + + /** Called instead of the run when the fingerprint matched. */ + protected void onWholeRunSkipped() { + } + + /** Set by the goal when this run refused a file (hand-edited or hand-written): such a run + * stores no fingerprint, since its output is not what the inputs describe. */ + protected boolean runWasClean = true; + + /** Generated files that landed outside the module (the manifest records only files inside + * it); their existence is part of the skip rule. Set by the goal after its run. */ + protected List outputsOutsideModule = List.of(); + + // State of the current run, set by planWholeRun and read by finishWholeRun. + private Path fingerprintFile; + private List fingerprintBase; + private List fingerprintExtras = List.of(); + private List fingerprintExtraInputs = List.of(); + private boolean allCacheable = true; + + private Path moduleGenStateDir() { + return project != null && project.getBasedir() != null + ? project.getBasedir().toPath().resolve(".metaobjects").resolve(".gen-state") : null; + } + + /** The stable name of this execution's generator/output-directory configuration. */ + String fingerprintOwnerTag() { + List lines = new ArrayList<>(); + if ( getGenerators() != null ) { + for ( GeneratorParam g : getGenerators() ) { + String dir = mergeAndOverwriteArgs(g).get(GeneratorBase.ARG_OUTPUTDIR); + lines.add(g.getClassname() + "@" + (dir == null ? "-" : moduleDir(Path.of(dir)))); + } + } + return GenFingerprint.ownerTag(lines); + } + + /** + * Decide, before anything loads, whether this run can be skipped. Returns {@code true} to + * skip. Otherwise it deletes the stored fingerprint, so a run that fails halfway can never + * leave one claiming its half-written output is current. + */ + private boolean planWholeRun(MetaDataLoader loader) { + fingerprintBase = null; + fingerprintFile = null; + Path genStateDir = moduleGenStateDir(); + if ( !skipsWhenUnchanged() || genStateDir == null ) return false; + try { + fingerprintFile = GenFingerprint.fileFor(genStateDir, fingerprintOwnerTag()); + fingerprintBase = fingerprintInputs(loader); + } catch ( java.io.IOException | RuntimeException e ) { + // Anything the fingerprint cannot prove unchanged counts as changed. + getLog().debug("MetaData Mojo > No fingerprint for this run: " + e); + fingerprintBase = null; + } + if ( fingerprintBase != null && !forced() && fingerprintMatches(genStateDir, false) ) return true; + if ( fingerprintFile != null ) GenFingerprint.delete(fingerprintFile); + return false; + } + + /** Local {@code verify}: the stored fingerprint matches and every file the manifest records + * still hashes to its record. Anything else is a full render. */ + protected boolean fingerprintAnswersNoDrift(MetaDataLoader loader) { + Path genStateDir = moduleGenStateDir(); + if ( genStateDir == null ) return false; + try { + fingerprintFile = GenFingerprint.fileFor(genStateDir, fingerprintOwnerTag()); + fingerprintBase = fingerprintInputs(loader); + } catch ( java.io.IOException | RuntimeException e ) { + return false; + } + return fingerprintMatches(genStateDir, true); + } + + /** + * Whether the stored fingerprint matches the one just computed and the files the last run + * wrote are all still there. With {@code checkHashes}, each file the manifest records must + * also still hash to its record (what a local {@code verify} needs). + */ + protected boolean fingerprintMatches(Path genStateDir, boolean checkHashes) { + if ( fingerprintBase == null || fingerprintFile == null ) return false; + java.util.Optional stored = GenFingerprint.read(fingerprintFile); + if ( stored.isEmpty() || stored.get().formatVersion() != GenFingerprint.FORMAT_VERSION ) return false; + try { + List all = new ArrayList<>(fingerprintBase); + all.addAll(extraInputsOf(stored.get().extras())); + if ( !GenFingerprint.fold(all).equals(stored.get().key()) ) return false; + Path root = project.getBasedir().toPath(); + // Amendment A: every recorded file must still hash to what the last run left on + // disk. A hand edit therefore makes gen render, and a hand edit that gen merged and + // kept does not. Verify also wants each file to match the manifest record. + for ( Map.Entry e : HashManifest.load(genStateDir).entrySet() ) { + Path file = root.resolve(e.getKey()); + if ( !Files.isRegularFile(file) ) return false; + String onDisk = HashManifest.contentHash(Files.readString(file, StandardCharsets.UTF_8)); + if ( !onDisk.equals(stored.get().outputs().get(e.getKey())) ) return false; + if ( checkHashes && !e.getValue().equals(onDisk) ) return false; + } + for ( String outside : stored.get().untracked() ) { + if ( !Files.isRegularFile(Path.of(outside)) ) return false; + } + return true; + } catch ( java.io.IOException | RuntimeException e ) { + return false; + } + } + + /** Record what the built generators declare: whether they are cacheable and what extra + * files they read, hashed now, before any of them runs. */ + private void noteGenerators( List impls ) { + allCacheable = true; + fingerprintExtras = List.of(); + fingerprintExtraInputs = List.of(); + if ( fingerprintBase == null ) return; + java.util.TreeSet extras = new java.util.TreeSet<>(); + for ( Generator g : impls ) { + if ( !g.cacheable() ) allCacheable = false; + extras.addAll(g.extraInputs()); + } + try { + fingerprintExtras = new ArrayList<>(extras); + fingerprintExtraInputs = extraInputsOf(fingerprintExtras); + } catch ( java.io.IOException | RuntimeException e ) { + fingerprintBase = null; + } + } + + /** Store the new fingerprint, after a run that succeeded, refused nothing and included + * only cacheable generators. It was computed from inputs read before the run. */ + private void finishWholeRun() { + if ( fingerprintBase == null || fingerprintFile == null || !allCacheable || !runWasClean ) return; + if ( getGenerators() == null || getGenerators().isEmpty() ) return; // nothing ran, nothing to skip + List all = new ArrayList<>(fingerprintBase); + all.addAll(fingerprintExtraInputs); + // The outputs as this run left them. A recorded file that is missing means the run did + // not leave a state a later run could trust: store no key. + Path genStateDir = moduleGenStateDir(); + if ( genStateDir == null ) return; + Map outputs = new java.util.TreeMap<>(); + try { + Path root = project.getBasedir().toPath(); + for ( String rel : HashManifest.load(genStateDir).keySet() ) { + Path file = root.resolve(rel); + if ( !Files.isRegularFile(file) ) return; + outputs.put(rel, HashManifest.contentHash(Files.readString(file, StandardCharsets.UTF_8))); + } + } catch ( java.io.IOException | RuntimeException e ) { + return; + } + GenFingerprint.write(fingerprintFile, new GenFingerprint.Stored(GenFingerprint.FORMAT_VERSION, + GenFingerprint.fold(all), fingerprintExtras, outputsOutsideModule, outputs)); + } + + private List extraInputsOf( List extras ) throws java.io.IOException { + List out = new ArrayList<>(); + Path base = getProjectBaseDir().toPath(); + for ( String extra : extras ) { + Path p = Path.of(extra); + GenFingerprint.addTree(out, "extra", extra, p.isAbsolute() ? p : base.resolve(p).normalize(), r -> false); + } + return out; + } + + /** The version of this plugin, or "unknown" when it is not known (a unit test). */ + private String pluginVersion() { + try { + if ( execution != null && execution.getPlugin() != null && execution.getPlugin().getVersion() != null ) { + return execution.getPlugin().getVersion(); + } + } catch ( RuntimeException ignored ) { + // fall through + } + return "unknown"; } + /** + * The jars and directories whose content decides what the generators do: the plugin's own + * classpath (the shipped generators, and any generator jar the pom adds to the plugin's + * dependencies) and the project classpath the generators are loaded from. A unit test may + * override it. + */ + protected List engineClasspath() { + java.util.TreeSet out = new java.util.TreeSet<>(); + try { + if ( execution != null && execution.getMojoDescriptor() != null ) { + for ( org.apache.maven.artifact.Artifact a : execution.getMojoDescriptor().getPluginDescriptor().getArtifacts() ) { + if ( a.getFile() != null ) out.add(a.getFile().toPath().toAbsolutePath().normalize()); + } + } + } catch ( RuntimeException ignored ) { + // fall back to the code source below + } + if ( out.isEmpty() ) { + try { + out.add(Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()) + .toAbsolutePath().normalize()); + } catch ( Exception ignored ) { + // nothing known: the plugin version still keys it + } + } + if ( project != null && execution != null ) { + try { + // The module's own compiled output is a build product, not a generator: it moves + // whenever generated code is compiled. Left out unless this phase loads + // generators from it (the test and command-line phases do). + String phase = phaseName(); + boolean loadsOwnClasses = phase.equals(PHASE_GENERATE_TEST_SOURCES) + || phase.equals(PHASE_GENERATE_TEST_RESOURCES) || phase.equals("cli"); + Set own = new HashSet<>(); + if ( project.getBuild() != null ) { + if ( project.getBuild().getOutputDirectory() != null ) + own.add(Path.of(project.getBuild().getOutputDirectory()).toAbsolutePath().normalize()); + if ( project.getBuild().getTestOutputDirectory() != null ) + own.add(Path.of(project.getBuild().getTestOutputDirectory()).toAbsolutePath().normalize()); + } + for ( String e : classpathElements(phase) ) { + Path p = Path.of(e).toAbsolutePath().normalize(); + if ( loadsOwnClasses || !own.contains(p) ) out.add(p); + } + } catch ( Exception e ) { + throw new MetaDataException("Could not read the project classpath: " + e.getMessage(), e); + } + } + return new ArrayList<>(out); + } + + private String phaseName() { + String phase = execution != null ? execution.getLifecyclePhase() : null; + return phase == null ? "cli" : phase; + } + + /** Every input that is known before the loader runs, as small named entries. Throws when + * an input cannot be proven (a metadata source that is not a local file or the classpath). */ + protected List fingerprintBaseInputs() throws java.io.IOException { + List in = new ArrayList<>(); + Path base = getProjectBaseDir().toPath().toAbsolutePath().normalize(); + in.add(new GenFingerprint.Input("tool", "fingerprint-format", String.valueOf(GenFingerprint.FORMAT_VERSION))); + in.add(new GenFingerprint.Input("tool", "plugin-version", pluginVersion())); + + // Generator identity: the content of everything the generators are loaded from. + for ( Path p : engineClasspath() ) { + GenFingerprint.addTree(in, "engine", p.getFileName() == null ? p.toString() : p.getFileName().toString(), + p, r -> false); + } + // An owned (ejected) generator: the content of its source. + GenFingerprint.addTree(in, "owned-generator", MetaDataEjectMojo.CODEGEN_DIR, + base.resolve(MetaDataEjectMojo.CODEGEN_DIR), r -> false); + + // Options: the loader, the flags and every generator's configuration. + LoaderParam lp = getLoader(); + in.add(config("loader", String.join("|", String.valueOf(lp.getClassname()), String.valueOf(lp.getName()), + String.valueOf(lp.getSourceDir()), String.valueOf(lp.getSources()), + String.valueOf(lp.getLibraries()), String.valueOf(lp.getFilters())))); + in.add(config("strict", String.valueOf(!lax))); + in.add(config("globals", new java.util.TreeMap<>(globals == null ? Map.of() : globals).toString())); + if ( getGenerators() != null ) { + for ( GeneratorParam g : getGenerators() ) { + Map merged = new java.util.TreeMap<>(mergeAndOverwriteArgs(g)); + in.add(new GenFingerprint.Input("generator", String.valueOf(g.getClassname()), + GenFingerprint.sha256(String.join("|", String.valueOf(g.getHandEdits()), + String.valueOf(g.getFilters()), String.valueOf(g.getScripts()), merged.toString())))); + if ( g.getScripts() != null ) { + for ( String script : g.getScripts() ) { + Path sp = base.resolve(script).normalize(); + if ( Files.isRegularFile(sp) ) in.add(GenFingerprint.fileInput("script", script, sp)); + } + } + } + } + + // The project's .metaobjects folder (config, dependency lock, snapshot), minus the state. + File srcDir = getSourceDir(); + java.util.Optional configDir = resolveProjectConfigDir(srcDir); + if ( configDir.isPresent() ) { + GenFingerprint.addTree(in, "project-config", ".metaobjects", + configDir.get().resolve(".metaobjects"), r -> r.startsWith(".gen-state")); + } else { + in.add(new GenFingerprint.Input("project-config", ".metaobjects", "none")); + } + + return in; + } + + /** Generator identity, options and project config, plus the model's hash from the loaded + * root. Never the metadata source files. */ + private List fingerprintInputs( MetaDataLoader loader ) throws java.io.IOException { + List in = new ArrayList<>(fingerprintBaseInputs()); + in.add(new GenFingerprint.Input("model", "model", ModelKey.of(loader).model())); + return in; + } + + private static GenFingerprint.Input config( String name, String value ) { + return new GenFingerprint.Input("config", name, GenFingerprint.sha256(value)); + } + + /** * Reflectively instantiate and configure each declared generator, mirroring the exact * mechanism {@code meta:gen} uses. This is the single source of truth for generator @@ -827,50 +1147,7 @@ protected ClassLoader createProjectClassLoader() getLog().info("MetaData Mojo > LifeCycle Phase: " + execution.getLifecyclePhase()); - List runTimeClasspath = project.getRuntimeClasspathElements(); - List compileClasspath = project.getCompileClasspathElements(); - //List compileSources = project.getCompileSourceRoots(); - List testClasspath = project.getTestClasspathElements(); - //List testCompileSources = project.getTestCompileSourceRoots(); - //getLog().info( "runTimeClasspath: " + compileClasspath ); - //getLog().info( "compileClasspath: " + compileClasspath ); - //getLog().info( "compileSources: " + compileSources ); - //getLog().info( "testClasspath: " + compileClasspath ); - //getLog().info( "testSources: " + testCompileSources ); - - List classpathElements = new ArrayList<>(); - - // Add runtime and compile time classes - classpathElements.addAll(runTimeClasspath); - classpathElements.addAll(compileClasspath); - - if ( lifeCyclePhase.equals(PHASE_GENERATE_SOURCES)) { - //classpathElements.add(project.getBuild().getOutputDirectory()); - } - else if ( lifeCyclePhase.equals(PHASE_GENERATE_RESOURCES)) { - //classpathElements.add(project.getBuild().getOutputDirectory()); - addDirIfExists( classpathElements, "generated-resources" ); - } - else if (lifeCyclePhase.equals(PHASE_GENERATE_TEST_SOURCES)) { - // Get the processed resources and compiled classes - classpathElements.addAll(testClasspath); - classpathElements.add(project.getBuild().getOutputDirectory()); - addDirIfExists( classpathElements, "generated-resources" ); - } - else if (lifeCyclePhase.equals(PHASE_GENERATE_TEST_RESOURCES) || - lifeCyclePhase.equals("cli")) { - // Get the processed resources and compiled classes - // Also get any generated-test-resources - classpathElements.addAll(testClasspath); - classpathElements.add(project.getBuild().getOutputDirectory()); - addDirIfExists( classpathElements, "generated-resources" ); - addDirIfExists( classpathElements, "generated-test-resources" ); - - //if ( lifeCyclePhase.equals("cli")) { - // classpathElements.addAll(runTimeClasspath); - // classpathElements.addAll(compileClasspath); - //} - } + List classpathElements = classpathElements(lifeCyclePhase); if ( classpathElements.size() > 0 ) { URL urls[] = new URL[classpathElements.size()]; @@ -896,6 +1173,46 @@ else if (lifeCyclePhase.equals(PHASE_GENERATE_TEST_RESOURCES) || return thisLoader; } + /** + * The classpath elements the project class loader is built from for {@code lifeCyclePhase}: + * the runtime and compile classpaths, plus (for the test and command-line phases) the test + * classpath and the module's compiled classes. + */ + protected List classpathElements(String lifeCyclePhase) throws Exception { + List runTimeClasspath = project.getRuntimeClasspathElements(); + List compileClasspath = project.getCompileClasspathElements(); + List testClasspath = project.getTestClasspathElements(); + + List classpathElements = new ArrayList<>(); + + // Add runtime and compile time classes + classpathElements.addAll(runTimeClasspath); + classpathElements.addAll(compileClasspath); + + if ( lifeCyclePhase.equals(PHASE_GENERATE_SOURCES)) { + // nothing more + } + else if ( lifeCyclePhase.equals(PHASE_GENERATE_RESOURCES)) { + addDirIfExists( classpathElements, "generated-resources" ); + } + else if (lifeCyclePhase.equals(PHASE_GENERATE_TEST_SOURCES)) { + // Get the processed resources and compiled classes + classpathElements.addAll(testClasspath); + classpathElements.add(project.getBuild().getOutputDirectory()); + addDirIfExists( classpathElements, "generated-resources" ); + } + else if (lifeCyclePhase.equals(PHASE_GENERATE_TEST_RESOURCES) || + lifeCyclePhase.equals("cli")) { + // Get the processed resources and compiled classes + // Also get any generated-test-resources + classpathElements.addAll(testClasspath); + classpathElements.add(project.getBuild().getOutputDirectory()); + addDirIfExists( classpathElements, "generated-resources" ); + addDirIfExists( classpathElements, "generated-test-resources" ); + } + return classpathElements; + } + protected void addDirIfExists(List classpathElements, String s) { File f = new File( project.getBasedir()+"/target/"+s); //getLog().info( "Looking for: " + f.getPath()); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java new file mode 100644 index 0000000000..89d785ce18 --- /dev/null +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/GenFingerprint.java @@ -0,0 +1,225 @@ +package com.metaobjects.mojo; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * The whole-run codegen fingerprint of ADR-0062, JVM edition. + * + *

    A fingerprint is one SHA-256 folded over a sorted list of small named {@link Input} + * entries (a kind, a name, a content hash). The entries are what a later per-object key would + * reuse for the subset of inputs that reaches one generator and one object. Timestamps are + * never an input: a file is its content. + * + *

    The stored form lives beside the committed hash manifest, in + * {@code .metaobjects/.gen-state/.fingerprint-java-.json}, and is not committed. It + * records the folded key, the declared extra inputs that went into it (so a check, which runs + * before any generator is constructed, can hash them), and the generated files that live + * outside the project root (the manifest records only the ones inside it). + */ +final class GenFingerprint { + + private GenFingerprint() {} + + /** Bump when what goes into the key changes, so no stored fingerprint survives it. */ + static final int FORMAT_VERSION = 2; + + /** One named input: what kind it is, what it is called, and the hash of its content. */ + record Input(String kind, String name, String sha256) { + String line() { + return kind + "\t" + name + "\t" + sha256; + } + } + + /** What a successful run stored. */ + record Stored(int formatVersion, String key, List extras, List untracked, + java.util.Map outputs) {} + + // ---------------------------------------------------------------- hashing + + static String sha256(byte[] bytes) { + return hex(digest().digest(bytes)); + } + + static String sha256(String text) { + return sha256(text.getBytes(StandardCharsets.UTF_8)); + } + + private static MessageDigest digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 not available", e); + } + } + + private static String hex(byte[] hash) { + StringBuilder sb = new StringBuilder(hash.length * 2); + for (byte b : hash) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } + + /** Content hashes of files already read this JVM, keyed by path, size and mtime: a build + * that runs the goal in many modules reads one jar once. Only an accelerator, never an + * input: a file whose size or mtime moved is read again. */ + private static final Map FILE_HASHES = new ConcurrentHashMap<>(); + + /** SHA-256 of one file's bytes. */ + static String hashFile(Path file) throws IOException { + Path abs = file.toAbsolutePath().normalize(); + String memo = abs + "|" + Files.size(abs) + "|" + Files.getLastModifiedTime(abs).toMillis(); + String known = FILE_HASHES.get(memo); + if (known != null) return known; + MessageDigest d = digest(); + byte[] buf = new byte[1 << 16]; + try (InputStream in = Files.newInputStream(abs)) { + for (int n; (n = in.read(buf)) > 0; ) d.update(buf, 0, n); + } + String hash = hex(d.digest()); + FILE_HASHES.put(memo, hash); + return hash; + } + + /** One entry for a file. A file that does not exist hashes to {@code "missing"}, so a + * path that appears later changes the key. */ + static Input fileInput(String kind, String name, Path file) throws IOException { + return new Input(kind, name, Files.isRegularFile(file) ? hashFile(file) : "missing"); + } + + /** One entry per file under {@code root} (or for {@code root} itself when it is a file), + * named relative to {@code namePrefix}; a root that is absent is one {@code missing} + * entry. {@code skip} is told each path relative to the root and drops it. */ + static void addTree(List into, String kind, String namePrefix, Path root, Predicate skip) + throws IOException { + if (Files.isRegularFile(root)) { + into.add(fileInput(kind, namePrefix, root)); + return; + } + if (!Files.isDirectory(root)) { + into.add(new Input(kind, namePrefix, "missing")); + return; + } + List files; + try (Stream walk = Files.walk(root)) { + files = walk.filter(Files::isRegularFile) + .filter(p -> !skip.test(root.relativize(p))) + .sorted(Comparator.comparing(p -> root.relativize(p).toString())) + .toList(); + } + into.add(new Input(kind, namePrefix + "/", "dir")); + for (Path f : files) { + into.add(fileInput(kind, namePrefix + "/" + root.relativize(f).toString().replace('\\', '/'), f)); + } + } + + /** The one key: SHA-256 over the sorted lines of every entry. */ + static String fold(List inputs) { + List lines = new ArrayList<>(inputs.size()); + for (Input in : inputs) lines.add(in.line()); + lines.sort(Comparator.naturalOrder()); + return sha256(String.join("\n", lines)); + } + + /** A short stable name for one execution's generator/output-dir configuration. */ + static String ownerTag(List ownerLines) { + List sorted = new ArrayList<>(ownerLines); + sorted.sort(Comparator.naturalOrder()); + return sha256(String.join("\n", sorted)).substring(0, 12); + } + + // ---------------------------------------------------------------- storage + + static final String FILE_PREFIX = ".fingerprint-java-"; + + static Path fileFor(Path genStateDir, String ownerTag) { + return genStateDir.resolve(FILE_PREFIX + ownerTag + ".json"); + } + + private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + /** The stored fingerprint, or empty when there is none or it cannot be read. */ + static Optional read(Path file) { + if (!Files.isRegularFile(file)) return Optional.empty(); + try { + JsonElement parsed = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8)); + if (!parsed.isJsonObject()) return Optional.empty(); + JsonObject o = parsed.getAsJsonObject(); + return Optional.of(new Stored( + o.get("formatVersion").getAsInt(), + o.get("key").getAsString(), + strings(o.get("extras")), + strings(o.get("untracked")), + map(o.get("outputs")))); + } catch (IOException | RuntimeException e) { + return Optional.empty(); + } + } + + private static java.util.Map map(JsonElement e) { + java.util.Map out = new java.util.TreeMap<>(); + if (e != null && e.isJsonObject()) e.getAsJsonObject().entrySet().forEach(x -> out.put(x.getKey(), x.getValue().getAsString())); + return out; + } + + private static List strings(JsonElement e) { + List out = new ArrayList<>(); + if (e != null && e.isJsonArray()) e.getAsJsonArray().forEach(x -> out.add(x.getAsString())); + return out; + } + + static void write(Path file, Stored stored) { + JsonObject o = new JsonObject(); + o.addProperty("formatVersion", stored.formatVersion()); + o.addProperty("key", stored.key()); + o.add("extras", array(stored.extras())); + o.add("untracked", array(stored.untracked())); + JsonObject outs = new JsonObject(); + new java.util.TreeMap<>(stored.outputs()).forEach(outs::addProperty); + o.add("outputs", outs); + try { + Files.createDirectories(file.getParent()); + Files.writeString(file, GSON.toJson(o) + "\n", StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException("Could not write the codegen fingerprint at " + file, e); + } + } + + private static JsonArray array(List values) { + JsonArray a = new JsonArray(); + values.forEach(a::add); + return a; + } + + static void delete(Path file) { + try { + Files.deleteIfExists(file); + } catch (IOException e) { + throw new UncheckedIOException("Could not remove the codegen fingerprint at " + file, e); + } + } +} diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java index a0338bf323..ce3cba5c53 100644 --- a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/MetaDataGeneratorMojo.java @@ -36,6 +36,30 @@ public class MetaDataGeneratorMojo extends AbstractMetaDataMojo @Parameter(property = "metaobjects.allowUnmetRequires", defaultValue = "false") boolean allowUnmetRequires; + /** + * Run in full even when no input changed since the last successful run (ADR-0062). + * {@code -Dmetaobjects.force=true}, or {@code true} in the configuration. + */ + @Parameter(property = "metaobjects.force", defaultValue = "false") + boolean force; + + @Override + protected boolean skipsWhenUnchanged() { + return true; + } + + @Override + protected boolean forced() { + return force; + } + + @Override + protected void onWholeRunSkipped() { + getLog().info("MetaData Mojo > " + OWNER + ": nothing changed since the last run, so nothing was " + + "generated. Pass -Dmetaobjects.force=true to generate anyway."); + registerGeneratedSourceRoots(); + } + /** How this goal is named in a message telling the adopter what to run. */ static final String OWNER = "mvn metaobjects:generate"; @@ -117,13 +141,28 @@ protected void executeGenerators(MetaDataLoader loader, List generato run.flush(); Set emittedThisBuild = refuseSharedPaths(run.emissions(), run.emittedPaths()); + boolean sweepRefused = false; if (migrating) { getLog().info("MetaData Mojo > Recorded the generator and output dir of every generated " + "file in `.metaobjects/.gen-state/.hashes.json`; this build deletes no orphaned file."); } else if (genStateDir != null) { - sweepOrphans(genStateDir, projectRoot, handEditsByDir, emittedThisBuild, runOwners); + sweepRefused = sweepOrphans(genStateDir, projectRoot, handEditsByDir, emittedThisBuild, runOwners); } reportManifestNotices(run, genStateDir, hadManifestAtStart); + + // ADR-0062: a run that refused a file stores no fingerprint, and a file written + // outside the module (no manifest record) is checked by path. + runWasClean = run.refusedCount() == 0 && !sweepRefused; + List outside = new ArrayList<>(); + if (projectRoot != null) { + Set recorded = genStateDir != null ? HashManifest.load(genStateDir).keySet() : Set.of(); + for (Path emitted : run.emittedPaths()) { + String key = OrphanSweep.keyFor(projectRoot, emitted); + if (key == null || !recorded.contains(key)) outside.add(emitted.toString()); + } + } + Collections.sort(outside); + outputsOutsideModule = outside; } registerGeneratedSourceRoots(); @@ -152,7 +191,7 @@ private void noteOwnedStock() { * ({@link OrphanSweep#isCandidate}): its own generators' files, and files whose * generator the module configures in no execution any more. */ - private void sweepOrphans(Path genStateDir, Path projectRoot, Map> handEditsByDir, + private boolean sweepOrphans(Path genStateDir, Path projectRoot, Map> handEditsByDir, Set emitted, Set runOwners) { List dirs = new ArrayList<>(); for (Map.Entry> e : handEditsByDir.entrySet()) { @@ -171,6 +210,7 @@ private void sweepOrphans(Path genStateDir, Path projectRoot, MapIt regenerates every declared generator into a throwaway temp directory (by overriding - * each generator's {@code outputDir} arg) and then compares the freshly generated tree + *

    It regenerates every declared generator with its output captured in memory (each generator's + * {@code outputDir} arg is pointed at a virtual directory, so no file is written) and then + * compares the freshly generated tree * against the committed output under the configured (real) {@code outputDir}. Any drift — * a file whose content differs, a committed file that the generator no longer produces, or * a newly produced file that is not committed — fails the build with a @@ -164,6 +166,25 @@ private String genGoal() { public void setRequireImplementers(boolean requireImplementers) { this.requireImplementers = requireImplementers; } public boolean isRequireImplementers() { return requireImplementers; } + /** + * Force a full render and byte comparison even when the fingerprint says nothing changed + * (ADR-0062). {@code -Dmetaobjects.verify.full=true}. + */ + @Parameter(property = "metaobjects.verify.full", defaultValue = "false") + private boolean full = false; + + public void setFull(boolean full) { this.full = full; } + + /** The last in-memory render, by normalized absolute path; {@code null} before one runs. */ + private Map rendered; + + /** Whether the fingerprint may answer at all: never in CI, never with {@code full}. */ + private boolean mayAnswerFromFingerprint() { + if (full) return false; + String ci = getEnv("CI"); + return ci == null || ci.isEmpty() || "0".equals(ci) || "false".equalsIgnoreCase(ci); + } + /** The process environment, overridable so a test can set a variable. */ String getEnv(String name) { return System.getenv(name); } @@ -380,6 +401,15 @@ private void verifyCodegen() throws MojoExecutionException, MojoFailureException runFieldLintAdvisory(loader); int requirementErrors = runRequirementGate(loader); + // ADR-0062 §4: locally, the stored fingerprint and the manifest may answer "no drift" + // without rendering. CI always renders; `full` forces a render. + if (mayAnswerFromFingerprint() && fingerprintAnswersNoDrift(loader)) { + getLog().info(PREFIX + "codegen: no drift (no input changed since the last generate and " + + "no generated file was edited). Pass -Dmetaobjects.verify.full=true to render and compare."); + failOnRequirementErrors(requirementErrors); + return; + } + // Per-generator: resolve its committed (real) outputDir from the merged args, then // stage an arg-override so the regenerate writes to a temp dir instead. Keep the // real<->temp mapping for the post-run comparison. @@ -394,10 +424,20 @@ private void verifyCodegen() throws MojoExecutionException, MojoFailureException // to gen when two generators emit the same path: last-writer-wins in both. Path tempRoot; try { - tempRoot = Files.createTempDirectory("metaobjects-verify"); + // The render is captured in memory (GeneratedFileWriter.beginCaptureRun): no generated + // file is written. This root only names the virtual output directories; a generator + // that creates its output directory up front leaves an empty one here, so it goes under + // DEV_SCRATCH when that is set, and the finally below always deletes it. + String scratch = getEnv("DEV_SCRATCH"); + if (scratch != null && !scratch.isEmpty() && Files.isDirectory(Path.of(scratch))) { + tempRoot = Files.createTempDirectory(Path.of(scratch), "metaobjects-verify"); + } else { + tempRoot = Files.createTempDirectory("metaobjects-verify"); + } } catch (IOException e) { throw new MojoExecutionException("Could not create temp dir for verify", e); } + try { // outer: the render directory is deleted whatever happens below Map> overrides = new HashMap<>(); List targets = new ArrayList<>(); @@ -460,9 +500,12 @@ private void verifyCodegen() throws MojoExecutionException, MojoFailureException // Build + run generators with the temp-dir overrides applied. List generatorImpls = buildGenerators(projectClassLoader, overrides); try { - for (Generator gen : generatorImpls) { - getLog().info("MetaData Verify Mojo > Regenerating (temp): " + gen.getClass().getName()); - gen.execute(loader); + try (GeneratedFileWriter.Run capture = GeneratedFileWriter.beginCaptureRun()) { + for (Generator gen : generatorImpls) { + getLog().info("MetaData Verify Mojo > Regenerating (in memory): " + gen.getClass().getName()); + gen.execute(loader); + } + rendered = new HashMap<>(capture.captured()); } // Compare each output directory's temp tree against its committed tree. @@ -515,6 +558,9 @@ private void verifyCodegen() throws MojoExecutionException, MojoFailureException deleteRecursively(tempRoot); } failOnRequirementErrors(requirementErrors); + } finally { + deleteRecursively(tempRoot); + } } /** @@ -536,9 +582,9 @@ private WireFormat matchingWire(MetaDataLoader loader, ClassLoader projectClassL for (WireFormat.NullMembers n : List.of(WireFormat.NullMembers.NATIVE, WireFormat.NullMembers.OMIT)) { if (d == used.decimals() && n == usedNulls) continue; loader.getRoot().setWireFormat(new WireFormat(d, n)); - for (GenTarget t : targets) deleteRecursively(t.tempDir); - try { + try (GeneratedFileWriter.Run capture = GeneratedFileWriter.beginCaptureRun()) { for (Generator gen : buildGenerators(projectClassLoader, overrides)) gen.execute(loader); + rendered = new HashMap<>(capture.captured()); } catch (RuntimeException e) { getLog().debug("MetaData Verify Mojo > wire probe failed: " + e); return null; @@ -652,7 +698,7 @@ private List strandedOutsideTargets(Map ownHashes, List< */ List compareTrees(GenTarget t, Map hashes, Path projectRoot, List editedOrphans) throws MojoExecutionException { - Set generated = relativeFiles(t.tempDir); + Set generated = renderedFiles(t); Set committed = relativeFiles(t.realDir); // Union of relative paths, sorted for stable, deterministic reporting. @@ -703,7 +749,7 @@ List compareTrees(GenTarget t, Map hashes, Path projectR } } else { // Present in both — compare bytes. - if (!contentEquals(t.tempDir.resolve(rel), committedFile)) { + if (!renderedEquals(t, rel, committedFile)) { drift.add("[content-differs] " + committedFile); } } @@ -711,6 +757,32 @@ List compareTrees(GenTarget t, Map hashes, Path projectR return drift; } + /** + * What the generators rendered into {@code t}'s virtual output directory, relative to it. + * The render is held in memory ({@link #rendered}); with none captured (a test driving + * {@link #compareTrees} over a real directory), the directory on disk is walked instead. + */ + private Set renderedFiles(GenTarget t) throws MojoExecutionException { + if (rendered == null) return relativeFiles(t.tempDir); + Path root = t.tempDir.toAbsolutePath().normalize(); + Set out = new LinkedHashSet<>(); + for (Path p : rendered.keySet()) { + if (p.startsWith(root)) out.add(root.relativize(p).toString()); + } + return out; + } + + /** Whether the rendered bytes for {@code rel} equal {@code committedFile}'s, compared in memory. */ + private boolean renderedEquals(GenTarget t, String rel, Path committedFile) throws MojoExecutionException { + if (rendered == null) return contentEquals(t.tempDir.resolve(rel), committedFile); + byte[] fresh = rendered.get(t.tempDir.resolve(rel).toAbsolutePath().normalize()); + try { + return fresh != null && Arrays.equals(fresh, Files.readAllBytes(committedFile)); + } catch (IOException e) { + throw new MojoExecutionException("Could not read [" + committedFile + "]", e); + } + } + /** All regular files under {@code root}, as paths relative to {@code root}; empty if absent. */ private Set relativeFiles(Path root) throws MojoExecutionException { Set out = new LinkedHashSet<>(); diff --git a/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/ModelKey.java b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/ModelKey.java new file mode 100644 index 0000000000..86be8cf3e0 --- /dev/null +++ b/server/java/maven-plugin/src/main/java/com/metaobjects/mojo/ModelKey.java @@ -0,0 +1,53 @@ +package com.metaobjects.mojo; + +import com.metaobjects.MetaData; +import com.metaobjects.io.json.CanonicalJsonSerializer; +import com.metaobjects.loader.MetaDataLoader; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * The model half of the ADR-0062 skip key, taken from the LOADED root and never from the + * metadata source files. + * + *

    Each root-level node is hashed in its canonical effective form + * ({@link CanonicalJsonSerializer#canonicalSerializeEffective}: {@code extends} and overlays + * applied, attributes in fixed order, no source positions), so reformatting a file, reordering + * it or moving an object to another file leaves the key alone, and editing an abstract parent + * changes the key of every object that inherits from it. Node hashes roll up into one hash per + * package (sorted {@code name:hash} lines) and one for the model. The tree is exposed so a later + * per-object or per-package key can reuse it. + */ +final class ModelKey { + + /** Node hashes by {@code type.subtype name}, package hashes by package, and the model hash. */ + record Tree(Map nodes, Map packages, String model) {} + + private ModelKey() {} + + static Tree of(MetaDataLoader loader) { + Map nodes = new TreeMap<>(); + Map> byPackage = new TreeMap<>(); + for (MetaData child : loader.getRoot().getChildren()) { + String name = child.getName() == null ? "" : child.getName(); + String key = child.getType() + "." + child.getSubType() + " " + name; + String hash = GenFingerprint.sha256(key + "\n" + CanonicalJsonSerializer.canonicalSerializeEffective(child)); + nodes.put(key, hash); + String pkg = child.getPackage() == null ? "" : child.getPackage(); + byPackage.computeIfAbsent(pkg, k -> new ArrayList<>()).add(key + ":" + hash); + } + Map packages = new TreeMap<>(); + List modelLines = new ArrayList<>(); + byPackage.forEach((pkg, lines) -> { + lines.sort(Comparator.naturalOrder()); + String h = GenFingerprint.sha256(String.join("\n", lines)); + packages.put(pkg, h); + modelLines.add(pkg + ":" + h); + }); + return new Tree(nodes, packages, GenFingerprint.sha256(String.join("\n", modelLines))); + } +} diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java index c4bd72dc1e..681789f7e1 100644 --- a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/DeclaresNothingWritesNothingTest.java @@ -62,6 +62,8 @@ private MetaDataGeneratorMojo generateGoal(List generators) { private List written() throws Exception { try (Stream s = Files.walk(module)) { return s.filter(Files::isRegularFile) + // the whole-run skip key is uncommitted tool state, not generated output + .filter(p -> !p.getFileName().toString().startsWith(".fingerprint-")) .map(p -> module.relativize(p).toString().replace(File.separatorChar, '/')) .sorted().collect(Collectors.toList()); } diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java new file mode 100644 index 0000000000..e46c042bbd --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/GenSkipConformanceTest.java @@ -0,0 +1,398 @@ +package com.metaobjects.mojo; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.metaobjects.generator.GeneratorBase; +import com.metaobjects.generator.util.GeneratedFileWriter; +import com.metaobjects.loader.MetaDataLoader; +import org.apache.maven.project.MavenProject; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * Runs the shared table of ADR-0062 cases ({@code fixtures/codegen-skip-conformance/cases.json}) + * against the JVM project shape: a Maven module whose pom configures one generator (a stand-in + * for any stock Java or Kotlin generator, which all run through this same goal and the same + * {@code Generator} SPI), a template root, a declared extra input and an owned generator + * directory. Each case runs {@code generate} once, applies the change, and asks both goals what + * they would do. A case id this runner does not know fails the run. + */ +public class GenSkipConformanceTest { + + private static final Path CASES = Path.of("../../../fixtures/codegen-skip-conformance/cases.json"); + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + /** Counts how many times a generator really ran, and carries the per-case switches. */ + public static class FixtureGenerator extends GeneratorBase { + static int runs; + static boolean cacheable = true; + static boolean fail = false; + static Path extra; + + @Override + public boolean cacheable() { + return cacheable; + } + + @Override + public List extraInputs() { + List out = new ArrayList<>(); + out.add(getArg("templatesDir")); + if (extra != null) out.add(extra.toString()); + return out; + } + + @Override + public void execute(MetaDataLoader loader) { + runs++; + if (fail) throw new IllegalStateException("simulated failure"); + try { + GeneratedFileWriter.write(getOutputDir().toPath().resolve("Out.java"), + "/** GENERATED */\nclass Out { /* " + getArg("content", "x") + " */ }\n"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + private Path project; + private Path engine; + private String content; + private boolean lax; + private String ci; + private boolean verifyFull; // -Dmetaobjects.verify.full=true, the verify spelling of --force + + @Before + public void setUp() throws IOException { + project = tmp.getRoot().toPath(); + engine = tmp.newFolder("engine").toPath(); + FixtureGenerator.runs = 0; + FixtureGenerator.cacheable = true; + FixtureGenerator.fail = false; + FixtureGenerator.extra = null; + setUpFiles(); + } + + @After + public void tearDown() { + FixtureGenerator.cacheable = true; + FixtureGenerator.fail = false; + FixtureGenerator.extra = null; + } + + private MavenProject mavenProject() { + MavenProject p = Mockito.mock(MavenProject.class); + Mockito.when(p.getBasedir()).thenReturn(project.toFile()); + return p; + } + + private LoaderParam loader() { + return LoaderParam.builder("skip-conformance") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(project.resolve("metaobjects").toString()) + .build(); + } + + private List generators() { + GeneratorParam g = new GeneratorParam(); + g.setClassname(FixtureGenerator.class.getName()); + g.setArgs(Map.of(GeneratorBase.ARG_OUTPUTDIR, "gen", "templatesDir", "tpl", "content", content)); + return List.of(g); + } + + private void gen(boolean force) throws Exception { + MetaDataGeneratorMojo m = new MetaDataGeneratorMojo() { + @Override + protected List engineClasspath() { + return List.of(engine); + } + }; + m.project = mavenProject(); + m.setLoader(loader()); + m.setGenerators(generators()); + m.setLax(lax); + m.force = force; + m.execute(); + } + + /** Runs verify and returns how many generator runs it spent. Drift is not what this asks. */ + private int verifyRenders() { + MetaDataVerifyMojo m = new MetaDataVerifyMojo() { + @Override + protected List engineClasspath() { + return List.of(engine); + } + + @Override + String getEnv(String name) { + return "CI".equals(name) ? ci : super.getEnv(name); + } + }; + m.project = mavenProject(); + m.setLoader(loader()); + m.setGenerators(generators()); + m.setLax(lax); + m.setMode(MetaDataVerifyMojo.MODE_CODEGEN); + m.setFull(verifyFull); + int before = FixtureGenerator.runs; + try { + m.execute(); + } catch (Exception drift) { + // a render that found drift still rendered + } + return FixtureGenerator.runs - before; + } + + /** Item 9: a rendering verify leaves no temp tree behind, with DEV_SCRATCH set or not, clean or drifted. */ + @Test + public void verifyLeavesNoTempFiles() throws Exception { + gen(false); + Path scratch = tmp.newFolder("scratch").toPath(); + Path sysTmp = Path.of(System.getProperty("java.io.tmpdir")); + long before = countVerifyTemps(sysTmp); + ci = "true"; // CI always renders + verifyWithScratch(null); + verifyWithScratch(scratch.toString()); + Files.writeString(project.resolve("gen/Out.java"), "// drifted\n"); + verifyWithScratch(scratch.toString()); // the drift failure path + ci = null; + assertEquals("nothing left under DEV_SCRATCH", 0, countVerifyTemps(scratch)); + assertEquals("nothing left under the system temp dir", before, countVerifyTemps(sysTmp)); + } + + private static long countVerifyTemps(Path dir) throws IOException { + try (var s = Files.list(dir)) { + return s.filter(p -> p.getFileName().toString().startsWith("metaobjects-verify")).count(); + } + } + + private void verifyWithScratch(String scratch) { + MetaDataVerifyMojo m = new MetaDataVerifyMojo() { + @Override + protected List engineClasspath() { + return List.of(engine); + } + + @Override + String getEnv(String name) { + if ("CI".equals(name)) return ci; + if ("DEV_SCRATCH".equals(name)) return scratch; + return super.getEnv(name); + } + }; + m.project = mavenProject(); + m.setLoader(loader()); + m.setGenerators(generators()); + m.setMode(MetaDataVerifyMojo.MODE_CODEGEN); + try { + m.execute(); + } catch (Exception drift) { + // drift is allowed here; only the leftovers matter + } + } + + private void applyChange(String id) throws Exception { + switch (id) { + case "no-change", "fingerprint-missing-placeholder" -> { } + case "metadata-touched" -> { + Path f = project.resolve("metaobjects/meta.shop.json"); + Files.writeString(f, Files.readString(f)); + } + case "unrelated-file-edited" -> Files.writeString(project.resolve("README.md"), "edited"); + case "metadata-reformatted" -> Files.writeString(project.resolve("metaobjects/meta.extra.json"), """ + { + "metadata.root": { + "children": [ { "object.entity": { "children": [ { "field.string": { "name": "label" } } ], + "extends": "Base", "name": "Gizmo" } } ], + "package": "verify::extra" + } + } + """); + case "metadata-moved" -> { + // The same object, same package, in a different file. + Files.move(project.resolve("metaobjects/meta.extra.json"), project.resolve("metaobjects/meta.moved.json")); + } + case "parent-edited" -> Files.writeString(project.resolve("metaobjects/meta.base.json"), """ + {"metadata.root": {"package": "verify::extra", "children": [ + {"object.entity": {"name": "Base", "abstract": true, "children": [ + {"field.long": {"name": "id"}}, {"field.long": {"name": "createdAt"}} ]}} + ]}} + """); + case "metadata-edited" -> { + Path f = project.resolve("metaobjects/meta.shop.json"); + Files.writeString(f, Files.readString(f).replace("\"quantity\"", "\"quantity2\"")); + } + case "metadata-added" -> Files.writeString(project.resolve("metaobjects/meta.more.json"), """ + {"metadata.root": {"package": "verify::more", "children": [ + {"object.entity": {"name": "Doohickey", "children": [ {"field.long": {"name": "id"}} ]}} + ]}} + """); + case "metadata-removed" -> Files.delete(project.resolve("metaobjects/meta.extra.json")); + case "config-edited" -> content = "y"; + case "project-config-edited" -> + Files.writeString(project.resolve(".metaobjects/config.json"), + "{\n \"schema_version\": 1\n}\n\n"); + case "template-edited" -> Files.writeString(project.resolve("tpl/a.mustache"), "template A"); + case "template-added" -> Files.writeString(project.resolve("tpl/b.mustache"), "b"); + case "owned-generator-edited" -> Files.writeString(project.resolve("codegen/Gen.java"), "class Gen2 {}"); + case "engine-changed" -> Files.writeString(engine.resolve("engine.class"), "v2"); + case "selection-changed" -> lax = true; + case "declared-extra-edited" -> Files.writeString(project.resolve("lookup.txt"), "lookup 2"); + case "uncacheable-generator" -> { } // set up before the first run + case "generated-file-deleted" -> Files.delete(project.resolve("gen/Out.java")); + case "generated-file-edited" -> Files.writeString(project.resolve("gen/Out.java"), + Files.readString(project.resolve("gen/Out.java")) + "// hand edit\n"); + case "hand-edit-kept" -> { + Files.writeString(project.resolve("gen/Out.java"), + Files.readString(project.resolve("gen/Out.java")) + "// hand edit\n"); + gen(false); // renders, keeps the edit, and stores the key with the file as it now is + assertTrue("the run kept the edit", Files.readString(project.resolve("gen/Out.java")).contains("hand edit")); + assertTrue("a key was stored after the kept edit", hasFingerprint()); + } + case "fingerprint-missing" -> { + try (var s = Files.list(project.resolve(".metaobjects/.gen-state"))) { + for (Path p : s.filter(p -> p.getFileName().toString().startsWith(".fingerprint-")).toList()) { + Files.delete(p); + } + } + } + case "force", "ci" -> { } + case "failed-run" -> { + Path f = project.resolve("metaobjects/meta.shop.json"); + String original = Files.readString(f); + Files.writeString(f, original.replace("\"quantity\"", "\"quantity3\"")); + FixtureGenerator.fail = true; + try { + gen(false); + fail("the failing run must fail"); + } catch (RuntimeException expected) { + // the run started after an input change and failed + } + FixtureGenerator.fail = false; + Files.writeString(f, original); // restored to what the last good run saw + } + default -> fail("unknown case id '" + id + "': this runner must handle every id in cases.json"); + } + } + + @Test + public void everyCaseInTheSharedTable() throws Exception { + JsonObject table = JsonParser.parseString(Files.readString(CASES)).getAsJsonObject(); + int ran = 0; + for (JsonElement el : table.getAsJsonArray("cases")) { + JsonObject c = el.getAsJsonObject(); + String id = c.get("id").getAsString(); + runCase(id, c.get("gen").getAsString(), c.get("verify").getAsString()); + ran++; + } + assertTrue(ran > 0); + } + + private void runCase(String id, String expectGen, String expectVerify) throws Exception { + // Each case starts from a fresh project and a fresh run. + tearDown(); + setUp0(); + if (id.equals("uncacheable-generator")) FixtureGenerator.cacheable = false; + FixtureGenerator.extra = project.resolve("lookup.txt"); + gen(false); + assertTrue(id + ": the first run writes", FixtureGenerator.runs == 1); + assertTrue(id + ": the first run writes a file", Files.isRegularFile(project.resolve("gen/Out.java"))); + boolean stored = hasFingerprint(); + assertEquals(id + ": a fingerprint is stored exactly when every generator is cacheable", + !id.equals("uncacheable-generator"), stored); + + applyChange(id); + if (id.equals("ci")) ci = "true"; + verifyFull = id.equals("force"); + + // The verify decision comes first: it writes nothing, so gen then sees the same state. + int rendered = verifyRenders(); + if (expectVerify.equals("may-answer-no-drift")) { + // "may": answering from the fingerprint is allowed; this port does it. + assertEquals(id + ": local verify answers without rendering", 0, rendered); + } else { + assertTrue(id + ": verify must render", rendered > 0); + } + ci = null; + verifyFull = false; + + int before = FixtureGenerator.runs; + gen(id.equals("force")); + boolean ran = FixtureGenerator.runs > before; + assertEquals(id + ": gen " + expectGen, expectGen.equals("regenerate"), ran); + } + + private void setUp0() throws IOException { + // A fresh temp project per case: wipe and rebuild. + deleteTree(project); + Files.createDirectories(project); + Files.createDirectories(engine); + FixtureGenerator.runs = 0; + FixtureGenerator.fail = false; + FixtureGenerator.cacheable = true; + setUpFiles(); + } + + private void setUpFiles() throws IOException { + Files.createDirectories(project.resolve("metaobjects")); + Files.copy(Path.of("src/test/resources/mojo/verify-test-metadata.json"), + project.resolve("metaobjects/meta.shop.json")); + Files.writeString(project.resolve("metaobjects/meta.base.json"), """ + {"metadata.root": {"package": "verify::extra", "children": [ + {"object.entity": {"name": "Base", "abstract": true, "children": [ {"field.long": {"name": "id"}} ]}} + ]}} + """); + Files.writeString(project.resolve("metaobjects/meta.extra.json"), """ + {"metadata.root": {"package": "verify::extra", "children": [ + {"object.entity": {"name": "Gizmo", "extends": "Base", "children": [ {"field.string": {"name": "label"}} ]}} + ]}} + """); + Files.createDirectories(project.resolve("tpl")); + Files.writeString(project.resolve("tpl/a.mustache"), "template a"); + Files.createDirectories(project.resolve("codegen")); + Files.writeString(project.resolve("codegen/Gen.java"), "class Gen {}"); + Files.writeString(project.resolve("lookup.txt"), "lookup"); + Files.writeString(project.resolve("README.md"), "readme"); + Files.createDirectories(project.resolve(".metaobjects")); + Files.writeString(project.resolve(".metaobjects/config.json"), "{\n \"schema_version\": 1\n}\n"); + Files.writeString(engine.resolve("engine.class"), "v1"); + content = "x"; + lax = false; + ci = null; + } + + private boolean hasFingerprint() throws IOException { + Path dir = project.resolve(".metaobjects/.gen-state"); + if (!Files.isDirectory(dir)) return false; + try (var s = Files.list(dir)) { + return s.anyMatch(p -> p.getFileName().toString().startsWith(".fingerprint-java-")); + } + } + + private static void deleteTree(Path root) throws IOException { + if (!Files.exists(root)) return; + try (var walk = Files.walk(root)) { + for (Path p : walk.sorted(java.util.Comparator.reverseOrder()).toList()) { + if (!p.equals(root)) Files.delete(p); + } + } + } +} diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/RefusedOrphanSkipTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/RefusedOrphanSkipTest.java new file mode 100644 index 0000000000..53144fae53 --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/RefusedOrphanSkipTest.java @@ -0,0 +1,108 @@ +package com.metaobjects.mojo; + +import com.metaobjects.generator.GeneratorBase; +import com.metaobjects.generator.util.GeneratedFileWriter; +import com.metaobjects.loader.MetaDataLoader; +import org.apache.maven.project.MavenProject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * ADR-0062: a run whose orphan sweep kept an edited orphan is incomplete. It stores no key, so + * the next run renders again and repeats the refusal instead of printing "nothing changed". + */ +public class RefusedOrphanSkipTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + public static class TwoFileGenerator extends GeneratorBase { + static int runs; + + @Override + public void execute(MetaDataLoader loader) { + runs++; + try { + Path dir = getOutputDir().toPath(); + GeneratedFileWriter.write(dir.resolve("Keep.java"), "/** GENERATED */\nclass Keep {}\n"); + if ("both".equals(getArg("mode"))) { + GeneratedFileWriter.write(dir.resolve("Gone.java"), "/** GENERATED */\nclass Gone {}\n"); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + private Path project; + private Path engine; + + @Before + public void setUp() throws IOException { + project = tmp.getRoot().toPath(); + engine = tmp.newFolder("engine").toPath(); + TwoFileGenerator.runs = 0; + Files.createDirectories(project.resolve("metaobjects")); + Files.copy(Path.of("src/test/resources/mojo/verify-test-metadata.json"), + project.resolve("metaobjects/meta.shop.json")); + Files.writeString(engine.resolve("engine.class"), "v1"); + } + + private void gen(String mode) throws Exception { + MetaDataGeneratorMojo m = new MetaDataGeneratorMojo() { + @Override + protected List engineClasspath() { + return List.of(engine); + } + }; + MavenProject p = Mockito.mock(MavenProject.class); + Mockito.when(p.getBasedir()).thenReturn(project.toFile()); + m.project = p; + m.setLoader(LoaderParam.builder("refused-orphan") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(project.resolve("metaobjects").toString()) + .build()); + GeneratorParam g = new GeneratorParam(); + g.setClassname(TwoFileGenerator.class.getName()); + g.setArgs(Map.of(GeneratorBase.ARG_OUTPUTDIR, "gen", "mode", mode)); + m.setGenerators(List.of(g)); + m.execute(); + } + + private boolean hasFingerprint() throws IOException { + Path state = project.resolve(".metaobjects/.gen-state"); + if (!Files.isDirectory(state)) return false; + try (var s = Files.list(state)) { + return s.anyMatch(p -> p.getFileName().toString().startsWith(".fingerprint-")); + } + } + + @Test + public void anEditedOrphanTheSweepKeepsStoresNoKey() throws Exception { + gen("both"); + assertTrue(hasFingerprint()); + Path orphan = project.resolve("gen/Gone.java"); + Files.writeString(orphan, Files.readString(orphan) + "// mine\n"); + + gen("one"); + assertTrue("the edited orphan is kept", Files.isRegularFile(orphan)); + assertEquals(2, TwoFileGenerator.runs); + assertFalse("a run whose sweep refused stored a key", hasFingerprint()); + + gen("one"); + assertEquals("nothing is stored, so the next run renders again", 3, TwoFileGenerator.runs); + } +} diff --git a/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/UnrecordedOutputSkipTest.java b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/UnrecordedOutputSkipTest.java new file mode 100644 index 0000000000..8b1231f4db --- /dev/null +++ b/server/java/maven-plugin/src/test/java/com/metaobjects/mojo/UnrecordedOutputSkipTest.java @@ -0,0 +1,101 @@ +package com.metaobjects.mojo; + +import com.metaobjects.generator.GeneratorBase; +import com.metaobjects.generator.util.GeneratedFileWriter; +import com.metaobjects.loader.MetaDataLoader; +import org.apache.maven.project.MavenProject; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * ADR-0062: an output a generator writes straight through {@code writeIfChanged} is in no hash + * manifest, yet a run that finds it gone must render again rather than skip. + */ +public class UnrecordedOutputSkipTest { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + public static class DirectWriteGenerator extends GeneratorBase { + static int runs; + + @Override + public void execute(MetaDataLoader loader) { + runs++; + try { + GeneratedFileWriter.writeIfChanged(getOutputDir().toPath().resolve("plain.json"), "{}\n"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + private Path project; + private Path engine; + + @Before + public void setUp() throws IOException { + project = tmp.getRoot().toPath(); + engine = tmp.newFolder("engine").toPath(); + DirectWriteGenerator.runs = 0; + Files.createDirectories(project.resolve("metaobjects")); + Files.copy(Path.of("src/test/resources/mojo/verify-test-metadata.json"), + project.resolve("metaobjects/meta.shop.json")); + Files.writeString(engine.resolve("engine.class"), "v1"); + } + + @After + public void tearDown() { + DirectWriteGenerator.runs = 0; + } + + private void gen() throws Exception { + MetaDataGeneratorMojo m = new MetaDataGeneratorMojo() { + @Override + protected List engineClasspath() { + return List.of(engine); + } + }; + MavenProject p = Mockito.mock(MavenProject.class); + Mockito.when(p.getBasedir()).thenReturn(project.toFile()); + m.project = p; + m.setLoader(LoaderParam.builder("unrecorded") + .withClassname("com.metaobjects.loader.MetaDataLoader") + .withSourceDir(project.resolve("metaobjects").toString()) + .build()); + GeneratorParam g = new GeneratorParam(); + g.setClassname(DirectWriteGenerator.class.getName()); + g.setArgs(Map.of(GeneratorBase.ARG_OUTPUTDIR, "gen")); + m.setGenerators(List.of(g)); + m.execute(); + } + + @Test + public void aDeletedUnrecordedOutputMakesTheNextRunRender() throws Exception { + gen(); + assertEquals(1, DirectWriteGenerator.runs); + Path out = project.resolve("gen/plain.json"); + assertTrue(Files.isRegularFile(out)); + + gen(); + assertEquals("nothing changed: the second run skips", 1, DirectWriteGenerator.runs); + + Files.delete(out); + gen(); + assertEquals("the output is gone: the run must render", 2, DirectWriteGenerator.runs); + assertTrue("the output is back", Files.isRegularFile(out)); + } +} diff --git a/server/python/src/metaobjects/cli.py b/server/python/src/metaobjects/cli.py index 06817f3b69..86a308bf8c 100644 --- a/server/python/src/metaobjects/cli.py +++ b/server/python/src/metaobjects/cli.py @@ -58,7 +58,6 @@ import os import re import sys -import tempfile from pathlib import Path from typing import Any, Callable @@ -91,6 +90,7 @@ ) from metaobjects.codegen.config import DEFAULT_API_PREFIX, GenConfig from metaobjects.codegen.overwrite_policy import ( + HashManifest, has_hash_manifest, is_pristine_generated, read_generated_hash, @@ -102,7 +102,8 @@ TargetConfig, load_project_config, ) -from metaobjects.codegen.generator import Generator +from metaobjects.codegen.generator import Generator, generator_cacheable, generator_extra_inputs +from metaobjects.codegen import model_key, skip from metaobjects.codegen.generators.entity_model import entity_model from metaobjects.codegen.generators.extractor_generator import extractor_generator from metaobjects.codegen.generators.filter_allowlist_generator import ( @@ -902,7 +903,9 @@ def _run_suite( api_prefix: str = DEFAULT_API_PREFIX, overwrite_hand_edits: frozenset[str] = frozenset(), overwrite_paths_out: set[str] | None = None, -) -> list[str]: + manifest: HashManifest | None = None, + sink: dict[str, str] | None = None, +) -> list[tuple[str, str]]: """Run a generator suite against an ALREADY-LOADED ``root`` into ``out_dir``. ``overwrite_hand_edits`` names the generators (by ``.name``) declared @@ -913,7 +916,8 @@ def _run_suite( Split out from :func:`_generate` so a single gen invocation can load the metadata once and run multiple passes against it (the default Python suite + the ``--template-spec`` pass). See :func:`_generate` for the parameter - semantics. Returns the written paths. + semantics. Returns ``(path, status)`` for every emitted file that was not refused + (status ``unchanged`` marks a file left alone because its bytes already matched). ``select`` (FR-023 §11.1 item 2) — normally a resolved `Collection`'s `in_scope`: the output filter that excludes an imported dependency's @@ -953,6 +957,8 @@ def _run_suite( # verify path (those pass gen_state_dir=None and record nothing at all). baseline=baseline, overwrite_hand_edits=overwrite_hand_edits, + manifest=manifest, + sink=sink, ) # No default suite — see NO_GENERATORS_SELECTED. A caller that names none gets a # usage error and an empty out dir, never a shape this CLI picked. @@ -972,7 +978,7 @@ def _run_suite( # and only the ones that own an exit code care about the refusals. if refused_out is not None: refused_out.extend(path for path, status in result.files if status == "refused") - return [path for path, status in result.files if status != "refused"] + return [(path, status) for path, status in result.files if status != "refused"] def gen_state_dir_for(metadata_dir: str) -> str: @@ -1496,6 +1502,9 @@ def _run_gen_targets( selection: list[str] | None = None, targeted_out: set[str] | None = None, overwrite_paths_out: set[str] | None = None, + emitted_out: set[str] | None = None, + skip_info: skip.SkipRunInfo | None = None, + sink: dict[str, str] | None = None, ) -> tuple[list[str], list[str]]: """Run each target's declared generators into its ``outDir``. Returns (all_written, errors). @@ -1524,6 +1533,11 @@ def _run_gen_targets( ``targeted_out`` collects the ``outDir`` of every target with a declared entry left to run after ``selection``: decided from the config, whatever the entries then emit. + The returned list holds only the files this run WROTE; ``emitted_out`` collects every + path the run emitted, unchanged ones included (what the orphan sweep and the duplicate + guard need). ``skip_info`` (ADR-0062) learns whether every generator is cacheable and + the extra inputs they declared, hashed before the first write. + A generator entry written as ``{name: ..., handEdits: overwrite}`` replaces its hand-edited files instead of refusing them; ``overwrite_paths_out`` collects the paths such entries emitted (see :func:`_run_suite`). @@ -1604,6 +1618,49 @@ def selected(gen: Generator, token: str) -> bool: if errors: return [], errors + if skip_info is not None: + every = [g for _t, gens, spec_gens, _o in plan for g in (*gens, *spec_gens)] + skip_info.cacheable = all(generator_cacheable(g) for g in every) + skip_info.extras = {p for g in every for p in generator_extra_inputs(g)} + skip_info.extra_entries = skip.extras_entries( + Path(project_root or "."), skip_info.extras) + + from metaobjects.render.renderer import RenderError + + # ONE manifest session for the whole run (ADR-0062 decision 1), saved once at the end + # and only when an entry changed. + session = HashManifest(gen_state_dir) if gen_state_dir is not None else None + try: + return _run_plan( + config, plan, root, seen, all_written, errors, session, template_root, + gen_state_dir, project_root, baseline, refused_out, select, column_naming, + targeted_out, overwrite_paths_out, emitted_out, sink, + ) + finally: + if session is not None: + session.save() + + +def _run_plan( + config: ProjectConfig, + plan: list[tuple[TargetConfig, list[Generator], list[Generator], frozenset[str]]], + root: MetaData, + seen: dict[str, str], + all_written: list[str], + errors: list[str], + session: HashManifest | None, + template_root: str, + gen_state_dir: str | None, + project_root: str | None, + baseline: str, + refused_out: list[str] | None, + select: Callable[[str], bool] | None, + column_naming: str, + targeted_out: set[str] | None, + overwrite_paths_out: set[str] | None, + emitted_out: set[str] | None, + sink: dict[str, str] | None = None, +) -> tuple[list[str], list[str]]: from metaobjects.render.renderer import RenderError for t, gens, spec_gens, overwrite in plan: @@ -1613,21 +1670,23 @@ def selected(gen: Generator, token: str) -> bool: out_dir = config.out_dir_for(t) if targeted_out is not None: targeted_out.add(out_dir) - written: list[str] = [] + results: list[tuple[str, str]] = [] try: if gens: - written = _run_suite( + results = _run_suite( root, out_dir, gens, t.entities, gen_state_dir=gen_state_dir, column_naming=column_naming, project_root=project_root, baseline=baseline, refused_out=refused_out, select=select, api_prefix=config.api_prefix, overwrite_hand_edits=overwrite, overwrite_paths_out=overwrite_paths_out, + manifest=session, sink=sink, ) if spec_gens: - written = written + _run_suite( + results = results + _run_suite( root, out_dir, spec_gens, t.entities, emit_package_init=False, gen_state_dir=gen_state_dir, column_naming=column_naming, project_root=project_root, baseline=baseline, refused_out=refused_out, - select=select, api_prefix=config.api_prefix, + select=select, api_prefix=config.api_prefix, manifest=session, + sink=sink, ) except ValueError as exc: # intra-target run_gen collision → clean error errors.append(f"target '{t.name}': {exc}") @@ -1638,7 +1697,11 @@ def selected(gen: Generator, token: str) -> bool: f"template refs and the --templates dir {template_root!r}): {exc}" ) continue - for full in written: + emitted = [path for path, _status in results] + written = [path for path, status in results if status not in _NOT_WRITTEN] + if emitted_out is not None: + emitted_out.update(emitted) + for full in emitted: if Path(full).name == "__init__.py": continue # auto-emitted package marker — byte-identical across targets sharing an outDir; not a real collision prior = seen.get(full) @@ -1653,7 +1716,166 @@ def selected(gen: Generator, token: str) -> bool: return all_written, errors +#: Statuses of an emitted file that was NOT written: the bytes already matched, it was +#: left alone as an existing file, or its on-disk text was only recorded as the baseline. +_NOT_WRITTEN = frozenset({"unchanged", "skipped", "adopted"}) + + +def _skip_identity( + args: argparse.Namespace, + config: ProjectConfig, + config_path: Path | None, + *, + strict: bool, + baseline: str, +) -> list[skip.InputEntry] | None: + """The generator-side entries of the skip key (ADR-0062 section 3), as named entries. + + Every input that can change what ``gen`` writes OTHER than the model: the engine's built + code, the generator config, owned generators, templates, the project config and the flags + that change output. No metadata source file is read: the model is keyed from the loaded + root (:func:`_model_entries`). ``None`` means an input could not be proven (an owned module + that cannot be found, a refused template root): the run then goes ahead in full. + """ + project = project_root_for(config.metadata_dir()) + entries: list[skip.InputEntry] = list(skip.engine_entries()) + + def rel(path: Path) -> str: + try: + return path.resolve().relative_to(project).as_posix() + except ValueError: + return str(path) + + if config_path is not None: + entries.append(skip.InputEntry(skip.KIND_CONFIG, rel(config_path), skip.hash_file(config_path))) + meta_dir = project / ".metaobjects" + for name in ("config.json", "deps.lock.json"): + entries.append(skip.InputEntry(skip.KIND_CONFIG, f".metaobjects/{name}", + skip.hash_file(meta_dir / name))) + entries.append(skip.InputEntry(skip.KIND_CONFIG, ".metaobjects/deps", + skip.hash_tree(meta_dir / "deps"))) + + flags = { + "generators": ",".join(_selection_from_args(args) or []) + if getattr(args, "generators", None) is not None else "", + "entities": getattr(args, "entities", None) or "", + "target": getattr(args, "target", None) or "", + "strict": str(bool(strict)), + "baseline": baseline, + } + for name, value in flags.items(): + entries.append(skip.InputEntry(skip.KIND_FLAG, name, str(value))) + + template_root, refusal = _template_root_for_config(args, config) + if refusal is not None: + return None + entries.append(skip.InputEntry(skip.KIND_TEMPLATES, "root", skip.hash_tree(Path(template_root)))) + for t in config.targets: + spec = config.template_spec_for(t) + if spec is not None: + entries.append(skip.InputEntry(skip.KIND_TEMPLATES, f"spec:{t.name}", skip.hash_file(Path(spec)))) + + for t in config.targets: + for token in t.generators or []: + if get_generator(token) is not None: + entries.append(skip.InputEntry(skip.KIND_GENERATOR, token, "stock")) + continue + found = skip.module_source_entries(token, config.config_dir) + if found is None: + return None + entries.append(skip.InputEntry(skip.KIND_GENERATOR, token, "owned")) + entries.extend(found) + + specs = [*config.providers, *(getattr(args, "provider", None) or [])] + rt = config.requirement_tests + if rt is not None: + specs.extend(x for x in (rt.renderer, rt.filter) if x) + for spec in specs: + found = skip.module_source_entries(spec, config.config_dir) + if found is None: + return None + entries.extend(found) + return entries + + +def _model_entries(root: MetaData) -> list[skip.InputEntry]: + """The model half of the key: the loaded root's hash tree plus the settings carried on it + that reach generated output. Built from the loaded root, never from source files.""" + tree = model_key.build_model_tree(root) + return [ + skip.InputEntry(skip.KIND_MODEL, "model", tree.model), + skip.InputEntry(skip.KIND_MODEL, "naming", f"{root.naming.columns}/{root.naming.tables}"), + skip.InputEntry(skip.KIND_MODEL, "wire", wire_block(root.wire)), + ] + + +class _SkipState: + """What one ``gen`` run knows about its stored key, so a failed run can never leave one.""" + + def __init__(self) -> None: + self.skipped = False + self.stored = False + + +def _skip_matches( + config: ProjectConfig, + identity: list[skip.InputEntry] | None, + root: MetaData, +) -> bool: + """True when the key computed from ``identity`` and the loaded ``root`` equals the stored + one and every file the manifest records exists.""" + if identity is None: + return False + gen_state_dir = gen_state_dir_for(config.metadata_dir()) + stored = skip.read_stored(gen_state_dir) + if stored is None: + return False + project = project_root_for(config.metadata_dir()) + try: + key = skip.current_key([*identity, *_model_entries(root)], project, stored) + except Exception: # noqa: BLE001 - a model that cannot be keyed is not proven unchanged + return False + return key == stored.key and skip.outputs_unchanged( + stored, gen_state_dir, project, [config.out_dir_for(t) for t in config.targets]) + + +def _verify_may_answer( + args: argparse.Namespace, + config: ProjectConfig, + identity: list[skip.InputEntry] | None, + root: MetaData, +) -> bool: + """A LOCAL ``verify --codegen`` may answer "no drift" without rendering (ADR-0062 section + 4): not in CI, not ``--full``, the stored key matches and every file the manifest records + still hashes to its recorded entry.""" + if getattr(args, "full", False) or skip.ci_environment(): + return False + if not _skip_matches(config, identity, root): + return False + return skip.manifest_files_match( + gen_state_dir_for(config.metadata_dir()), project_root_for(config.metadata_dir()), + [config.out_dir_for(t) for t in config.targets]) + + def _cmd_gen_config(args: argparse.Namespace) -> int: + """``gen`` with the ADR-0062 stored-key guard: unless the run skipped or stored a fresh + key, whatever key a previous run left is deleted, so a failed or half-written run is never + mistaken for a current one.""" + state = _SkipState() + try: + return _cmd_gen_config_run(args, state) + finally: + if not state.skipped and not state.stored: + config_path = _find_config(args) + try: + cfg = load_project_config(config_path) if config_path is not None else None + except ConfigError: + cfg = None + if cfg is not None: + skip.delete_stored(gen_state_dir_for(cfg.metadata_dir())) + + +def _cmd_gen_config_run(args: argparse.Namespace, state: _SkipState) -> int: """``gen`` — run the generator list in ``metaobjects.config.yaml`` (ADR-0034 Amendment 9). Load the config, load metadata ONCE, and run every target (or ``--target``) into its own @@ -1676,6 +1898,10 @@ def _cmd_gen_config(args: argparse.Namespace) -> int: return 1 targets = _narrow_entities(targets, args) + strict = bool(getattr(args, "strict", False)) + baseline = getattr(args, "baseline", None) or "default" + gen_state_dir = gen_state_dir_for(config.metadata_dir()) + providers, providers_ok = _config_providers(config) if not providers_ok: return 1 @@ -1695,7 +1921,6 @@ def _cmd_gen_config(args: argparse.Namespace) -> int: # `--strict` is the load `verify` uses (ADR-0023): an unknown attribute is an error and # nothing is written. Without it `gen` loads leniently and only warns. - strict = bool(getattr(args, "strict", False)) unknown_attrs: list[str] = [] root, load_errors = _load_root_from_collection( collection, strict=strict, providers=providers, libraries=config.libraries, @@ -1730,9 +1955,24 @@ def _cmd_gen_config(args: argparse.Namespace) -> int: refused: list[str] = [] targeted: set[str] = set() - baseline = getattr(args, "baseline", None) or "default" - gen_state_dir = gen_state_dir_for(config.metadata_dir()) project_root = str(project_root_for(config.metadata_dir())) + emitted: set[str] = set() + + # ADR-0062: the decision comes AFTER the load (the key is made of the loaded model) and + # BEFORE anything renders. A skip renders and writes nothing, the stored key included. + identity = _skip_identity(args, config, _find_config(args), strict=strict, baseline=baseline) + if ( + _skip_matches(config, identity, root) + and not getattr(args, "force", False) + and baseline != "adopt" + ): + state.skipped = True + print("metaobjects gen: nothing changed since the last run, so nothing was generated " + "(pass --force to regenerate).") + return 0 + skip.delete_stored(gen_state_dir) + model_entries = _model_entries(root) if identity is not None else None + skip_info = skip.SkipRunInfo() written, errors = _run_gen_targets( config, targets, root, gen_state_dir=gen_state_dir, @@ -1744,6 +1984,8 @@ def _cmd_gen_config(args: argparse.Namespace) -> int: column_naming=column_naming, selection=selection, targeted_out=targeted, + emitted_out=emitted, + skip_info=skip_info, ) if errors: for msg in errors: @@ -1751,14 +1993,17 @@ def _cmd_gen_config(args: argparse.Namespace) -> int: return 1 for path in written: print(path) + sweep_refused: list[str] = [] removed = _sweep_orphans_after_gen( args, config, targets, targeted, selection, baseline, gen_state_dir, project_root, - emitted={*written, *refused}, + emitted={*emitted, *refused}, refused_out=sweep_refused, ) for path in removed: print(f"removed {path}") + unchanged = len(emitted) - len(written) print( - f"metaobjects gen: wrote {len(written)} file(s) across {len(targets)} target(s)." + f"metaobjects gen: wrote {len(written)} file(s) across {len(targets)} target(s)" + + (f", {unchanged} unchanged." if unchanged > 0 else ".") + (f" Removed {len(removed)} file(s) no generator emits any more." if removed else "") ) if refused: @@ -1772,6 +2017,23 @@ def _cmd_gen_config(args: argparse.Namespace) -> int: file=sys.stderr, ) return 1 + if ( + identity is not None and model_entries is not None and skip_info.cacheable + and baseline != "adopt" and emitted and not sweep_refused # a refusal is a failure (ADR-0062) + ): + outputs = skip.output_hashes( + gen_state_dir, Path(project_root), [config.out_dir_for(t) for t in config.targets]) + if outputs is not None: # a recorded file missing after the run: store no key + skip.write_stored( + gen_state_dir, + skip.fold([*identity, *model_entries, *(skip_info.extra_entries or [])]), + skip_info.extras or [], + outputs, + skip.untracked_outputs( + gen_state_dir, Path(project_root), + [config.out_dir_for(t) for t in config.targets], emitted), + ) + state.stored = True return 0 @@ -1786,6 +2048,7 @@ def _sweep_orphans_after_gen( project_root: str, *, emitted: set[str], + refused_out: list[str] | None = None, ) -> list[str]: """Delete what this run no longer generates (``codegen/orphan_sweep.py``) and return the paths removed. Only a run of the WHOLE declared output into a directory sweeps it. @@ -1827,6 +2090,8 @@ def _sweep_orphans_after_gen( ) if result.refused: print(f"warning: {refused_orphan_message(result.refused)}") + if refused_out is not None: + refused_out.extend(result.refused) return result.removed @@ -1852,6 +2117,28 @@ def _overwrites_hand_edits(config: ProjectConfig, out_dir: str) -> bool: _UNCOMPARED_SUFFIXES = {".pyc", ".pyo"} +#: The virtual root ``verify --codegen`` keys its in-memory render under. Never created. +_VIRTUAL_RENDER_ROOT = os.path.join(os.sep, "__metaobjects_verify_render__") + + +def _memory_set( + rendered: dict[str, str], root: Path, nested: list[Path] | None = None +) -> dict[str, str]: + """:func:`_relative_set`'s counterpart for a render held in memory: the rendered files + under the virtual ``root``, keyed by path relative to it, skipping what + :func:`_relative_set` skips.""" + files: dict[str, str] = {} + for full, text in sorted(rendered.items()): + p = Path(full) + if not p.is_relative_to(root) or any(p.is_relative_to(n) for n in nested or []): + continue + rel = p.relative_to(root) + if any(part in _UNCOMPARED_DIRS for part in rel.parts) or p.suffix in _UNCOMPARED_SUFFIXES: + continue + files[str(rel)] = text + return files + + def _relative_set(root: Path, nested: list[Path] | None = None) -> dict[str, str]: """Map every generated-artifact file under ``root`` to its content, keyed by rel path. @@ -2065,6 +2352,16 @@ def _verify_codegen_config(args: argparse.Namespace) -> int: if templates_refusal is not None: print(templates_refusal, file=sys.stderr) return 2 + + # ADR-0062 section 4: locally, after the load, answer from the stored key and the + # manifest when both prove nothing changed. CI and `--full` always render, and that full + # render is the guard that catches anything the key missed. Neither `strict` nor the load + # choice changes what is written, so the key is computed as `gen`'s default run. + identity = _skip_identity(args, config, _find_config(args), strict=False, baseline="default") + if _verify_may_answer(args, config, identity, root): + print("metaobjects verify: in sync (the model and every recorded file are unchanged " + "since the last gen; pass --full to render and compare).") + return 0 # ADR-0058 Decision 3 — the loaded root's `naming` is THE strategy. column_naming = root.naming.columns @@ -2084,108 +2381,114 @@ def compare(naming: str) -> tuple[list[str], list[_DirReport]]: (``overwrite_dir``), when ``gen`` deletes the edited one too. ``replaced`` is the subset of ``changed`` that was edited by hand and that ``gen`` replaces anyway, because its generator is declared ``handEdits: overwrite``.""" - with tempfile.TemporaryDirectory() as temp_root, tempfile.TemporaryDirectory() as declared_root: - temp_for = { - real: _temp_slot_for(Path(temp_root), real, config.config_dir) for real in real_outdirs - } - remapped = [ - dataclasses.replace(t, out_dir=temp_for[config.out_dir_for(t)]) for t in closure - ] + # Rendered IN MEMORY (``sink``): nothing is written for the comparison, so a verify + # run creates no temp tree and no scratch gen-state. The slots are virtual paths that + # only key the rendered files; they are never created on disk. + temp_root = _VIRTUAL_RENDER_ROOT + declared_root = _VIRTUAL_RENDER_ROOT + "-declared" + sink: dict[str, str] = {} + declared_sink: dict[str, str] = {} + temp_for = { + real: _temp_slot_for(Path(temp_root), real, config.config_dir) for real in real_outdirs + } + remapped = [ + dataclasses.replace(t, out_dir=temp_for[config.out_dir_for(t)]) for t in closure + ] - # The exact gen pipeline into the temp tree — verify now rejects exactly - # what gen rejects (incl. the cross-target duplicate-output-path guard). - # gen_state_dir stays None: this regenerates into a temp tree purely to - # diff, so recording a manifest would mutate the user's project from a - # read-only drift check, keyed to a directory deleted seconds later. - # build_ctx from the SAME resolver `gen` uses — a verify that resolved the - # template root differently would regenerate render-helper against another - # directory and convict the committed output of being stale. - targeted: set[str] = set() - overwrite_paths: set[str] = set() - regen = dict( - select=collection.in_scope, - build_ctx=GeneratorBuildContext(template_root), - # R31: the `names` generator's constants are strategy-dependent, so the regen - # must use the strategy `gen` wrote with, or every constant reads as drift. - column_naming=naming, - ) + # The exact gen pipeline, rendered into the in-memory sink — verify rejects exactly + # what gen rejects (incl. the cross-target duplicate-output-path guard). + # gen_state_dir stays None: this render exists purely to diff, so recording a + # manifest would mutate the user's project from a read-only drift check. + # build_ctx from the SAME resolver `gen` uses — a verify that resolved the + # template root differently would regenerate render-helper against another + # directory and convict the committed output of being stale. + targeted: set[str] = set() + overwrite_paths: set[str] = set() + regen = dict( + select=collection.in_scope, + build_ctx=GeneratorBuildContext(template_root), + # R31: the `names` generator's constants are strategy-dependent, so the regen + # must use the strategy `gen` wrote with, or every constant reads as drift. + column_naming=naming, + ) + _written, errors = _run_gen_targets( + config, remapped, root, selection=selection, targeted_out=targeted, + overwrite_paths_out=overwrite_paths, sink=sink, **regen) + # A narrowed run's paths get the content the whole declared list writes, which is + # what `gen` committed: a second regen of the un-narrowed closure supplies it. + declared_for: dict[str, str] = {} + if narrowed and not errors: + unnarrowed = [t for t in config.targets if config.out_dir_for(t) in temp_for] + for real in temp_for: + declared_for[real] = _temp_slot_for(Path(declared_root), real, config.config_dir) _written, errors = _run_gen_targets( - config, remapped, root, selection=selection, targeted_out=targeted, - overwrite_paths_out=overwrite_paths, **regen) - # A narrowed run's paths get the content the whole declared list writes, which is - # what `gen` committed: a second regen of the un-narrowed closure supplies it. - declared_for: dict[str, str] = {} - if narrowed and not errors: - unnarrowed = [t for t in config.targets if config.out_dir_for(t) in temp_for] - for real in temp_for: - declared_for[real] = _temp_slot_for(Path(declared_root), real, config.config_dir) - _written, errors = _run_gen_targets( - config, - [dataclasses.replace(t, out_dir=declared_for[config.out_dir_for(t)]) - for t in unnarrowed], - root, **regen) - if errors: - return errors, [] - - reports: list[_DirReport] = [] - for real_outdir in real_outdirs: - tmp_slot = temp_for[real_outdir] - if narrowed and tmp_slot not in targeted: - continue - nested = [ - o for o in configured_outdirs if o != real_outdir and Path(o).is_relative_to(real_outdir) - ] - inside = [o for o in nested if o in temp_for] - expected = _relative_set(Path(tmp_slot), [Path(temp_for[o]) for o in inside]) - committed = _relative_set(Path(real_outdir), [Path(o) for o in nested]) - if narrowed: - declared = _relative_set( - Path(declared_for[real_outdir]), [Path(declared_for[o]) for o in inside]) - expected = {k: declared[k] for k in expected if k in declared} - - changed = sorted( - k for k in expected if k in committed and expected[k] != committed[k] + config, + [dataclasses.replace(t, out_dir=declared_for[config.out_dir_for(t)]) + for t in unnarrowed], + root, sink=declared_sink, **regen) + if errors: + return errors, [] + + reports: list[_DirReport] = [] + for real_outdir in real_outdirs: + tmp_slot = temp_for[real_outdir] + if narrowed and tmp_slot not in targeted: + continue + nested = [ + o for o in configured_outdirs if o != real_outdir and Path(o).is_relative_to(real_outdir) + ] + inside = [o for o in nested if o in temp_for] + expected = _memory_set(sink, Path(tmp_slot), [Path(temp_for[o]) for o in inside]) + committed = _relative_set(Path(real_outdir), [Path(o) for o in nested]) + if narrowed: + declared = _memory_set( + declared_sink, Path(declared_for[real_outdir]), + [Path(declared_for[o]) for o in inside]) + expected = {k: declared[k] for k in expected if k in declared} + + changed = sorted( + k for k in expected if k in committed and expected[k] != committed[k] + ) + missing = sorted(k for k in expected if k not in committed) + project_gen_state = gen_state_dir_for(config.metadata_dir()) + prefix = _out_prefix(real_outdir, project_root_for(config.metadata_dir())) + if narrowed: + extra: list[str] = [] + else: + # Same jurisdiction rule as _diff_report — this rung inlines its diff to + # report per-target, so the guard has to be inlined with it. Without it, + # broadening the comparison past *.py convicts every stranger's file. + # + # PER-TARGET prefix, because that is the whole point on this rung: two + # targets with different outDirs share one manifest, and the key that tells + # their identically-named files apart is the one anchored on the project. + is_ours = _is_ours_for(project_gen_state, prefix) + extra = sorted(k for k in committed if k not in expected and is_ours(k)) + # The sweep's own test, on the same evidence: with no manifest nothing is + # proven untouched, and every extra file reads as edited. + edited_extra = [ + k for k in extra + if not is_pristine_generated( + project_gen_state, os.path.join(prefix, k), committed[k], legacy_rel_path=k ) - missing = sorted(k for k in expected if k not in committed) - project_gen_state = gen_state_dir_for(config.metadata_dir()) - prefix = _out_prefix(real_outdir, project_root_for(config.metadata_dir())) - if narrowed: - extra: list[str] = [] - else: - # Same jurisdiction rule as _diff_report — this rung inlines its diff to - # report per-target, so the guard has to be inlined with it. Without it, - # broadening the comparison past *.py convicts every stranger's file. - # - # PER-TARGET prefix, because that is the whole point on this rung: two - # targets with different outDirs share one manifest, and the key that tells - # their identically-named files apart is the one anchored on the project. - is_ours = _is_ours_for(project_gen_state, prefix) - extra = sorted(k for k in committed if k not in expected and is_ours(k)) - # The sweep's own test, on the same evidence: with no manifest nothing is - # proven untouched, and every extra file reads as edited. - edited_extra = [ - k for k in extra - if not is_pristine_generated( - project_gen_state, os.path.join(prefix, k), committed[k], legacy_rel_path=k - ) - ] - - replaced = [ - k for k in changed - if os.path.join(tmp_slot, k) in overwrite_paths - and not is_pristine_generated( - project_gen_state, os.path.join(prefix, k), committed[k], legacy_rel_path=k - ) - ] + ] - names = "+".join( - t.name for t in closure if config.out_dir_for(t) == real_outdir + replaced = [ + k for k in changed + if os.path.join(tmp_slot, k) in overwrite_paths + and not is_pristine_generated( + project_gen_state, os.path.join(prefix, k), committed[k], legacy_rel_path=k ) - reports.append(_DirReport( - names, len(expected), changed, missing, extra, edited_extra, replaced, - _overwrites_hand_edits(config, real_outdir), - )) - return [], reports + ] + + names = "+".join( + t.name for t in closure if config.out_dir_for(t) == real_outdir + ) + reports.append(_DirReport( + names, len(expected), changed, missing, extra, edited_extra, replaced, + _overwrites_hand_edits(config, real_outdir), + )) + return [], reports errors, reports = compare(column_naming) if errors: @@ -2885,6 +3188,14 @@ def _build_parser() -> argparse.ArgumentParser: action="store_true", help="list registered generators (stable name + description) and exit", ) + gen.add_argument( + "--force", + action="store_true", + help=( + "regenerate even when the model and every generator identity match the last " + "successful run (without it, an unchanged project skips rendering; ADR-0062)." + ), + ) gen.add_argument( "--baseline", choices=("default", "adopt"), @@ -3055,6 +3366,14 @@ def _build_parser() -> argparse.ArgumentParser: "META_REQUIRE_IMPLEMENTERS=1 does the same." ), ) + verify.add_argument( + "--full", + action="store_true", + help=( + "with --codegen: always render and compare, never answer from the stored key " + "(a local run may skip the render when nothing changed; CI never does)." + ), + ) verify.add_argument( "--lax", action="store_true", diff --git a/server/python/src/metaobjects/codegen/config.py b/server/python/src/metaobjects/codegen/config.py index 3b862adc2b..bc0edd1f00 100644 --- a/server/python/src/metaobjects/codegen/config.py +++ b/server/python/src/metaobjects/codegen/config.py @@ -5,6 +5,8 @@ from metaobjects.naming import DEFAULT_COLUMN_NAMING +from .overwrite_policy import HashManifest + #: What generated routers mount under when no ``apiPrefix`` is configured. DEFAULT_API_PREFIX = "/api" @@ -71,6 +73,14 @@ class GenConfig: # The names of the generators declared ``handEdits: overwrite``: a hand edit to one of # their files is replaced with fresh output (and re-baselined) instead of refused. overwrite_hand_edits: frozenset[str] = frozenset() + # The run's shared manifest session (ADR-0062 decision 1): loaded once, saved once by + # whoever created it. ``None`` makes ``run_gen`` open its own for the one call and save + # it before returning, which is what a programmatic caller always got. + manifest: HashManifest | None = None + # When set, nothing is written: every emitted file is collected into this dict as + # ``{path: content}`` instead. ``verify --codegen`` renders into it and compares the bytes + # with disk in memory, so it creates no temp tree. + sink: dict[str, str] | None = None provided_enum_namespace: str | None = None provided_enum_packages: dict[str, str] = field(default_factory=dict) diff --git a/server/python/src/metaobjects/codegen/generator.py b/server/python/src/metaobjects/codegen/generator.py index 80aa1e0c55..ae363c8999 100644 --- a/server/python/src/metaobjects/codegen/generator.py +++ b/server/python/src/metaobjects/codegen/generator.py @@ -34,11 +34,33 @@ class GenContext: class Generator(Protocol): + """A generator has a ``name`` and a ``generate`` method. + + It may also carry two optional attributes that ADR-0062's whole-run skip reads (both + default as below when absent, so no existing generator changes): + + - ``cacheable: bool`` (default ``True``). ``False`` means the generator reads something + nobody can declare; a run that includes it never skips. + - ``declared_extra_inputs: tuple[str, ...]`` (default ``()``). Project-relative paths + the generator reads beyond the model, the config and the template roots; their + content is part of the run's key. + """ + name: str def generate(self, ctx: GenContext) -> list[EmittedFile]: ... +def generator_cacheable(gen: object) -> bool: + """Whether a run that includes ``gen`` may be skipped when nothing changed.""" + return bool(getattr(gen, "cacheable", True)) + + +def generator_extra_inputs(gen: object) -> tuple[str, ...]: + """The project-relative paths ``gen`` declared as extra inputs.""" + return tuple(getattr(gen, "declared_extra_inputs", ()) or ()) + + def per_entity( fn: Callable[[MetaObject, GenContext], "EmittedFile | list[EmittedFile]"], ) -> Callable[[GenContext], list[EmittedFile]]: diff --git a/server/python/src/metaobjects/codegen/model_key.py b/server/python/src/metaobjects/codegen/model_key.py new file mode 100644 index 0000000000..c857f12de8 --- /dev/null +++ b/server/python/src/metaobjects/codegen/model_key.py @@ -0,0 +1,63 @@ +"""The model half of the skip key (ADR-0062 section 3): a hash tree over the LOADED root. + +Each root-level node (an object, a shared field, a template node) is hashed in its canonical +EFFECTIVE form (:func:`metaobjects.serializer_json.canonical_serialize_effective`: ``extends`` +and overlays applied, attributes in fixed order, no source positions). Node hashes roll up +into one hash per package (sorted ``name:hash`` lines) and one for the model. + +Nothing here reads a metadata source file, so a file that is reformatted, reordered or split +in two without changing what loads does not change the key, and an edit to an abstract parent +changes the key of every node that inherits from it. The tree is exposed whole so a later +per-object or per-package key can reuse the node and package hashes. +""" +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass, field + +from metaobjects.meta.meta_data import MetaData +from metaobjects.serializer_json import canonical_serialize_effective + +from .template_codegen.template_data import package_of + + +@dataclass(frozen=True) +class ModelTree: + #: resolution key -> sha256 of the node's canonical effective form. + nodes: dict[str, str] = field(default_factory=dict) + #: package -> sha256 over its sorted ``resolution-key:node-hash`` lines. + packages: dict[str, str] = field(default_factory=dict) + #: sha256 over the sorted ``package:package-hash`` lines. + model: str = "" + + +def _sha(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def node_hash(node: MetaData) -> str: + """The node's effective canonical form, hashed. The node's own ``package`` attribute is + dropped from the body: the RESOLVED package is part of its resolution key, so moving a + node to another file of the same package (which may or may not restate the package) + does not change it.""" + parsed = json.loads(canonical_serialize_effective(node)) + for body in parsed.values(): + if isinstance(body, dict): + body.pop("package", None) + return _sha(json.dumps(parsed, sort_keys=True, ensure_ascii=False)) + + +def build_model_tree(root: MetaData) -> ModelTree: + # ADR-0039 sanctioned own: top-level scan of the loader ROOT (metadata.root is never + # extended, so own == effective). + nodes: dict[str, str] = {} + by_package: dict[str, list[str]] = {} + for child in root.own_children(): + key = child.resolution_key() + digest = node_hash(child) + nodes[key] = digest + by_package.setdefault(package_of(child), []).append(f"{key}:{digest}") + packages = {p: _sha("\n".join(sorted(lines))) for p, lines in by_package.items()} + model = _sha("\n".join(f"{p}:{h}" for p, h in sorted(packages.items()))) + return ModelTree(nodes, packages, model) diff --git a/server/python/src/metaobjects/codegen/overwrite_policy.py b/server/python/src/metaobjects/codegen/overwrite_policy.py index c83a0e10d5..0c12845998 100644 --- a/server/python/src/metaobjects/codegen/overwrite_policy.py +++ b/server/python/src/metaobjects/codegen/overwrite_policy.py @@ -125,6 +125,52 @@ def _save_hashes(gen_state_dir: str, hashes: dict[str, str]) -> None: fh.write("\n") +class HashManifest: + """The manifest as ONE in-memory session (ADR-0062 decision 1). + + Loaded once, updated in memory by :func:`decide_and_write`, and saved once by + :meth:`save`, and only when an entry was added, changed or removed. The bytes it writes + are exactly what :func:`_save_hashes` has always written (sorted keys, two-space indent, + trailing newline, extra fields of object entries kept), so a run that changes nothing + leaves the committed file, and its timestamp, alone. + """ + + def __init__(self, gen_state_dir: str) -> None: + self.gen_state_dir = gen_state_dir + self.hashes: dict[str, str] = _load_hashes(gen_state_dir) + self.dirty = False + + def get(self, rel_path: str, legacy_rel_path: str | None = None) -> str | None: + recorded = self.hashes.get(rel_path) + if recorded is None and legacy_rel_path is not None: + return self.hashes.get(legacy_rel_path) + return recorded + + def is_pristine(self, rel_path: str, current: str, legacy_rel_path: str | None = None) -> bool: + recorded = self.get(rel_path, legacy_rel_path) + return recorded is not None and recorded == content_hash(current) + + def record( + self, rel_path: str, content: str, legacy_rel_path: str | None = None + ) -> None: + new = content_hash(content) + if self.hashes.get(rel_path) != new: + self.hashes[rel_path] = new + self.dirty = True + # Drop the pre-re-keying spelling in the same save (see `_record`). + if legacy_rel_path is not None and legacy_rel_path != rel_path: + if self.hashes.pop(legacy_rel_path, None) is not None: + self.dirty = True + + def save(self) -> bool: + """Write the manifest if anything changed. Returns whether it wrote.""" + if not self.dirty: + return False + _save_hashes(self.gen_state_dir, self.hashes) + self.dirty = False + return True + + def read_generated_hash( gen_state_dir: str, rel_path: str, legacy_rel_path: str | None = None ) -> str | None: @@ -189,9 +235,14 @@ def decide_and_write( legacy_rel_path: str | None = None, baseline: str = "default", hand_edits: str = "keep", + manifest: HashManifest | None = None, ) -> str: """Decide and perform the write for one generated file. + ``manifest`` is the run's shared :class:`HashManifest` session; the caller saves it + once at the end of the run. Without one, a session is opened for this single call and + saved before returning (what every caller did before ADR-0062). + ``hand_edits="overwrite"`` (the generator's ``handEdits`` setting) replaces a file we recorded writing that was edited since with fresh output, re-records it, and returns :data:`STATUS_OVERWROTE_EDIT` so the caller names it. A file with no record of being @@ -211,12 +262,34 @@ def decide_and_write( next run regenerates over it. What it guarantees is that establishing the baseline writes nothing, which is what lets the regeneration land as its own reviewable diff. """ + session = manifest + if session is None and gen_state_dir is not None: + session = HashManifest(gen_state_dir) + try: + return _decide( + path, content, strategy, session, gen_state_dir, rel_path, legacy_rel_path, + baseline, hand_edits, + ) + finally: + if manifest is None and session is not None: + session.save() + + +def _decide( + path: str, + content: str, + strategy: str, + session: HashManifest | None, + gen_state_dir: str | None, + rel_path: str | None, + legacy_rel_path: str | None, + baseline: str, + hand_edits: str, +) -> str: if not os.path.exists(path): _write(path, content) - if gen_state_dir is not None: - _record( - gen_state_dir, rel_path or os.path.basename(path), content, legacy_rel_path - ) + if session is not None: + session.record(rel_path or os.path.basename(path), content, legacy_rel_path) return "new" if strategy == "skip-existing": @@ -227,41 +300,43 @@ def decide_and_write( # No state to reason from: keep the legacy marker rule rather than refuse # everything, and let the CLI (which always supplies state) carry the guarantee. - if gen_state_dir is None: + if session is None or gen_state_dir is None: if GENERATED_MARKER not in current: return "refused" - _write(path, content) - return "overwrite" + if current != content: + _write(path, content) + return "overwrite" if current != content else "unchanged" key = rel_path or os.path.basename(path) if current == content: - # Nothing to do, but record it: a first run over already-correct output should - # leave the file recognisable as ours next time. - _record(gen_state_dir, key, content, legacy_rel_path) + # Nothing to write, and never a rewrite: it would move the timestamp every build + # tool downstream watches (ADR-0062 decision 2). Record it in memory: a first run + # over already-correct output should leave the file recognisable as ours next time. + session.record(key, content, legacy_rel_path) return "unchanged" - if is_pristine_generated(gen_state_dir, key, current, legacy_rel_path): + if session.is_pristine(key, current, legacy_rel_path): _write(path, content) - _record(gen_state_dir, key, content, legacy_rel_path) + session.record(key, content, legacy_rel_path) return "overwrite" # Edited since we wrote it, and the generator says to discard hand edits. - if hand_edits == "overwrite" and read_generated_hash(gen_state_dir, key, legacy_rel_path) is not None: + if hand_edits == "overwrite" and session.get(key, legacy_rel_path) is not None: _write(path, content) - _record(gen_state_dir, key, content, legacy_rel_path) + session.record(key, content, legacy_rel_path) return STATUS_OVERWROTE_EDIT # Edited, or never recorded. Deliberately does NOT record the current content: # doing so would make the file look pristine next run and turn this into a silent # overwrite one run later. # - # …unless the caller explicitly adopted what is on disk. Placed HERE, at the refusal, + # ...unless the caller explicitly adopted what is on disk. Placed HERE, at the refusal, # rather than earlier in the function: adopting can then only ever convert a refusal # into a recorded baseline, leaving "unchanged" and the pristine overwrite exactly as # they are, so passing it cannot freeze a project's regeneration. if baseline == "adopt": - _record(gen_state_dir, key, current, legacy_rel_path) + session.record(key, current, legacy_rel_path) return "adopted" return "refused" diff --git a/server/python/src/metaobjects/codegen/runner.py b/server/python/src/metaobjects/codegen/runner.py index 5c41fab5c6..9ba312ddcf 100644 --- a/server/python/src/metaobjects/codegen/runner.py +++ b/server/python/src/metaobjects/codegen/runner.py @@ -17,7 +17,12 @@ from .constants import generated_package_init from .generator import GenContext, Generator from .instance_artifacts import is_served_report -from .overwrite_policy import STATUS_OVERWROTE_EDIT, decide_and_write, has_hash_manifest +from .overwrite_policy import ( + STATUS_OVERWROTE_EDIT, + HashManifest, + decide_and_write, + has_hash_manifest, +) _VALID_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") @@ -34,6 +39,8 @@ class RunGenResult: #: Which generator emitted each path (``verify --codegen`` reads it to apply a #: generator's ``handEdits`` to the file). generated_by: dict[str, str] = field(default_factory=dict) + #: How many files were written outside the project root (never recorded). + untracked: int = 0 def _objects(root: MetaData) -> list[MetaObject]: @@ -188,9 +195,38 @@ def run_gen( refused: list[str] = [] adopted: list[str] = [] - untracked = 0 + # ONE manifest session for the whole write loop (ADR-0062 decision 1): loaded here, + # saved once below, and only when an entry changed. A caller that runs several passes + # hands in its own session through ``config.manifest`` and saves it itself. + own_session = config.manifest is None and config.gen_state_dir is not None + session = config.manifest + if session is None and config.gen_state_dir is not None: + session = HashManifest(config.gen_state_dir) + try: + _write_all( + config, emitted, merge_strategy, session, result, refused, adopted + ) + finally: + if own_session and session is not None: + session.save() + return _finish(result, config, emitted, refused, adopted, tracking_hashes, had_manifest) + + +def _write_all( + config: GenConfig, + emitted: dict[str, tuple[str, str]], + merge_strategy: str, + session: HashManifest | None, + result: RunGenResult, + refused: list[str], + adopted: list[str], +) -> None: for full, (content, by) in emitted.items(): result.generated_by[full] = by + if config.sink is not None: + config.sink[full] = content + result.files.append((full, "new")) + continue # The out-dir-relative name: what the manifest used to be keyed by, and still # what a refusal is REPORTED as (it is the name the reader sees in `--out`). rel = os.path.relpath(full, config.out_dir) @@ -217,7 +253,7 @@ def run_gen( # manifest-less rule a run with no project gets — written, never recorded. outside = bool(config.project_root) and (key.startswith("..") or os.path.isabs(key)) if outside: - untracked += 1 + result.untracked += 1 status = decide_and_write( full, content, @@ -227,6 +263,7 @@ def run_gen( legacy_rel_path=rel if key != rel else None, baseline=config.baseline, hand_edits="overwrite" if by in config.overwrite_hand_edits else "keep", + manifest=None if outside else session, ) result.files.append((full, status)) if status == STATUS_OVERWROTE_EDIT: @@ -238,6 +275,17 @@ def run_gen( elif status == "adopted": adopted.append(rel) + +def _finish( + result: RunGenResult, + config: GenConfig, + emitted: dict[str, tuple[str, str]], + refused: list[str], + adopted: list[str], + tracking_hashes: bool, + had_manifest: bool, +) -> RunGenResult: + untracked = result.untracked if untracked: result.warnings.append( f"{untracked} generated file(s) were written outside the project root and are " diff --git a/server/python/src/metaobjects/codegen/skip.py b/server/python/src/metaobjects/codegen/skip.py new file mode 100644 index 0000000000..5c13dc8c72 --- /dev/null +++ b/server/python/src/metaobjects/codegen/skip.py @@ -0,0 +1,428 @@ +"""Whole-run codegen skip (ADR-0062). + +``gen`` computes ONE fingerprint of every input that can change what it writes, before it +loads any metadata or constructs any generator, and compares it with the one the last +successful run stored in ``/.fingerprint-python.json``. A match, with every +file the manifest records still on disk, skips the run. + +The key may be wrong only in the safe direction: anything this module cannot prove +unchanged is reported as changed (``None`` from an input builder means "cannot prove", and +the caller then runs in full). + +The fingerprint is built from small named entries (:class:`InputEntry`: a kind, a name and a +content hash) folded into one key by :func:`fold`, so a later per-object key can reuse the +same entries for a subset of the inputs. Its bytes are internal to this port and are never +compared with another port's. +""" +from __future__ import annotations + +import hashlib +import json +import os +from dataclasses import dataclass +from importlib import metadata as importlib_metadata +from importlib import util as importlib_util +from pathlib import Path +from typing import Iterable + +from .overwrite_policy import HASHES_FILE, content_hash + +#: Bump when the fingerprint's own recipe changes: every stored fingerprint then misses. +FINGERPRINT_FORMAT = 2 + +#: Where this port keeps its fingerprint, beside the (committed) manifest and never +#: committed itself (``.gen-state/*`` is ignored except ``.hashes.json``). +FINGERPRINT_FILE = ".fingerprint-python.json" + +#: The hash of an input that does not exist. A file that appears or disappears changes it. +ABSENT = "absent" + +_SKIPPED_DIRS = {"__pycache__", ".git", ".venv", "node_modules", ".mypy_cache", ".ruff_cache"} +_SKIPPED_SUFFIXES = {".pyc", ".pyo"} + +KIND_TOOL = "tool" +KIND_ENGINE = "engine" +KIND_CONFIG = "config" +KIND_MODEL = "model" +KIND_FLAG = "flag" +KIND_GENERATOR = "generator" +KIND_TEMPLATES = "templates" +KIND_SOURCE = "source" +KIND_EXTRA = "extra" + + +@dataclass(frozen=True) +class InputEntry: + """One named input of the run: what kind it is, its name, and its content hash.""" + + kind: str + name: str + sha256: str + + +def fold(entries: Iterable[InputEntry]) -> str: + """The one key: a SHA-256 over the sorted entries. Order of arrival is irrelevant.""" + lines = sorted(f"{e.kind}\0{e.name}\0{e.sha256}" for e in entries) + return hashlib.sha256("\n".join(lines).encode("utf-8")).hexdigest() + + +def _sha(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def hash_file(path: Path) -> str: + """SHA-256 of a file's bytes, or :data:`ABSENT`. Timestamps are never read.""" + try: + return _sha(path.read_bytes()) + except OSError: + return ABSENT + + +def _tree_files(root: Path) -> list[Path]: + files: list[Path] = [] + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted(d for d in dirnames if d not in _SKIPPED_DIRS) + for name in sorted(filenames): + if Path(name).suffix in _SKIPPED_SUFFIXES: + continue + files.append(Path(dirpath, name)) + return files + + +def hash_tree(root: Path) -> str: + """One hash over every file under ``root`` (relative path and content), or + :data:`ABSENT`. Adding, removing, renaming or editing any file changes it.""" + if not root.exists(): + return ABSENT + if root.is_file(): + return hash_file(root) + h = hashlib.sha256() + for f in _tree_files(root): + h.update(f.relative_to(root).as_posix().encode("utf-8")) + h.update(b"\0") + h.update(hash_file(f).encode("ascii")) + h.update(b"\n") + return h.hexdigest() + + +# --- identity of the engine and of generators ------------------------------------------- + + +def _installed_version() -> str: + try: + return importlib_metadata.version("metaobjects") + except importlib_metadata.PackageNotFoundError: + return "0.0.0" + + +def engine_identity() -> str: + """A content hash of the engine's built code (the generators, their templates and + helpers all live in this package), so a linked or locally built engine changes the key + with its content and an installed one changes it with its release.""" + return f"content:{hash_tree(Path(__file__).resolve().parent.parent)}" + + +def engine_entries() -> list[InputEntry]: + return [ + InputEntry(KIND_TOOL, "fingerprint-format", str(FINGERPRINT_FORMAT)), + InputEntry(KIND_TOOL, "engine-version", _installed_version()), + InputEntry(KIND_ENGINE, "metaobjects", engine_identity()), + ] + + +def module_source_entries(spec: str, root: Path) -> list[InputEntry] | None: + """The identity of the code behind a ``module:symbol`` spec (an owned generator, a + provider, a requirement-tests hook), WITHOUT importing it. + + Found under ``root`` first (the config directory: a ``module.py`` or a package directory) + and then on the import path. A module under the project is hashed whole, its top-level + package included, because an owned generator imports its ejected runtime siblings. An + installed distribution is identified by its version. ``None`` when the module cannot be + found: the run then cannot be proven unchanged. + """ + module_name = spec.partition(":")[0] + top = module_name.split(".")[0] + if not top: + return None + for candidate in (root / f"{top}.py", root / top): + if candidate.exists(): + return [InputEntry(KIND_SOURCE, top, hash_tree(candidate))] + try: + found = importlib_util.find_spec(top) + except (ImportError, ValueError): + return None + if found is None or not found.origin or found.origin in ("built-in", "frozen"): + return None + origin = Path(found.origin).resolve() + package_dir = origin.parent if origin.name == "__init__.py" else origin + return [InputEntry(KIND_SOURCE, top, hash_tree(package_dir))] + + +def extras_entries(project_root: Path, paths: Iterable[str]) -> list[InputEntry]: + """The content of every declared extra input (project-relative paths; a directory is + hashed whole). A path that does not exist hashes as :data:`ABSENT`.""" + return [ + InputEntry(KIND_EXTRA, rel, hash_tree(project_root / rel)) + for rel in sorted(set(paths)) + ] + + +# --- the stored fingerprint ------------------------------------------------------------- + + +def fingerprint_path(gen_state_dir: str) -> str: + return os.path.join(gen_state_dir, FINGERPRINT_FILE) + + +@dataclass(frozen=True) +class StoredFingerprint: + key: str + #: Project-relative paths the last run's generators declared as extra inputs. Kept here + #: because the check runs before any generator exists and must hash them. + extras: tuple[str, ...] + #: Amendment A: every manifest-recorded path (project-relative, as the manifest keys it) + #: mapped to the sha256 of the bytes on disk when the run finished. + outputs: dict[str, str] + #: Every other path the run emitted, which the manifest does not record (a file outside + #: the project root, or one written without a record): project-relative when inside the + #: project, absolute otherwise. A skip needs each to exist. + untracked: tuple[str, ...] = () + + +def read_stored(gen_state_dir: str) -> StoredFingerprint | None: + try: + with open(fingerprint_path(gen_state_dir), encoding="utf-8") as fh: + raw = json.load(fh) + except (OSError, ValueError): + return None + if ( + not isinstance(raw, dict) + or raw.get("format") != FINGERPRINT_FORMAT + or not isinstance(raw.get("fingerprint"), str) + ): + return None + extras = raw.get("extras", []) + if not isinstance(extras, list) or not all(isinstance(x, str) for x in extras): + return None + outputs = raw.get("outputs") + if not isinstance(outputs, dict) or not all( + isinstance(k, str) and isinstance(v, str) for k, v in outputs.items() + ): + return None + untracked = raw.get("untracked", []) + if not isinstance(untracked, list) or not all(isinstance(x, str) for x in untracked): + return None + return StoredFingerprint(raw["fingerprint"], tuple(extras), dict(outputs), tuple(untracked)) + + +def write_stored( + gen_state_dir: str, + key: str, + extras: Iterable[str], + outputs: dict[str, str], + untracked: Iterable[str] = (), +) -> None: + os.makedirs(gen_state_dir, exist_ok=True) + payload = { + "format": FINGERPRINT_FORMAT, + "fingerprint": key, + "extras": sorted(set(extras)), + "outputs": dict(sorted(outputs.items())), + "untracked": sorted(set(untracked)), + } + with open(fingerprint_path(gen_state_dir), "w", encoding="utf-8") as fh: + json.dump(payload, fh, indent=2) + fh.write("\n") + + +def delete_stored(gen_state_dir: str) -> None: + try: + os.remove(fingerprint_path(gen_state_dir)) + except OSError: + pass + + +def current_key( + entries: list[InputEntry], project_root: Path, stored: StoredFingerprint | None +) -> str: + """The key the inputs fold to, with the stored run's declared extras hashed in.""" + extras = extras_entries(project_root, stored.extras) if stored else [] + return fold([*entries, *extras]) + + +# --- the manifest's files --------------------------------------------------------------- + + +def _manifest_records(gen_state_dir: str) -> dict[str, str] | None: + """key -> recorded hash, or ``None`` when there is no readable manifest.""" + try: + with open(os.path.join(gen_state_dir, HASHES_FILE), encoding="utf-8") as fh: + raw = json.load(fh) + except (OSError, ValueError): + return None + if not isinstance(raw, dict): + return None + records: dict[str, str] = {} + for key, value in raw.items(): + if isinstance(value, str): + records[key] = value + elif isinstance(value, dict) and isinstance(value.get("hash"), str): + records[key] = value["hash"] + return records + + +def _locate(key: str, project_root: Path, out_dirs: Iterable[str]) -> Path | None: + """The file a manifest key names: project-relative, else (a pre-re-keying entry) + relative to one of the output directories.""" + candidate = project_root / key + if candidate.is_file(): + return candidate + for out in out_dirs: + legacy = Path(out) / key + if legacy.is_file(): + return legacy + return None + + +def output_hashes( + gen_state_dir: str, project_root: Path, out_dirs: Iterable[str] +) -> dict[str, str] | None: + """Every manifest-recorded path mapped to the sha256 of the bytes on disk now, or + ``None`` when the manifest is unreadable or any recorded file is missing (a run that + left a recorded file missing stores no key; a skip then never matches).""" + records = _manifest_records(gen_state_dir) + if records is None: + return None + outs = list(out_dirs) + hashes: dict[str, str] = {} + for key in records: + found = _locate(key, project_root, outs) + if found is None: + return None + try: + hashes[key] = _sha(found.read_bytes()) + except OSError: + return None + return hashes + + +def untracked_outputs( + gen_state_dir: str, project_root: Path, out_dirs: Iterable[str], emitted: Iterable[str] +) -> list[str]: + """Every emitted path the manifest does not record, project-relative when inside the + project and absolute otherwise.""" + outs = list(out_dirs) + root = project_root.resolve() + recorded: set[str] = set() + for key in _manifest_records(gen_state_dir) or {}: + found = _locate(key, project_root, outs) + if found is not None: + recorded.add(os.path.realpath(found)) + result: list[str] = [] + for path in emitted: + real = os.path.realpath(path) + if real in recorded: + continue + rel = os.path.relpath(real, root) + result.append(real if rel.startswith("..") or os.path.isabs(rel) else rel) + return sorted(set(result)) + + +def untracked_exist(stored: StoredFingerprint, project_root: Path) -> bool: + """True when every path the stored run emitted outside the manifest still exists.""" + return all((project_root / p).is_file() for p in stored.untracked) + + +def outputs_unchanged( + stored: StoredFingerprint, gen_state_dir: str, project_root: Path, out_dirs: Iterable[str] +) -> bool: + """Amendment A: every manifest-recorded file exists and still hashes to the value the + last run left, and every path emitted outside the manifest still exists. A missing entry + on either side is a mismatch.""" + return ( + output_hashes(gen_state_dir, project_root, out_dirs) == stored.outputs + and untracked_exist(stored, project_root) + ) + + +def manifest_files_exist( + gen_state_dir: str, project_root: Path, out_dirs: Iterable[str] +) -> bool: + """True when every file the manifest records still exists. A missing or unreadable + manifest is not proof of anything, so it reads as False.""" + records = _manifest_records(gen_state_dir) + if records is None: + return False + outs = list(out_dirs) + return all(_locate(key, project_root, outs) is not None for key in records) + + +def manifest_files_match( + gen_state_dir: str, project_root: Path, out_dirs: Iterable[str] +) -> bool: + """True when every file the manifest records still hashes to its recorded entry.""" + records = _manifest_records(gen_state_dir) + if records is None: + return False + outs = list(out_dirs) + for key, recorded in records.items(): + found = _locate(key, project_root, outs) + if found is None: + return False + try: + text = found.read_bytes().decode("utf-8") + except (OSError, UnicodeDecodeError): + return False + if content_hash(text) != recorded: + return False + return True + + +def ci_environment(environ: dict[str, str] | None = None) -> bool: + """The ``CI`` variable is set to anything but empty, ``0`` or ``false``.""" + value = (environ if environ is not None else os.environ).get("CI", "") + return value.strip().lower() not in ("", "0", "false") + + +@dataclass +class SkipRunInfo: + """What a run learned while it resolved its generators, for the fingerprint it stores: + whether every generator is cacheable, and the extra inputs they declared (with the + content they had BEFORE the run wrote anything).""" + + cacheable: bool = True + extras: set[str] | None = None + extra_entries: list[InputEntry] | None = None + + def __post_init__(self) -> None: + if self.extras is None: + self.extras = set() + if self.extra_entries is None: + self.extra_entries = [] + + +__all__ = [ + "ABSENT", + "FINGERPRINT_FILE", + "FINGERPRINT_FORMAT", + "InputEntry", + "SkipRunInfo", + "StoredFingerprint", + "ci_environment", + "current_key", + "delete_stored", + "engine_entries", + "engine_identity", + "extras_entries", + "fingerprint_path", + "fold", + "hash_file", + "hash_tree", + "manifest_files_exist", + "output_hashes", + "outputs_unchanged", + "manifest_files_match", + "module_source_entries", + "read_stored", + "write_stored", +] diff --git a/server/python/tests/codegen/test_cli_verify_requirements.py b/server/python/tests/codegen/test_cli_verify_requirements.py index c8f3dec2a7..b5d6b57f07 100644 --- a/server/python/tests/codegen/test_cli_verify_requirements.py +++ b/server/python/tests/codegen/test_cli_verify_requirements.py @@ -18,6 +18,9 @@ import pytest +import contextlib +import io + from metaobjects import cli from metaobjects.cli import main from tests.codegen.gen_suite import GEN_SUITE @@ -57,7 +60,9 @@ def _meta_dir(tmp_path: Path, requirements: list[dict[str, Any]]) -> str: def _verify(tmp_path: Path, meta_dir: str, *extra: str) -> int: out = tmp_path / "out" - assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(out)])) == 0 + # gen's own report is not what this compares: a repeat run reports files as unchanged. + with contextlib.redirect_stdout(io.StringIO()): + assert main(as_config(["gen", "--generators", GEN_SUITE, meta_dir, "--out", str(out)])) == 0 return main(as_config(["verify", "--codegen", "--generators", GEN_SUITE, meta_dir, "--out", str(out), *extra])) diff --git a/server/python/tests/codegen/test_gen_unchanged.py b/server/python/tests/codegen/test_gen_unchanged.py new file mode 100644 index 0000000000..9ac3ba70ad --- /dev/null +++ b/server/python/tests/codegen/test_gen_unchanged.py @@ -0,0 +1,231 @@ +"""ADR-0062 decisions 1 and 2: the manifest is written once per run and only when an entry +changed; a file whose bytes already match is never rewritten and reports as unchanged.""" +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +from metaobjects import codegen +from metaobjects.cli import main +from metaobjects.codegen import overwrite_policy + +_DOC = { + "metadata.root": { + "package": "app", + "children": [ + {"object.entity": {"name": "Order", "children": [ + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ]}}, + {"object.entity": {"name": "Item", "children": [ + {"field.long": {"name": "id"}}, + {"identity.primary": {"name": "pk", "@fields": ["id"]}}, + ]}}, + ], + } +} + + +def _project(tmp_path: Path) -> Path: + (tmp_path / "metaobjects").mkdir() + (tmp_path / "metaobjects" / "meta.app.json").write_text(json.dumps(_DOC)) + (tmp_path / "metaobjects.config.yaml").write_text( + "metadata: metaobjects\ntargets:\n app:\n outDir: gen\n generators: [entity]\n" + ) + return tmp_path + + +def test_unchanged_files_keep_mtime_manifest_untouched_and_report_unchanged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + root = _project(tmp_path) + monkeypatch.chdir(root) + assert main(["gen"]) == 0 + files = [f for f in (root / "gen").rglob("*.py")] + assert files + manifest = root / ".metaobjects" / ".gen-state" / ".hashes.json" + before = manifest.read_bytes() + for f in [*files, manifest]: + os.utime(f, (1, 1)) + capsys.readouterr() + + assert main(["gen", "--force"]) == 0 + out = capsys.readouterr().out + + assert all(f.stat().st_mtime == 1 for f in files), "an identical file was rewritten" + assert manifest.stat().st_mtime == 1, "an unchanged manifest was rewritten" + assert manifest.read_bytes() == before + assert "wrote 0 file(s)" in out and f"{len(files)} unchanged" in out + assert not [ln for ln in out.splitlines() if ln.startswith(str(root / "gen"))] + + +def test_manifest_is_saved_once_per_run_and_only_when_it_changed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + root = _project(tmp_path) + monkeypatch.chdir(root) + saves: list[int] = [] + real = overwrite_policy._save_hashes + + def counting(gen_state_dir: str, hashes: dict[str, str]) -> None: + saves.append(len(hashes)) + real(gen_state_dir, hashes) + + monkeypatch.setattr(overwrite_policy, "_save_hashes", counting) + assert main(["gen"]) == 0 + assert len(saves) == 1, "first run: one save for every written file" + saves.clear() + assert main(["gen", "--force"]) == 0 + assert saves == [], "a run that changes nothing saves nothing" + + +def test_manifest_bytes_keep_sorted_keys_and_extra_fields(tmp_path: Path) -> None: + state = tmp_path / "state" + state.mkdir() + (state / ".hashes.json").write_text( + json.dumps({"b.py": {"hash": "old", "owner": "jvm"}}, indent=2) + "\n" + ) + session = overwrite_policy.HashManifest(str(state)) + session.record("b.py", "new", None) + session.record("a.py", "x", None) + assert session.save() is True + raw = json.loads((state / ".hashes.json").read_text()) + assert list(raw) == ["a.py", "b.py"] + assert raw["b.py"]["owner"] == "jvm" and raw["b.py"]["hash"] == overwrite_policy.content_hash("new") + assert (state / ".hashes.json").read_text().endswith("}\n") + assert session.save() is False + + +def test_decide_and_write_without_a_state_dir_does_not_rewrite_identical_bytes( + tmp_path: Path, +) -> None: + f = tmp_path / "x.py" + f.write_text(codegen.constants.GENERATED_MARKER + "\nbody\n") + os.utime(f, (1, 1)) + status = overwrite_policy.decide_and_write(str(f), f.read_text()) + assert status == "unchanged" and f.stat().st_mtime == 1 + + +def test_non_prompt_targets_rewrite_nothing_and_save_no_manifest_when_unchanged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Drive-wear regression: two non-prompt targets, several generators each. A forced run + over unchanged output rewrites no file (every mtime stays) and saves no manifest; the + first run saves the manifest exactly once, however many files it writes.""" + root = tmp_path + (root / "metaobjects").mkdir() + (root / "metaobjects" / "meta.app.json").write_text(json.dumps(_DOC)) + (root / "metaobjects.config.yaml").write_text( + "metadata: metaobjects\n" + "targets:\n" + " models:\n outDir: gen/models\n generators: [entity, names]\n" + " api:\n outDir: gen/api\n generators: [routes, filter-allowlist]\n" + ) + monkeypatch.chdir(root) + saves: list[int] = [] + real = overwrite_policy._save_hashes + + def counting(gen_state_dir: str, hashes: dict[str, str]) -> None: + saves.append(len(hashes)) + real(gen_state_dir, hashes) + + monkeypatch.setattr(overwrite_policy, "_save_hashes", counting) + assert main(["gen"]) == 0 + files = [f for f in (root / "gen").rglob("*") if f.is_file()] + assert len(files) > 4 and {f.relative_to(root).parts[1] for f in files} == {"models", "api"} + assert len(saves) == 1, f"first run saved the manifest {len(saves)} times" + manifest = root / ".metaobjects" / ".gen-state" / ".hashes.json" + for f in [*files, manifest]: + os.utime(f, (1, 1)) + saves.clear() + capsys.readouterr() + + assert main(["gen", "--force"]) == 0 + rewritten = [str(f) for f in files if f.stat().st_mtime != 1] + assert rewritten == [], f"unchanged files were rewritten: {rewritten}" + assert saves == [] and manifest.stat().st_mtime == 1 + assert "wrote 0 file(s)" in capsys.readouterr().out + + +# --- item 9: verify --codegen renders in memory and creates no temp tree ---------------------- + + +def test_verify_codegen_creates_no_temp_files_or_directories( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + import tempfile + + (tmp_path / "proj").mkdir() + root = _project(tmp_path / "proj") + monkeypatch.chdir(root) + assert main(["gen"]) == 0 + + scratch = tmp_path / "scratch-tmp" + scratch.mkdir() + monkeypatch.setenv("TMPDIR", str(scratch)) + monkeypatch.setattr(tempfile, "tempdir", None) + + def forbidden(*_a: object, **_k: object) -> None: + raise AssertionError("verify --codegen created a temp file or directory") + + for name in ("TemporaryDirectory", "mkdtemp", "mkstemp", "NamedTemporaryFile", + "TemporaryFile", "SpooledTemporaryFile"): + monkeypatch.setattr(tempfile, name, forbidden) + + assert main(["verify", "--codegen", "--full"]) == 0 # renders, finds no drift + target = next((root / "gen").glob("Order*.py")) + target.write_text(target.read_text() + "# edited\n") + assert main(["verify", "--codegen", "--full"]) == 1 # renders, reports the drift + assert "drifted" in capsys.readouterr().err + assert list(scratch.iterdir()) == [] + # No rendered tree anywhere under the project either: only what gen itself wrote. + assert not [p for p in root.rglob("*") if "verify" in p.name.lower()] + + +def test_a_refused_orphan_stores_no_skip_key( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + root = _project(tmp_path) + monkeypatch.chdir(root) + assert main(["gen"]) == 0 + key = root / ".metaobjects" / ".gen-state" / ".fingerprint-python.json" + assert key.exists() + # Hand-edit Item's output, then drop Item from the model: it is an orphan the sweep + # must refuse to delete (ADR-0062 counts a refusal as a failed run). + orphan = next((root / "gen").glob("Item*.py")) + orphan.write_text(orphan.read_text() + "# mine\n") + doc = json.loads(json.dumps(_DOC)) + doc["metadata.root"]["children"] = doc["metadata.root"]["children"][:1] + (root / "metaobjects" / "meta.app.json").write_text(json.dumps(doc)) + capsys.readouterr() + + assert main(["gen"]) == 0 + assert "NOT deleted" in capsys.readouterr().out + assert not key.exists(), "a run whose orphan sweep refused stored a skip key" + assert main(["gen"]) == 0 + assert "nothing changed" not in capsys.readouterr().out + + +def test_a_deleted_output_outside_the_project_makes_gen_render_again( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + root = _project(tmp_path / "proj") if (tmp_path / "proj").mkdir() is None else tmp_path + (root / "metaobjects.config.yaml").write_text( + "metadata: metaobjects\ntargets:\n" + " app:\n outDir: gen\n generators: [entity]\n" + " other:\n outDir: ../elsewhere\n generators: [entity]\n" + ) + monkeypatch.chdir(root) + assert main(["gen"]) == 0 + assert list((root / "gen").glob("Order*.py")), "the in-project target must record a manifest" + outside = next((tmp_path / "elsewhere").glob("Order*.py")) + outside.unlink() + capsys.readouterr() + + assert main(["gen"]) == 0 + + assert "nothing changed" not in capsys.readouterr().out + assert outside.exists(), "gen skipped and left a deleted output unrestored" diff --git a/server/python/tests/test_gen_skip_conformance.py b/server/python/tests/test_gen_skip_conformance.py new file mode 100644 index 0000000000..4902939483 --- /dev/null +++ b/server/python/tests/test_gen_skip_conformance.py @@ -0,0 +1,350 @@ +"""ADR-0062 — the shared table of skip cases (``fixtures/codegen-skip-conformance/cases.json``). + +Every case: run ``gen`` once (it must write and store a fingerprint), apply the change, then +ask what the next ``gen`` does and what a LOCAL ``verify --codegen`` may do. A case id this +runner does not know FAILS, so a case added to the shared table reaches this port. +""" +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Callable + +import pytest + +from metaobjects import cli +from metaobjects.codegen import skip +from metaobjects.cli import main + +CASES = json.loads( + (Path(__file__).parents[3] / "fixtures" / "codegen-skip-conformance" / "cases.json").read_text() +)["cases"] + +_ENTITY = { + "metadata.root": { + "package": "skip", + "children": [ + {"object.entity": {"name": "{name}", "children": [ + {"field.long": {"name": "id"}}, + {"field.string": {"name": "title"}}, + ]}} + ], + } +} + +_OWNED = '''\ +from pathlib import Path +from metaobjects.codegen.generator import EmittedFile + + +class Owned: + name = "owned" + declared_extra_inputs = ("extra/data.txt",) + + def generate(self, ctx): + data = Path("extra/data.txt") + return [EmittedFile("owned.txt", "owned\\n")] + + +def make(): + return Owned() +''' + +_UNCACHEABLE = '''\ +from metaobjects.codegen.generator import EmittedFile + + +class Volatile: + name = "volatile" + cacheable = False + + def generate(self, ctx): + return [EmittedFile("volatile.txt", "v\\n")] + + +def make(): + return Volatile() +''' + + +def _book_json(base_extra: bool = False, with_book: bool = True) -> str: + """meta.b.json: an abstract parent (Base) and, optionally, a child that extends it.""" + base_fields = [{"field.long": {"name": "id"}}] + if base_extra: + base_fields.append({"field.string": {"name": "note"}}) + children: list[object] = [ + {"object.entity": {"name": "Base", "abstract": True, "children": base_fields}} + ] + if with_book: + children.append({"object.entity": {"name": "Book", "extends": "Base", "children": [ + {"field.string": {"name": "title"}}]}}) + return json.dumps({"metadata.root": {"package": "skip", "children": children}}, indent=2) + "\n" + + +def _entity_json(name: str, extra_attr: str | None = None) -> str: + doc = json.loads(json.dumps(_ENTITY).replace("{name}", name)) + if extra_attr: + doc["metadata.root"]["children"][0]["object.entity"]["@description"] = extra_attr + return json.dumps(doc, indent=2) + "\n" + + +@dataclass +class Project: + root: Path + uncacheable: bool = False + + @property + def config(self) -> Path: + return self.root / "metaobjects.config.yaml" + + @property + def state(self) -> Path: + return self.root / ".metaobjects" / ".gen-state" + + def write_config(self, generators: str = "[entity, owned:make]") -> None: + gens = generators + if self.uncacheable: + gens = "[entity, owned:make, volatile:make]" + self.config.write_text( + "metadata: metaobjects\ntemplates: prompts\n" + f"targets:\n app:\n outDir: generated\n generators: {gens}\n", + encoding="utf-8", + ) + + +def _project(tmp_path: Path, uncacheable: bool = False) -> Project: + p = Project(tmp_path, uncacheable) + (tmp_path / "metaobjects").mkdir() + (tmp_path / "metaobjects" / "meta.a.json").write_text(_entity_json("Author")) + (tmp_path / "metaobjects" / "meta.b.json").write_text(_book_json()) + (tmp_path / "prompts").mkdir() + (tmp_path / "prompts" / "p.txt").write_text("hello\n") + (tmp_path / "extra").mkdir() + (tmp_path / "extra" / "data.txt").write_text("1\n") + (tmp_path / "README.md").write_text("readme\n") + (tmp_path / "owned.py").write_text(_OWNED) + (tmp_path / "volatile.py").write_text(_UNCACHEABLE) + (tmp_path / ".metaobjects").mkdir() + (tmp_path / ".metaobjects" / "config.json").write_text('{"schema_version": 1, "sources": [{"path": "metaobjects"}]}\n') + p.write_config() + return p + + +class Harness: + def __init__(self, project: Project, monkeypatch: pytest.MonkeyPatch, capsys) -> None: + self.project = project + self.mp = monkeypatch + self.capsys = capsys + self.loads = 0 + self.renders = 0 + self.out = "" + self.err = "" + real_load = cli._load_root_from_collection + real_run = cli._run_gen_targets + + def counting_load(*a, **k): + self.loads += 1 + return real_load(*a, **k) + + def counting_run(*a, **k): + self.renders += 1 + return real_run(*a, **k) + + monkeypatch.setattr(cli, "_load_root_from_collection", counting_load) + monkeypatch.setattr(cli, "_run_gen_targets", counting_run) + monkeypatch.chdir(project.root) + monkeypatch.delenv("CI", raising=False) + + def gen(self, *flags: str) -> tuple[int, bool]: + """Run gen; return (exit code, whether it skipped without loading anything).""" + self.loads = 0 + self.renders = 0 + self.capsys.readouterr() + rc = main(["gen", "--config", str(self.project.config), *flags]) + cap = self.capsys.readouterr() + out = self.out = cap.out + self.err = cap.err + skipped = "nothing changed" in out + if skipped: + assert self.renders == 0, "a skipped run renders nothing" + return rc, skipped + + def verify(self, *flags: str) -> tuple[int, bool]: + """Run verify --codegen; return (exit code, whether it rendered).""" + self.renders = 0 + rc = main(["verify", "--codegen", "--config", str(self.project.config), *flags]) + self.capsys.readouterr() + return rc, self.renders > 0 + + +def _touch_same(p: Project, h: Harness) -> None: + f = p.root / "metaobjects" / "meta.a.json" + f.write_text(f.read_text()) + os.utime(f, (1, 1)) + + +def _reformat(p: Project, h: Harness) -> None: + f = p.root / "metaobjects" / "meta.a.json" + doc = json.loads(f.read_text()) + entity = doc["metadata.root"]["children"][0]["object.entity"] + # Different whitespace and key order, same content (children keep their authored order). + f.write_text(json.dumps(doc, separators=(",", ":"), sort_keys=True)) + del entity + + +def _move(p: Project, h: Harness) -> None: + (p.root / "metaobjects" / "meta.b.json").write_text(_book_json(with_book=False)) + book = {"metadata.root": {"package": "skip", "children": [ + {"object.entity": {"name": "Book", "extends": "Base", "children": [ + {"field.string": {"name": "title"}}]}}]}} + (p.root / "metaobjects" / "meta.c.json").write_text(json.dumps(book)) + + +def _edit_owned(p: Project, h: Harness) -> None: + f = p.root / "owned.py" + f.write_text(f.read_text() + "\n# edited\n") + + +def _delete_generated(p: Project, h: Harness) -> None: + (p.root / "generated" / "owned.txt").unlink() + + +def _edit_generated(p: Project, h: Harness) -> None: + f = p.root / "generated" / "owned.txt" + f.write_text(f.read_text() + "hand edit\n") + + +def _hand_edit_kept(p: Project, h: Harness) -> None: + # Python has no three-way merge: a hand edit is REFUSED, the run exits 1 and stores no + # key (a refusal is a failed gate), so the "kept" run can never be followed by a skip. + # The follow-up gen is therefore asserted to re-run and refuse again, not to skip. + _edit_generated(p, h) + + +def _failed_run(p: Project, h: Harness) -> None: + good = (p.root / "metaobjects" / "meta.a.json").read_text() + (p.root / "metaobjects" / "meta.a.json").write_text("{ not json") + rc, _ = h.gen() + assert rc != 0 + (p.root / "metaobjects" / "meta.a.json").write_text(good) + + +def _write(rel: str, text: str) -> Callable[[Project, Harness], None]: + def go(p: Project, h: Harness) -> None: + f = p.root / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(text) + + return go + + +def _append(rel: str, text: str) -> Callable[[Project, Harness], None]: + def go(p: Project, h: Harness) -> None: + f = p.root / rel + f.write_text(f.read_text() + text) + + return go + + +def _engine_changed(p: Project, h: Harness) -> None: + h.mp.setattr(skip, "engine_identity", lambda: "another-engine") + + +#: id -> (setup, extra gen flags). A flag-only case has a no-op setup. +_NOOP = lambda p, h: None # noqa: E731 +HANDLERS: dict[str, tuple[Callable[[Project, Harness], None], tuple[str, ...]]] = { + "no-change": (_NOOP, ()), + "metadata-touched": (_touch_same, ()), + "unrelated-file-edited": (_append("README.md", "more\n"), ()), + "metadata-reformatted": (_reformat, ()), + "metadata-moved": (_move, ()), + "parent-edited": (_write("metaobjects/meta.b.json", _book_json(base_extra=True)), ()), + "metadata-edited": (_write("metaobjects/meta.a.json", _entity_json("Author", "edited")), ()), + "metadata-added": (_write("metaobjects/meta.c.json", _entity_json("Chapter")), ()), + "metadata-removed": (lambda p, h: (p.root / "metaobjects" / "meta.b.json").unlink(), ()), + "config-edited": (lambda p, h: p.write_config("[entity, owned:make, names]"), ()), + "project-config-edited": ( + _write(".metaobjects/config.json", '{ "schema_version": 1, "sources": [{"path": "metaobjects"}] }\n'), ()), + "template-edited": (_write("prompts/p.txt", "changed\n"), ()), + "template-added": (_write("prompts/new.txt", "new\n"), ()), + "owned-generator-edited": (_edit_owned, ()), + "engine-changed": (_engine_changed, ()), + "selection-changed": (_NOOP, ("--generators", "entity")), + "declared-extra-edited": (_write("extra/data.txt", "2\n"), ()), + "uncacheable-generator": (_NOOP, ()), + "generated-file-deleted": (_delete_generated, ()), + "generated-file-edited": (_edit_generated, ()), + "hand-edit-kept": (_hand_edit_kept, ()), + "fingerprint-missing": (lambda p, h: skip.delete_stored(str(p.state)), ()), + "force": (_NOOP, ("--force",)), + "ci": (_NOOP, ()), + "failed-run": (_failed_run, ()), +} + + +def test_every_shared_case_has_a_handler() -> None: + ids = {c["id"] for c in CASES} + assert ids - set(HANDLERS) == set(), "unknown case id(s): add a handler for them" + assert set(HANDLERS) - ids == set(), "handler for a case id the shared table dropped" + + +#: Cases whose "gen keeps the edit" outcome is a refusal in Python (no merge engine). +PYTHON_REFUSES_HAND_EDIT = {"hand-edit-kept"} + + +@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES]) +def test_case(case: dict[str, str], tmp_path: Path, monkeypatch, capsys) -> None: + assert case["id"] in HANDLERS, f"unknown case id {case['id']!r}" + setup, flags = HANDLERS[case["id"]] + project = _project(tmp_path, uncacheable=case["id"] == "uncacheable-generator") + h = Harness(project, monkeypatch, capsys) + + rc, skipped = h.gen() + assert rc == 0 and not skipped, h.out + h.err + assert (project.state / skip.FINGERPRINT_FILE).exists() == (case["id"] != "uncacheable-generator") + + setup(project, h) + if case["id"] == "ci": + monkeypatch.setenv("CI", "true") + + # verify first: it never writes or deletes anything, so gen's decision is unaffected. + verify_flags = {"selection-changed": ("--generators", "entity"), "force": ("--full",)} + v_rc, rendered = h.verify(*verify_flags.get(case["id"], ())) + if case["verify"] == "must-render": + assert rendered, "verify must render and compare" + else: + assert not rendered and v_rc == 0, "verify may answer from the fingerprint" + + monkeypatch.delenv("CI", raising=False) + rc, skipped = h.gen(*flags) + if case["id"] in PYTHON_REFUSES_HAND_EDIT: + assert not skipped and rc == 1, "a refused hand edit must keep failing, never skip" + elif case["gen"] == "skip": + assert skipped and rc == 0 + else: + assert not skipped + + +def test_unchanged_files_keep_their_timestamp_and_report_unchanged( + tmp_path: Path, monkeypatch, capsys +) -> None: + project = _project(tmp_path) + h = Harness(project, monkeypatch, capsys) + assert h.gen()[0] == 0 + generated = project.root / "generated" + files = [f for f in generated.rglob("*") if f.is_file()] + assert files + for f in files: + os.utime(f, (1, 1)) + manifest = project.state / ".hashes.json" + manifest_bytes = manifest.read_bytes() + os.utime(manifest, (1, 1)) + assert h.gen("--force")[0] == 0 + out = h.out + assert all(f.stat().st_mtime == 1 for f in files), "an identical file was rewritten" + assert manifest.stat().st_mtime == 1, "an unchanged manifest was rewritten" + assert manifest.read_bytes() == manifest_bytes + assert "wrote 0 file(s)" in out and "unchanged" in out + assert not [ln for ln in out.splitlines() if ln.startswith(str(generated))] diff --git a/server/typescript/packages/cli/README.md b/server/typescript/packages/cli/README.md index 629d6e6848..0da25164e3 100644 --- a/server/typescript/packages/cli/README.md +++ b/server/typescript/packages/cli/README.md @@ -124,6 +124,7 @@ Generates TS code (Drizzle schema, Zod validators, query helpers, TanStack Query Flags: - `--dry-run` — preview only: renders and reports what would be written, touching nothing on disk (no output files, no `.gen-state/` snapshot) - `--no-antipatterns` — suppress the advisory anti-pattern pass (see below) +- `--force` — render and write everything even when nothing changed since the last run; without it a run that matches the stored key renders nothing ([docs/features/cli.md](../../../../docs/features/cli.md#gen-skips-a-run-when-nothing-changed--and---force-runs-it-anyway-adr-0062)) Positional args filter entities by name. All other knobs (`outDir`, `targets`, `dialect`, `dbImport`, `extStyle`, `apiPrefix`, generator list) live in `metaobjects.config.ts`. diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index bdba49c353..183147951f 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -16,7 +16,8 @@ import { type AdvisoryFindingRow, type AdvisorySection, } from "../lib/advisory.js"; import { loadMemory, resolveCollection } from "@metaobjectsdev/sdk"; -import { declaredGeneratorNames, runGen, undeclaredGeneratorsMessage } from "@metaobjectsdev/codegen-ts"; +import { declaredGeneratorNames, modelHashTree, resolveGenerators, runGen, undeclaredGeneratorsMessage } from "@metaobjectsdev/codegen-ts"; +import type { Generator } from "@metaobjectsdev/codegen-ts"; import type { WriteStatus } from "@metaobjectsdev/codegen-ts"; import { packageOfResolutionKey } from "@metaobjectsdev/metadata"; import type { MetaRoot } from "@metaobjectsdev/metadata"; @@ -35,6 +36,11 @@ import { findRuntimeBoundaryCrossings, runtimeBoundaryWarnings } from "../lib/ru import { hasLegacyDocsBlock, legacyDocsConfigMessage, NO_CONFIG_MESSAGE } from "../lib/docs-removed.js"; import { buildAgentSchemaInput } from "../lib/agent-schema.js"; import { existsSync } from "node:fs"; +import { genMaySkip, reportGenSkip } from "../lib/gen-skip.js"; +import { + clearStoredFingerprint, computeGenInputs, decideGenSkip, keyFor, withModel, writeStoredFingerprint, type GenInputs, +} from "../lib/gen-fingerprint.js"; +import { GEN_CONFIG_FILE } from "../lib/gen-collection.js"; /** * Print a load failure with everything the loader's ADR-0009 envelope carried — the stable @@ -125,6 +131,18 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat // metadata from unrelated trees. Identical object when the two configs sit together. const genCollection = await resolveGenCollection(collection, projectRoot); + // ADR-0062 — the generator half of the skip key (engine, codegen config and owned + // generators, templates, project config, output-changing flags), read now, before the run + // can write anything. The model half is added once the metadata has loaded. + const skipBase: GenInputs | undefined = !cliConfig.dryRun && existsSync(join(projectRoot, GEN_CONFIG_FILE)) + ? computeGenInputs(projectRoot, collection, genCollection, { + entities: flags.entities, + generators: flags.generators, + strict: flags.strict, + baseline: flags.baseline, + }) + : undefined; + // Advisory: nudge to refresh the .claude/skills docs if they predate this CLI. // Rooted at `projectRoot`, not ambient cwd — the scaffolded agent context sits // with the project that declares the metadata, so a run from a subdirectory @@ -204,6 +222,19 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat return 1; } + // ADR-0062 — skip rendering when the loaded model and every generator input match the last + // successful run and every file it recorded exists. Nothing renders and nothing is written, + // the manifest and the stored key included. `--force` (and every mode that does not write) + // never skips. + const skipInputs = skipBase !== undefined ? withModel(skipBase, modelHashTree(metadata)) : undefined; + if (skipInputs !== undefined && genMaySkip(flags)) { + const verdict = decideGenSkip(skipInputs); + if (verdict.skip) { + await reportGenSkip(fmt, verdict.recorded.length); + return 0; + } + } + // ADR-0023: gen loads leniently, so an unknown attribute (`isAbstrakt: true`, a // misspelt `@required`) used to pass without a word while `meta verify` rejected the // same file — and the typo changed what was generated. Say so, naming attribute, node @@ -227,6 +258,23 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat return 2; } + // ADR-0062 — the key this run will store, from the inputs as read before it, plus the + // extra inputs its generators declare (hashed now, before they run). A run that + // includes a generator that cannot declare its inputs stores none and never skips. The + // old fingerprint goes first: a run that fails half-way must not leave one that claims + // its half-written output is current. + const declaredGenerators = forgeConfig.generators ?? []; + let resolvedGenerators: Generator[] | undefined; + // A name the registry does not know fails the run below; until then it is uncacheable. + try { resolvedGenerators = resolveGenerators(declaredGenerators); } catch { resolvedGenerators = undefined; } + const cacheable = resolvedGenerators !== undefined && resolvedGenerators.every((g) => g.cache !== false); + const extras = (resolvedGenerators ?? []).flatMap((g) => [ + ...(g.inputs ?? []), + ...(g.readsMetadataSources === true ? genCollection.sourceRoots : []), + ]); + const nextKey = skipInputs !== undefined ? keyFor(skipInputs, extras) : undefined; + if (skipInputs !== undefined) clearStoredFingerprint(skipInputs.genStateDir); + let result; try { result = await runGen({ @@ -374,6 +422,9 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat } const hasFailure = files.some((f) => f.status === "conflict" || f.status === "refused"); + if (!hasFailure && result.sweepRefused !== true && skipInputs !== undefined && nextKey !== undefined && cacheable && declaredGenerators.length > 0) { + writeStoredFingerprint(projectRoot, skipInputs.genStateDir, nextKey, extras, result.outsidePaths); + } return hasFailure ? 1 : 0; } diff --git a/server/typescript/packages/cli/src/commands/verify.ts b/server/typescript/packages/cli/src/commands/verify.ts index 991aebeaea..42de2edd11 100644 --- a/server/typescript/packages/cli/src/commands/verify.ts +++ b/server/typescript/packages/cli/src/commands/verify.ts @@ -34,6 +34,8 @@ import { derivePayloadFieldTree } from "../lib/payload-field-tree.js"; import { loadMemoryOptionsFrom, loadMetaobjectsConfig, RemovedNamingConfigError, resolveGenCollection, resolveGenConfigDir } from "../lib/load-metaobjects-config.js"; import { collectionLoadOptions } from "../lib/collection-load-options.js"; import { computeCodegenDrift } from "../lib/codegen-drift.js"; +import { computeGenInputs, decideVerifyNoDrift, isCi, withModel } from "../lib/gen-fingerprint.js"; +import { modelHashTree } from "@metaobjectsdev/codegen-ts"; import { hasLegacyDocsBlock, legacyDocsConfigMessage, REMOVED_VERIFY_DOCS } from "../lib/docs-removed.js"; import { buildAgentSchemaInput } from "../lib/agent-schema.js"; import { sourceRootsOf } from "./gen.js"; @@ -1689,6 +1691,25 @@ export async function verifyCommand( return 2; } const config = forgeConfig; + + // ADR-0062 §4 — locally, a key that still matches the last successful `meta gen` (the + // loaded model and every generator input) and a manifest whose every file still hashes to + // its record answer "no drift" without rendering. Never in CI (it renders and compares + // everything, which is the guard against a key that missed an input), and never with --full. + if (!flags.full && !isCi()) { + const inputs = withModel(computeGenInputs(genConfigDir, collection, genCollection, { + entities: [], generators: undefined, strict: false, baseline: "default", + }), modelHashTree(codegenRoot)); + const verdict = decideVerifyNoDrift(inputs); + if (verdict.skip) { + say( + `meta verify — nothing changed since the last \`meta gen\`, and all ${verdict.recorded.length} ` + + "generated file(s) match their record (no codegen drift; --full renders and compares).", + ); + return 0; + } + } + let result; try { result = await computeCodegenDrift(config, codegenRoot, genConfigDir, genCollection.inScope, genCollection.ownFiles, { diff --git a/server/typescript/packages/cli/src/index.ts b/server/typescript/packages/cli/src/index.ts index 8c4dba3bc5..16fb8cea93 100644 --- a/server/typescript/packages/cli/src/index.ts +++ b/server/typescript/packages/cli/src/index.ts @@ -225,6 +225,12 @@ FLAGS: --strict Load the model strictly, as \`meta verify\` does (ADR-0023): an unknown attribute (a typo'd \`@requird\`) is an error and nothing is written, instead of a warning over output that silently changed. + --force Run in full even when nothing changed. Without it, a run whose + inputs (metadata, metaobjects.config.ts and what it imports, + templates/, codegen/, the engine version, these flags) all match + the last successful run's, and whose generated files all still + match what that run left, renders nothing and writes nothing + (ADR-0062; the metadata is still loaded, since the key is made of it). --format Output format (global flag; default toon off-TTY) [] Positional filter on entity names --help, -h Print this help @@ -332,6 +338,10 @@ FLAGS: (a notice, exit code unchanged), so an edit is never invisible. --forbid-hand-edits With --codegen: fail (exit 1) on ANY hand edit inside generated code, for teams that want generated files untouchable. + --full With --codegen: render and compare everything. Without it, a LOCAL + run whose inputs match the last successful 'meta gen' and whose + generated files all still match their recorded hashes answers "no + drift" without rendering. CI (CI set) always renders (ADR-0062). --docs Removed in 1.1.0: says so and exits 2. --codegen checks documentation with everything else \`generators\` declares. --deps Dependency drift — re-resolve each declared dependency exactly as diff --git a/server/typescript/packages/cli/src/lib/args.ts b/server/typescript/packages/cli/src/lib/args.ts index 0280813a89..29aeab8de1 100644 --- a/server/typescript/packages/cli/src/lib/args.ts +++ b/server/typescript/packages/cli/src/lib/args.ts @@ -103,6 +103,8 @@ export function parseAgentDocsArgs(argv: string[]): AgentDocsFlags { export interface GenFlags { dryRun: boolean; + /** ADR-0062 — run in full even when nothing changed since the last run. */ + force: boolean; entities: string[]; /** First-time-on-existing-file behavior. Default: refuse a file that cannot be * proved to be ours. "adopt" → record the file as the merge base and write @@ -149,6 +151,7 @@ export const GEN_OPTIONS = { "limit": { type: "string" }, "generators": { type: "string" }, "strict": { type: "boolean", default: false }, + "force": { type: "boolean", default: false }, } as const; export function parseGenArgs(argv: string[]): GenFlags { @@ -177,6 +180,7 @@ export function parseGenArgs(argv: string[]): GenFlags { probe: !!values.probe, noAntipatterns: !!values["no-antipatterns"], strict: !!values.strict, + force: !!values.force, // Throws on a bad value; the command layer reports it and exits 2, exactly as // it does for --baseline above. limit: parseAdvisoryLimit(values.limit as string | undefined), @@ -386,6 +390,11 @@ export interface VerifyFlags { * it modifies that gate and would otherwise parse cleanly and do nothing. */ forbidHandEdits: boolean; + /** + * ADR-0062 — `--codegen` renders and compares everything, even where a local run could + * answer from the stored `meta gen` fingerprint. CI always does; this is for a local run. + */ + full: boolean; /** * `--docs`, removed in 1.1.0 (ADR-0034 Amendment 9): `--codegen` checks documentation with * everything else the generator list declares. Still parsed, so the command can say where @@ -509,6 +518,7 @@ export const VERIFY_OPTIONS = { templates: { type: "boolean", default: false }, codegen: { type: "boolean", default: false }, "forbid-hand-edits": { type: "boolean", default: false }, + full: { type: "boolean", default: false }, // Removed in 1.1.0 (ADR-0034 Amendment 9). Still parsed, so `meta verify --docs` prints // where the check went instead of an unknown-flag error. docs: { type: "boolean", default: false }, @@ -600,6 +610,7 @@ export function parseVerifyArgs(argv: string[]): VerifyFlags { templates, codegen, forbidHandEdits, + full: !!values.full, docs, deps, replay, diff --git a/server/typescript/packages/cli/src/lib/codegen-drift.ts b/server/typescript/packages/cli/src/lib/codegen-drift.ts index 334e02f512..60fab629c0 100644 --- a/server/typescript/packages/cli/src/lib/codegen-drift.ts +++ b/server/typescript/packages/cli/src/lib/codegen-drift.ts @@ -1,9 +1,9 @@ // `meta verify --codegen` — the codegen-drift gate (ADR-0021 D2). // -// Regenerates the configured codegen into a throwaway temp directory and DIFFs -// the freshly-generated file tree against the committed output (the config's -// outDir / per-target outDirs). Reuses the exact same `runGen` pipeline `meta gen` -// uses, so the comparison is faithful. +// Renders the configured codegen IN MEMORY (a dry run of the exact `runGen` pipeline +// `meta gen` uses, against the real project paths) and compares the rendered files with +// the committed output (the config's outDir / per-target outDirs). Nothing is written: +// no temp tree, no snapshot, no manifest (ADR-0062). // // A DIFFERENCE IS NOT AUTOMATICALLY DRIFT. This gate used to treat "metadata // changed but `meta gen` wasn't re-run" and "a generated file was hand-edited" as @@ -23,21 +23,10 @@ // Design: spec/design-docs/2026-08-27-codegen-drift-hand-edits-design.md // // Faithfulness note: generated content can embed import paths computed RELATIVE -// to a target's outDir (and between targets). To keep the regen byte-identical -// to the committed output, each outDir is remapped into the temp tree at the -// SAME path it has relative to the project root — preserving the inter-target -// layout. `importBase` (a stable string, not a path) is untouched. +// to a target's outDir (and between targets). The dry run renders at the real paths, +// so those imports come out exactly as `meta gen` writes them. -import { - mkdtempSync, - rmSync, - existsSync, - readFileSync, - readdirSync, - statSync, - cpSync, -} from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import { join, relative, resolve, isAbsolute } from "node:path"; import { runGen, @@ -162,7 +151,7 @@ function listFiles(dir: string): string[] { } /** - * Run codegen into a temp tree and diff it against the committed output. + * Render codegen in memory and diff it against the committed output. * * @param config the loaded metaobjects config (provides outDir/targets). * @param metadata the loaded MetaRoot (same object `meta gen` would use). @@ -214,71 +203,32 @@ export async function computeCodegenDrift( }; } - // Build a temp tree that mirrors each outDir at its project-relative path, so - // relative import paths in generated content come out identical. - const tempRoot = mkdtempSync(join(tmpdir(), "meta-verify-codegen-")); - try { - const tempFor = (committed: string): string => { - const rel = relative(root, committed); - // If a committed outDir lives outside the project root, fall back to a - // flattened, collision-safe slot under the temp root. (Relative-import - // fidelity for out-of-tree targets isn't guaranteed, but the diff is - // still meaningful per-file.) - const safeRel = rel.startsWith("..") || isAbsolute(rel) - ? committed.replace(/[^A-Za-z0-9]+/g, "_") - : rel; - return join(tempRoot, safeRel); - }; - - // Remap the config so runGen writes into the temp mirror instead of the - // committed output. Default outDir + each named target's outDir are - // rewritten — resolved against `root` (see committedOutDirs above), not - // the ambient process.cwd(), so this stays correct under `--cwd`. - const remappedTargets: Record = {}; - for (const [name, t] of Object.entries(config.targets ?? {})) { - remappedTargets[name] = { ...t, outDir: tempFor(resolve(root, t.outDir)) }; - } - const tempConfig: MetaobjectsGenConfig = { - ...config, - outDir: tempFor(resolve(root, config.outDir)), - ...(config.targets !== undefined ? { targets: remappedTargets } : {}), - }; - - // runGen is called with `projectRoot: tempRoot` below (so relative outDir - // remapping stays correct — see the module doc). Some generators resolve - // ancillary project-relative input at generation time rather than through - // `config` — namely the template-output codegen family (e.g. render-helper, - // via codegen-ts's `projectProvider(ctx.projectRoot)`), which reads a - // `/templates/` dir to build-time-verify each referenced - // mustache. Mirror it into the temp root so that lookup succeeds the same - // way it does for `meta gen` against the real project root — otherwise - // every project using those generators would spuriously fail `--codegen` - // with an "unresolved" template error that has nothing to do with drift. - const projectTemplatesDir = join(root, "templates"); - if (existsSync(projectTemplatesDir)) { - cpSync(projectTemplatesDir, join(tempRoot, "templates"), { recursive: true }); - } - - // Generate fresh into the temp tree. "overwrite" + "fresh" + a temp - // gen-state dir guarantees every file is written (no merge/skip), so the - // temp tree is the canonical "what gen would produce right now". + // Render what `meta gen` would write right now, IN MEMORY (ADR-0062, item 9): a dry run + // against the real project renders exactly what a real run renders (same paths, so the + // same relative imports) and writes nothing — no temp tree, no snapshot, no manifest. + { const regen = await runGen({ - config: tempConfig, + config, metadata, - projectRoot: tempRoot, - genStateDir: join(tempRoot, ".gen-state"), - mergeStrategy: "overwrite", - baseline: "fresh", - // The real project, for a generator that reads its files (`ctx.inputRoot`): - // `shared-model` takes its default version from the nearest package.json, and an - // owned generator may read anything. `projectRoot` stays the temp tree, which the - // owned route and entity generators compute their adapter import against. + projectRoot: root, + dryRun: true, + // A generator that reads the project's files (`ctx.inputRoot`) reads them here. inputRoot: root, ...(scope !== undefined ? { scope } : {}), ...(sourceFiles !== undefined ? { sourceFiles } : {}), ...(run?.sourceRoots !== undefined ? { sourceRoots: run.sourceRoots } : {}), ...(run?.agentSchema !== undefined ? { agentSchema: run.agentSchema } : {}), }); + const rendered = regen.rendered ?? new Map(); + /** The rendered files under `dir`, by path relative to it. */ + const renderedUnder = (dir: string): Map => { + const out = new Map(); + for (const [full, content] of rendered) { + const rel = relative(dir, full); + if (rel !== "" && !rel.startsWith("..") && !isAbsolute(rel)) out.set(rel, content); + } + return out; + }; // Where gen discards hand edits instead of keeping them (handEdits: "overwrite"). const overwrite = regen.handEditsOverwrite; @@ -299,9 +249,9 @@ export async function computeCodegenDrift( const docsIgnoredDirs: string[] = []; let docsIgnoreUnavailable: string | undefined; for (const committed of committedDirs) { - const fresh = tempFor(committed); + const freshContent = renderedUnder(committed); const committedFiles = new Set(listFiles(committed)); - const freshFiles = new Set(listFiles(fresh)); + const freshFiles = new Set(freshContent.keys()); const all = new Set([...committedFiles, ...freshFiles]); // Documentation the project git-ignores is not checked (carried from 1.0's @@ -346,7 +296,7 @@ export async function computeCodegenDrift( continue; } const verdict = haveWriteRecords - ? orphanVerdict(regen.orphanSweepJobs ?? [], tempRoot, relative(tempRoot, join(fresh, rel))) + ? orphanVerdict(regen.orphanSweepJobs ?? [], root, relKey) : undefined; if (verdict?.kept === true) continue; driftedFiles.add(relKey); @@ -377,7 +327,7 @@ export async function computeCodegenDrift( lines.push(`+ ${relKey} (regen would emit it; not committed — run 'meta gen')`); } else { const a = readFileSync(join(committed, rel), "utf8"); - const b = readFileSync(join(fresh, rel), "utf8"); + const b = freshContent.get(rel)!; if (a !== b) { // A `Names` artifact is the ONE generated file where a hand edit is // itself the defect, so the exemption below does not reach it. RULED: if you @@ -421,7 +371,7 @@ export async function computeCodegenDrift( // nothing is proven, so the old byte verdict stands. driftedFiles.add(relKey); lines.push(`~ ${relKey} (committed content differs from a fresh regen)`); - } else if (overwrite?.paths.has(join(fresh, rel)) === true) { + } else if (overwrite?.paths.has(join(committed, rel)) === true) { // Its generator says handEdits: "overwrite": `meta gen` replaces the edit // with fresh output, so it is drift that gen fixes, not a kept edit. driftedFiles.add(relKey); @@ -451,7 +401,5 @@ export async function computeCodegenDrift( docsIgnoredDirs, ...(docsIgnoreUnavailable !== undefined ? { docsIgnoreUnavailable } : {}), }; - } finally { - rmSync(tempRoot, { recursive: true, force: true }); } } diff --git a/server/typescript/packages/cli/src/lib/gen-collection.ts b/server/typescript/packages/cli/src/lib/gen-collection.ts new file mode 100644 index 0000000000..d001e1f90a --- /dev/null +++ b/server/typescript/packages/cli/src/lib/gen-collection.ts @@ -0,0 +1,97 @@ +// server/typescript/packages/cli/src/lib/gen-collection.ts +// +// Where a TypeScript package's codegen config lives and which collection it generates from. +// A leaf module, importing node builtins and the sdk's collection resolver only, because the +// `meta gen` skip check (ADR-0062) answers these two questions before anything heavier loads. +import { existsSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { resolveCollection, type Collection } from "@metaobjectsdev/sdk/collection"; + +export const GEN_CONFIG_FILE = "metaobjects.config.ts"; + +/** + * The directory whose `metaobjects.config.ts` governs a run started in `startDir` — + * the nearest ancestor carrying that file, `fallback` when there is none. + * + * This is a SECOND walk, deliberately separate from `resolveCollection`'s. The two + * files answer different questions and design §4.6 already says so: `.metaobjects/ + * config.json` declares where metadata comes from — port-neutral, read by all five + * CLIs, and reasonably repo-global in a polyglot monorepo — while + * `metaobjects.config.ts` declares how THIS TypeScript package generates code. Reading + * the second from the directory that carried the first (#326) meant a Maven- or + * pip-rooted repo with a JS app underneath could not run `meta gen` at all: the + * collection resolved to the repo root, and the app's config, sitting in the very + * directory the command was invoked from, was never looked at. + * + * Nearest wins, which is what keeps the opposite arm — the divergence commit + * 0c8fd136e fixed — closed: a run from a subdirectory that declares NO config of its + * own walks up to the project root's, exactly as before, rather than silently + * defaulting `columnNamingStrategy` and emitting a migration that renames every + * column. When the two files sit together, as they do in every `meta init` project, + * this walk and the collection walk return the same directory by construction. + * + * The `fallback` is the collection's directory, so a project with no + * `metaobjects.config.ts` anywhere keeps today's diagnostics unchanged: this walk can + * only ever move the answer CLOSER to the invocation, never further away. + * + * Boundaries mirror `discoverCollectionRoot` (sdk `discovery.ts`): the marker is + * checked before `.git`, so a repo-root project sharing its directory with `.git` is + * still reachable from any subdirectory, and the walk stops there so a monorepo can + * never adopt a parent checkout's codegen config. + */ +export function resolveGenConfigDir(startDir: string, fallback: string): string { + let dir = resolve(startDir); + for (;;) { + if (existsSync(join(dir, GEN_CONFIG_FILE))) return dir; + if (existsSync(join(dir, ".git"))) break; + const parent = dirname(dir); + if (parent === dir) break; + dir = parent; + } + return fallback; +} + +/** + * The collection a TypeScript package GENERATES FROM (#340). + * + * #326/#327 established that the two config files answer different questions, and gave + * `metaobjects.config.ts` its own walk. This is the remaining half of the same split: + * a sub-project whose TS config sits below the collection root was still LOADING the + * ancestor's whole source set, so its `src/generated` absorbed metadata belonging to + * unrelated parts of the repository — one adopter's web app went from 376 files to 831, + * the surplus being another module's server-side prompt payload DTOs. It fails OPEN + * (`tsc` passes, tests pass), so the only symptom is a directory that quietly doubled. + * + * The rule: an ancestor `.metaobjects/config.json` is the DEFAULT for a package that + * declares no sources of its own, never an ADDITION to one that does. So when the TS + * config sits somewhere the collection did not, that directory is re-resolved as a + * collection in its own right, and it wins if it actually resolves any metadata. + * + * It can only ever NARROW, and only in a shape that could not have worked before: + * - the two directories coincide (every `meta init` project, and every run from a + * project root) — returns the original, untouched, without a second resolve; + * - the sub-project declares no sources — the pinned resolve throws + * `ERR_SOURCE_UNRESOLVED` or comes back empty, and the ancestor stands, so a + * package that genuinely lives off an ancestor tree keeps working; + * - the sub-project has its own metadata — it generates from exactly that, which is + * what it did before source resolution learned to walk upward. + * + * Deliberately NOT applied to `.metaobjects/` STATE. Migrations, snapshots and the + * operational block stay keyed on the discovered collection's directory (#326 settled + * that); this narrows what is LOADED, and nothing about where state lives. + */ +export async function resolveGenCollection( + collection: Collection, + genConfigDir: string, +): Promise { + if (resolve(genConfigDir) === resolve(collection.configDir)) return collection; + try { + const pinned = await resolveCollection(genConfigDir, { explicitDir: genConfigDir }); + return pinned.files.length > 0 ? pinned : collection; + } catch { + // The sub-project declares nothing resolvable of its own — inherit, exactly as a + // package with no config always has. + return collection; + } +} + diff --git a/server/typescript/packages/cli/src/lib/gen-fingerprint.ts b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts new file mode 100644 index 0000000000..65b198b1f1 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/gen-fingerprint.ts @@ -0,0 +1,509 @@ +// server/typescript/packages/cli/src/lib/gen-fingerprint.ts +// +// ADR-0062 — `meta gen` skips rendering when the loaded model and its generators are +// unchanged since the last successful run. +// +// The key has two halves. The MODEL half is computed from the loaded model, never from the +// metadata source files (`modelHashTree` in codegen-ts): each root-level node in its +// canonical effective form, rolled up per package and for the model. The GENERATOR half is +// computed here: the built engine code, the codegen config and every owned generator it +// reaches, the template roots, the generator-declared extra inputs, the project config and +// the output-changing flags. +// +// The rule: the key may be wrong only in the safe direction. Anything the generator half +// cannot prove unchanged counts as changed, so its inputs are deliberately wide (a whole +// package's files in a checkout, every lockfile up the tree). +// +// Entries are named (kind, name, content hash) and folded into one key, so a later +// per-object or per-package key can reuse them for a subset of the inputs. +import { createHash } from "node:crypto"; +import { existsSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync, mkdirSync } from "node:fs"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { Collection } from "@metaobjectsdev/sdk/collection"; +import { GEN_CONFIG_FILE } from "./gen-collection.js"; + +/** Bumped whenever what goes into the fingerprint changes, so an old stored key never matches. */ +export const FINGERPRINT_FORMAT = 3; + +/** One input: what kind it is, which one, and the SHA-256 of its content. */ +export interface FingerprintEntry { + kind: string; + name: string; + hash: string; +} + +/** The output-changing flags of a `meta gen` run. Anything else on the command line does not + * change what is written (`--format`, `--limit`, `--no-antipatterns`). */ +export interface GenSelection { + entities: readonly string[]; + generators: readonly string[] | undefined; + strict: boolean; + baseline: string; +} + +/** What `.fingerprint-typescript.json` holds. */ +export interface StoredFingerprint { + format: number; + key: string; + /** The generator-declared extra inputs (project-relative), recorded so a check can hash + * them without resolving the generators first. */ + extras: string[]; + /** Every file the manifest records, by project-relative path, with the hash of its bytes + * as the run left them on disk. A file that changed since (a new hand edit, a checkout) + * makes the next run render: `meta gen` then puts it back or merges it, as `verify` + * tells the user it will. An edit the last run already kept is unchanged, and skips. */ + outputs: Record; + /** Absolute paths the run wrote outside the project root. The manifest records none of them, + * so a skip needs each to still exist. */ + untracked: string[]; +} + +export const FINGERPRINT_FILE = ".fingerprint-typescript.json"; +const HASHES_FILE = ".hashes.json"; + +/** Directories never descended into: dependencies, VCS and tool state, build caches. */ +const SKIP_DIRS = new Set(["node_modules", ".git", ".turbo", ".cache", ".metaobjects"]); +/** Directories inside an engine package that are not engine: its tests and reports. */ +const PACKAGE_SKIP_DIRS = new Set([...SKIP_DIRS, "test", "tests", "reports", "coverage"]); +const LOCKFILES = ["bun.lock", "bun.lockb", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock"]; +const MANIFEST_FILES = ["package.json", "pyproject.toml"]; + +function sha256(data: string | Buffer): string { + return createHash("sha256").update(data).digest("hex"); +} + +function fileHash(path: string): string { + return sha256(readFileSync(path)); +} + +/** Every regular file under `dir`, sorted, skipping `skip` directory names. */ +function listFiles(dir: string, skip: ReadonlySet): string[] { + const out: string[] = []; + const walk = (d: string): void => { + let names: string[]; + try { names = readdirSync(d).sort(); } catch { return; } + for (const name of names) { + const p = join(d, name); + let st; + try { st = statSync(p); } catch { continue; } + if (st.isDirectory()) { + if (!skip.has(name)) walk(p); + } else if (st.isFile()) out.push(p); + } + }; + walk(dir); + return out; +} + +/** A file or every file under a directory, as entries named relative to `base`. An absent + * path is an entry too: its later appearance must change the key. */ +function pathEntries(kind: string, path: string, base: string, skip: ReadonlySet = SKIP_DIRS): FingerprintEntry[] { + const name = (p: string): string => { + const r = relative(base, p); + return r.startsWith("..") || isAbsolute(r) ? p : r.split(sep).join("/"); + }; + if (!existsSync(path)) return [{ kind, name: name(path), hash: "absent" }]; + let st; + try { st = statSync(path); } catch { return [{ kind, name: name(path), hash: "unreadable" }]; } + if (st.isFile()) return [{ kind, name: name(path), hash: fileHash(path) }]; + return listFiles(path, skip).map((f) => ({ kind, name: name(f), hash: fileHash(f) })); +} + +/** Fold entries into one key: sorted, so the order inputs were discovered in never matters. */ +export function fingerprintKey(entries: readonly FingerprintEntry[]): string { + const lines = entries.map((e) => `${e.kind}\t${e.name}\t${e.hash}`); + lines.sort(); + return sha256(`metaobjects-gen-fingerprint ${FINGERPRINT_FORMAT}\n${lines.join("\n")}\n`); +} + +// --------------------------------------------------------------------------- +// Engine identity +// --------------------------------------------------------------------------- + +/** The directory holding `/package.json`, looked up from `fromDir` the way Node does. */ +function findPackageDir(name: string, fromDir: string): string | undefined { + for (let dir = fromDir; ; dir = dirname(dir)) { + const candidate = join(dir, "node_modules", name); + if (existsSync(join(candidate, "package.json"))) return candidate; + if (dirname(dir) === dir) return undefined; + } +} + +function readJson(path: string): Record | undefined { + try { + const v: unknown = JSON.parse(readFileSync(path, "utf-8")); + return typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record) : undefined; + } catch { + return undefined; + } +} + +function dependencyNames(pkg: Record | undefined): string[] { + const deps = pkg?.dependencies; + return typeof deps === "object" && deps !== null ? Object.keys(deps).sort() : []; +} + +function isInstalled(dir: string): boolean { + let real = dir; + try { real = realpathSync(dir); } catch { /* keep the path as given */ } + return real.split(sep).includes("node_modules"); +} + +/** + * One package's identity. Installed from a registry (it lives under `node_modules`): its + * `package.json`, which carries the version. A linked or source checkout: the content of + * every file it ships, because its version does not move when its code does. + */ +function packageEntries(kind: string, dir: string): FingerprintEntry[] { + const name = (readJson(join(dir, "package.json"))?.name as string | undefined) ?? dir; + if (isInstalled(dir)) { + return [{ kind, name: `${name}/package.json`, hash: fileHash(join(dir, "package.json")) }]; + } + return listFiles(dir, PACKAGE_SKIP_DIRS).map((f) => ({ + kind, + name: `${name}/${relative(dir, f).split(sep).join("/")}`, + hash: fileHash(f), + })); +} + +/** + * The packages a package runs on: every `@metaobjectsdev/*` dependency, followed all the + * way, by full identity; every other dependency by its `package.json` (its version). + */ +function packageClosureEntries(kind: string, rootDir: string, seen: Set): FingerprintEntry[] { + const entries: FingerprintEntry[] = []; + const visit = (dir: string): void => { + let real = dir; + try { real = realpathSync(dir); } catch { /* keep */ } + if (seen.has(real)) return; + seen.add(real); + entries.push(...packageEntries(kind, dir)); + const pkg = readJson(join(dir, "package.json")); + for (const dep of dependencyNames(pkg)) { + const depDir = findPackageDir(dep, dir); + if (depDir === undefined) { + entries.push({ kind, name: `${dep}/package.json`, hash: "absent" }); + continue; + } + if (dep.startsWith("@metaobjectsdev/")) visit(depDir); + else { + let depReal = depDir; + try { depReal = realpathSync(depDir); } catch { /* keep */ } + if (seen.has(depReal)) continue; + seen.add(depReal); + entries.push({ kind, name: `${dep}/package.json`, hash: fileHash(join(depDir, "package.json")) }); + } + } + }; + visit(rootDir); + return entries; +} + +/** The CLI package's own directory (the one holding its `package.json`). */ +function cliPackageDir(): string | undefined { + let dir = dirname(fileURLToPath(import.meta.url)); + for (;;) { + const pkg = readJson(join(dir, "package.json")); + if (pkg?.name === "@metaobjectsdev/cli") return dir; + if (dirname(dir) === dir) return undefined; + dir = dirname(dir); + } +} + +/** + * The engine: this CLI and every package it runs (the config's `@metaobjectsdev/*` imports + * are aliased onto these copies). A compiled single binary has no package tree on disk; its + * identity is the binary's own content. + */ +function engineEntries(seen: Set): FingerprintEntry[] { + if (import.meta.url.includes("$bunfs")) { + return [{ kind: "engine", name: "binary", hash: fileHash(process.execPath) }]; + } + const dir = cliPackageDir(); + if (dir === undefined) return [{ kind: "engine", name: "cli", hash: "unresolved" }]; + return packageClosureEntries("engine", dir, seen); +} + +// --------------------------------------------------------------------------- +// The project's generators: metaobjects.config.ts and everything it imports +// --------------------------------------------------------------------------- + +const IMPORT_RE = /(?:\bfrom\s*|\bimport\s*\(?\s*|\brequire\s*\(\s*|\bexport\s+\*\s+from\s*)["'`]([^"'`]+)["'`]/g; +const SOURCE_EXTS = [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".jsx", ".json"]; + +function resolveRelative(spec: string, fromFile: string): string | undefined { + const base = resolve(dirname(fromFile), spec); + const candidates = [base]; + // A `.js` specifier that names a `.ts` source (the ESM convention). + const m = /\.(m|c)?js$/.exec(base); + if (m !== null) candidates.push(base.slice(0, -m[0].length) + `.${m[1] ?? ""}ts`, base.slice(0, -m[0].length) + ".tsx"); + for (const ext of SOURCE_EXTS) candidates.push(base + ext); + for (const ext of SOURCE_EXTS) candidates.push(join(base, `index${ext}`)); + for (const c of candidates) { + try { if (statSync(c).isFile()) return c; } catch { /* next */ } + } + return undefined; +} + +function packageNameOf(spec: string): string { + const parts = spec.split("/"); + return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!; +} + +/** + * `metaobjects.config.ts` and its import graph: every local module it reaches, by content, + * and every package it imports, by identity. An owned (ejected) generator is a local module, + * so editing it changes the key. A package the engine already covers is not repeated. + */ +function configGraphEntries(configFile: string, projectRoot: string, seen: Set): FingerprintEntry[] { + const entries: FingerprintEntry[] = []; + const visited = new Set(); + const queue = [configFile]; + while (queue.length > 0) { + const file = queue.shift()!; + if (visited.has(file)) continue; + visited.add(file); + entries.push(...pathEntries("generator-source", file, projectRoot)); + let text: string; + try { text = readFileSync(file, "utf-8"); } catch { continue; } + for (const match of text.matchAll(IMPORT_RE)) { + const spec = match[1]!; + if (spec.startsWith("node:")) continue; + if (spec.startsWith(".") || spec.startsWith("/")) { + const target = resolveRelative(spec, file); + if (target === undefined) entries.push({ kind: "generator-source", name: `${relative(projectRoot, file)} -> ${spec}`, hash: "unresolved" }); + else if (!target.split(sep).includes("node_modules")) queue.push(target); + continue; + } + const name = packageNameOf(spec); + const dir = findPackageDir(name, dirname(file)); + if (dir === undefined) { + // A builtin without the `node:` prefix, or a package that is not installed (the run + // will fail on it). Either way its name is the stable answer. + entries.push({ kind: "generator-package", name, hash: "unresolved" }); + continue; + } + // The engine's own packages are already counted; the CLI aliases the config's + // `@metaobjectsdev/*` imports onto them, so the project's copy is not what runs. + if (name.startsWith("@metaobjectsdev/")) continue; + entries.push(...packageClosureEntries("generator-package", dir, seen)); + } + } + return entries; +} + +// --------------------------------------------------------------------------- +// The whole input set +// --------------------------------------------------------------------------- + +export interface GenInputs { + projectRoot: string; + genStateDir: string; + /** Everything but the generator-declared extras, which only the stored fingerprint names. + * Holds the model entry once `withModel` added it. */ + entries: FingerprintEntry[]; +} + +/** The inputs with the loaded model's hash added: the model half of the key. */ +export function withModel(inputs: GenInputs, model: { model: string }): GenInputs { + return { ...inputs, entries: [...inputs.entries, { kind: "model", name: "(model)", hash: model.model }] }; +} + +/** The project's ancestors up to and including the repository root (the first with `.git`). */ +function ancestorsToRepoRoot(start: string): string[] { + const out: string[] = []; + for (let dir = resolve(start); ; dir = dirname(dir)) { + out.push(dir); + if (existsSync(join(dir, ".git")) || dirname(dir) === dir) return out; + } +} + +/** + * The generator half of the key: every input other than the loaded model that can change + * what `meta gen` writes. + * + * `collection` is the collection the run GENERATES from and `discovered` the one it was + * discovered as (the same object unless a sub-project declares its own sources; both + * configs are inputs either way). + */ +export function computeGenInputs( + projectRoot: string, + discovered: Collection, + collection: Collection, + selection: GenSelection, + /** Test seam: the engine's entries in place of this installation's own. */ + engine?: readonly FingerprintEntry[], +): GenInputs { + const entries: FingerprintEntry[] = []; + const seen = new Set(); + + entries.push({ kind: "tool", name: "fingerprint-format", hash: String(FINGERPRINT_FORMAT) }); + entries.push(...(engine ?? engineEntries(seen))); + + // The metadata itself is NOT read here: the model half of the key comes from the loaded + // model (`withModel`). What sits beside it and is read raw is a template, not metadata: + // prompt `.mustache` sources under a source root, which the docs-site generator reads. + for (const root of collection.sourceRoots) { + if (!existsSync(root)) continue; + for (const f of listFiles(root, SKIP_DIRS)) { + if (f.endsWith(".mustache")) entries.push(...pathEntries("templates", f, projectRoot)); + } + } + + // Config: both config files of both collections, the codegen config and its imports. + for (const dir of new Set([discovered.configDir, collection.configDir, projectRoot])) { + entries.push(...pathEntries("config", join(dir, ".metaobjects", "config.json"), projectRoot)); + } + const configFile = join(projectRoot, GEN_CONFIG_FILE); + entries.push(...configGraphEntries(configFile, projectRoot, seen)); + + // Templates and owned code: the project's `templates/` (prompt and template-codegen + // sources, the owned docs-site theme's neighbours) and `codegen/` (owned generators and + // anything they read beside them), whether or not the config imports them. + entries.push(...pathEntries("templates", join(projectRoot, "templates"), projectRoot)); + entries.push(...pathEntries("generator-source", join(projectRoot, "codegen"), projectRoot)); + + // Package manifests and lockfiles up to the repository root: an installed dependency's + // version moves with them, and the shared-model generator reads the nearest version. + for (const dir of ancestorsToRepoRoot(projectRoot)) { + for (const f of [...MANIFEST_FILES, ...LOCKFILES]) { + const p = join(dir, f); + if (existsSync(p)) entries.push(...pathEntries("project", p, projectRoot)); + } + } + + entries.push({ + kind: "selection", + name: "flags", + hash: sha256(JSON.stringify({ + entities: [...selection.entities].sort(), + generators: selection.generators === undefined ? null : [...selection.generators].sort(), + strict: selection.strict, + baseline: selection.baseline, + })), + }); + + return { projectRoot, genStateDir: join(projectRoot, ".metaobjects", ".gen-state"), entries }; +} + +/** The generator-declared extra inputs, as entries. */ +export function extraEntries(projectRoot: string, extras: readonly string[]): FingerprintEntry[] { + return [...new Set(extras)].sort().flatMap((p) => pathEntries("extra", resolve(projectRoot, p), projectRoot)); +} + +/** The key for `inputs` plus `extras`. */ +export function keyFor(inputs: GenInputs, extras: readonly string[]): string { + return fingerprintKey([...inputs.entries, ...extraEntries(inputs.projectRoot, extras)]); +} + +// --------------------------------------------------------------------------- +// Stored state +// --------------------------------------------------------------------------- + +export function readStoredFingerprint(genStateDir: string): StoredFingerprint | undefined { + const raw = readJson(join(genStateDir, FINGERPRINT_FILE)); + if (raw === undefined) return undefined; + const { format, key, extras, outputs } = raw; + const untracked = raw.untracked ?? []; + if (format !== FINGERPRINT_FORMAT || typeof key !== "string") return undefined; + if (!Array.isArray(extras) || !extras.every((e) => typeof e === "string")) return undefined; + if (typeof outputs !== "object" || outputs === null || Array.isArray(outputs)) return undefined; + if (!Object.values(outputs).every((h) => typeof h === "string")) return undefined; + if (!Array.isArray(untracked) || !untracked.every((p) => typeof p === "string")) return undefined; + return { + format, key, extras: extras as string[], outputs: outputs as Record, + untracked: untracked as string[], + }; +} + +/** + * Store the key after a successful run, with the on-disk hash of every file the manifest + * now records. A recorded file that is missing makes no key at all: the next run renders. + */ +export function writeStoredFingerprint( + projectRoot: string, genStateDir: string, key: string, extras: readonly string[], + untracked: readonly string[] = [], +): void { + const outputs: Record = {}; + for (const path of [...recordedFiles(genStateDir).keys()].sort()) { + const full = resolve(projectRoot, path); + if (!existsSync(full)) return; + outputs[path] = fileHash(full); + } + mkdirSync(genStateDir, { recursive: true }); + const body: StoredFingerprint = { format: FINGERPRINT_FORMAT, key, extras: [...new Set(extras)].sort(), outputs, + untracked: [...new Set(untracked)].sort(), + }; + writeFileSync(join(genStateDir, FINGERPRINT_FILE), JSON.stringify(body, null, 2) + "\n"); +} + +/** Forget the stored fingerprint. A real run does this before it writes anything, so a run + * that fails half-way can never leave a key that claims its half-written output is current. */ +export function clearStoredFingerprint(genStateDir: string): void { + rmSync(join(genStateDir, FINGERPRINT_FILE), { force: true }); +} + +/** The manifest's recorded paths and hashes; empty when there is none. */ +function recordedFiles(genStateDir: string): Map { + const out = new Map(); + const raw = readJson(join(genStateDir, HASHES_FILE)); + if (raw === undefined) return out; + for (const [path, value] of Object.entries(raw)) { + if (typeof value === "string") out.set(path, value); + else if (typeof value === "object" && value !== null && typeof (value as { hash?: unknown }).hash === "string") { + out.set(path, (value as { hash: string }).hash); + } + } + return out; +} + +export type SkipVerdict = + | { skip: true; recorded: string[] } + | { skip: false; reason: string }; + +/** + * The `meta gen` decision (ADR-0062 §3): skip when the stored key matches, and every file + * the manifest records still exists with the bytes the last successful run left. It reads + * the generated files (no render, no write); a file changed since then makes the run render. + */ +export function decideGenSkip(inputs: GenInputs): SkipVerdict { + // Never decide without the model half: the generator half alone says nothing about it. + if (!inputs.entries.some((e) => e.kind === "model")) return { skip: false, reason: "the model was not hashed" }; + const stored = readStoredFingerprint(inputs.genStateDir); + if (stored === undefined) return { skip: false, reason: "no stored fingerprint" }; + if (keyFor(inputs, stored.extras) !== stored.key) return { skip: false, reason: "an input changed" }; + const recorded = recordedFiles(inputs.genStateDir); + for (const path of recorded.keys()) { + const full = resolve(inputs.projectRoot, path); + if (!existsSync(full)) return { skip: false, reason: `${path} is missing` }; + const left = stored.outputs[path]; + if (left === undefined || fileHash(full) !== left) return { skip: false, reason: `${path} changed since the last run` }; + } + for (const path of stored.untracked) { + if (!existsSync(path)) return { skip: false, reason: `${path} is missing` }; + } + return { skip: true, recorded: [...recorded.keys()].sort() }; +} + +/** + * The local `verify --codegen` shortcut (ADR-0062 §4): the stored key matches AND every + * recorded file still hashes to its record. Hashing the files on disk is the point here: a + * hand edit is not an input, so `gen` may skip over one, but `verify` must still see it. + */ +export function decideVerifyNoDrift(inputs: GenInputs): SkipVerdict { + const verdict = decideGenSkip(inputs); + if (!verdict.skip) return verdict; + const recorded = recordedFiles(inputs.genStateDir); + if (recorded.size === 0) return { skip: false, reason: "the manifest records no file" }; + for (const [path, hash] of recorded) { + if (fileHash(resolve(inputs.projectRoot, path)) !== hash) return { skip: false, reason: `${path} differs from its record` }; + } + return verdict; +} + +/** True on a CI runner: `CI` set to anything but empty, `0` or `false`. */ +export function isCi(env: NodeJS.ProcessEnv = process.env): boolean { + const v = env.CI; + return v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false"; +} diff --git a/server/typescript/packages/cli/src/lib/gen-skip.ts b/server/typescript/packages/cli/src/lib/gen-skip.ts new file mode 100644 index 0000000000..edb0a054c9 --- /dev/null +++ b/server/typescript/packages/cli/src/lib/gen-skip.ts @@ -0,0 +1,38 @@ +// server/typescript/packages/cli/src/lib/gen-skip.ts +// +// ADR-0062 — when `meta gen` may skip rendering, and how a skipped run is reported. +import type { GenFlags } from "./args.js"; +import { skippedSection } from "./advisory.js"; +import { log } from "./log.js"; + +type Format = "toon" | "json" | "text"; + +/** True when a `meta gen` run with these flags writes, and so may skip. */ +export function genMaySkip(flags: GenFlags): boolean { + return !flags.dryRun && !flags.list && !flags.probe && !flags.force; +} + +const SKIP_SUMMARY = "nothing changed since the last meta gen, so nothing was rendered or written"; +const SKIP_HELP = "meta gen --force regenerates everything"; + +/** Print the skipped run in the requested format. */ +export async function reportGenSkip(fmt: Format, recorded: number): Promise { + if (fmt === "text") { + log.info(`meta gen — ${SKIP_SUMMARY} (${recorded} generated file(s) up to date). ${SKIP_HELP}.`); + return; + } + // The same document shape a run prints, so a reader parsing it needs no second schema. + const doc = { + gen: [] as { file: string; status: string }[], + summary: SKIP_SUMMARY, + help: [SKIP_HELP], + antiPatterns: skippedSection("not run: nothing changed since the last meta gen"), + skipped: true, + upToDate: recorded, + }; + if (fmt === "json") log.info(JSON.stringify(doc, null, 2)); + else { + const { toonEncode } = await import("./format.js"); + log.info(toonEncode(doc)); + } +} diff --git a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts index 848b1e4c30..b227a408a6 100644 --- a/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts +++ b/server/typescript/packages/cli/src/lib/load-metaobjects-config.ts @@ -223,91 +223,9 @@ export function loadMemoryOptionsFrom( }; } -/** - * The directory whose `metaobjects.config.ts` governs a run started in `startDir` — - * the nearest ancestor carrying that file, `fallback` when there is none. - * - * This is a SECOND walk, deliberately separate from `resolveCollection`'s. The two - * files answer different questions and design §4.6 already says so: `.metaobjects/ - * config.json` declares where metadata comes from — port-neutral, read by all five - * CLIs, and reasonably repo-global in a polyglot monorepo — while - * `metaobjects.config.ts` declares how THIS TypeScript package generates code. Reading - * the second from the directory that carried the first (#326) meant a Maven- or - * pip-rooted repo with a JS app underneath could not run `meta gen` at all: the - * collection resolved to the repo root, and the app's config, sitting in the very - * directory the command was invoked from, was never looked at. - * - * Nearest wins, which is what keeps the opposite arm — the divergence commit - * 0c8fd136e fixed — closed: a run from a subdirectory that declares NO config of its - * own walks up to the project root's, exactly as before, rather than silently - * defaulting `columnNamingStrategy` and emitting a migration that renames every - * column. When the two files sit together, as they do in every `meta init` project, - * this walk and the collection walk return the same directory by construction. - * - * The `fallback` is the collection's directory, so a project with no - * `metaobjects.config.ts` anywhere keeps today's diagnostics unchanged: this walk can - * only ever move the answer CLOSER to the invocation, never further away. - * - * Boundaries mirror `discoverCollectionRoot` (sdk `discovery.ts`): the marker is - * checked before `.git`, so a repo-root project sharing its directory with `.git` is - * still reachable from any subdirectory, and the walk stops there so a monorepo can - * never adopt a parent checkout's codegen config. - */ -export function resolveGenConfigDir(startDir: string, fallback: string): string { - let dir = resolve(startDir); - for (;;) { - if (existsSync(join(dir, CONFIG_FILE))) return dir; - if (existsSync(join(dir, ".git"))) break; - const parent = dirname(dir); - if (parent === dir) break; - dir = parent; - } - return fallback; -} - -/** - * The collection a TypeScript package GENERATES FROM (#340). - * - * #326/#327 established that the two config files answer different questions, and gave - * `metaobjects.config.ts` its own walk. This is the remaining half of the same split: - * a sub-project whose TS config sits below the collection root was still LOADING the - * ancestor's whole source set, so its `src/generated` absorbed metadata belonging to - * unrelated parts of the repository — one adopter's web app went from 376 files to 831, - * the surplus being another module's server-side prompt payload DTOs. It fails OPEN - * (`tsc` passes, tests pass), so the only symptom is a directory that quietly doubled. - * - * The rule: an ancestor `.metaobjects/config.json` is the DEFAULT for a package that - * declares no sources of its own, never an ADDITION to one that does. So when the TS - * config sits somewhere the collection did not, that directory is re-resolved as a - * collection in its own right, and it wins if it actually resolves any metadata. - * - * It can only ever NARROW, and only in a shape that could not have worked before: - * - the two directories coincide (every `meta init` project, and every run from a - * project root) — returns the original, untouched, without a second resolve; - * - the sub-project declares no sources — the pinned resolve throws - * `ERR_SOURCE_UNRESOLVED` or comes back empty, and the ancestor stands, so a - * package that genuinely lives off an ancestor tree keeps working; - * - the sub-project has its own metadata — it generates from exactly that, which is - * what it did before source resolution learned to walk upward. - * - * Deliberately NOT applied to `.metaobjects/` STATE. Migrations, snapshots and the - * operational block stay keyed on the discovered collection's directory (#326 settled - * that); this narrows what is LOADED, and nothing about where state lives. - */ -export async function resolveGenCollection( - collection: Collection, - genConfigDir: string, -): Promise { - if (resolve(genConfigDir) === resolve(collection.configDir)) return collection; - try { - const pinned = await resolveCollection(genConfigDir, { explicitDir: genConfigDir }); - return pinned.files.length > 0 ? pinned : collection; - } catch { - // The sub-project declares nothing resolvable of its own — inherit, exactly as a - // package with no config always has. - return collection; - } -} +// `resolveGenConfigDir` and `resolveGenCollection` live in a leaf module so the `meta gen` +// skip check (ADR-0062) can resolve them before this module and its config loader load. +export { resolveGenCollection, resolveGenConfigDir } from "./gen-collection.js"; /** * A `metaobjects.config.ts` that still sets column naming (ADR-0058). Its own class because diff --git a/server/typescript/packages/cli/test/gen-docs-site.test.ts b/server/typescript/packages/cli/test/gen-docs-site.test.ts index ee722f1a0c..13e2884db5 100644 --- a/server/typescript/packages/cli/test/gen-docs-site.test.ts +++ b/server/typescript/packages/cli/test/gen-docs-site.test.ts @@ -8,6 +8,7 @@ import { existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { run } from "../src/index.js"; +import { FINGERPRINT_FILE } from "../src/lib/gen-fingerprint.js"; const META = { "metadata.root": { @@ -145,4 +146,21 @@ describe("meta gen with docsSiteFile()", () => { expect(await readFile(join(root, "docs-out", "site", "index.html"), "utf8")).toBe(first); expect(await run(["verify", "--codegen", "--cwd", root])).toBe(0); }); + + test("a comment-only edit to a YAML metadata file makes gen render again, since the site reads comments", async () => { + const root = await project(META, config("")); + await rm(join(root, "metaobjects", "meta.json")); + const yaml = (comment: string): string => + `metadata.root:\n package: acme::site\n children:\n ${comment}\n - object.value:\n name: Welcome\n children:\n - field.string: { name: name }\n`; + const file = join(root, "metaobjects", "meta.site.yaml"); + await writeFile(file, yaml("# first wording"), "utf8"); + expect(await run(["gen", "--cwd", root])).toBe(0); + const stored = join(root, ".metaobjects", ".gen-state", FINGERPRINT_FILE); + const first = await readFile(stored, "utf8"); + expect(await run(["gen", "--cwd", root])).toBe(0); + expect(await readFile(stored, "utf8")).toBe(first); + await writeFile(file, yaml("# second wording"), "utf8"); + expect(await run(["gen", "--cwd", root])).toBe(0); + expect(await readFile(stored, "utf8")).not.toBe(first); + }, 30_000); }); diff --git a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts new file mode 100644 index 0000000000..37bc1edb10 --- /dev/null +++ b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts @@ -0,0 +1,370 @@ +// ADR-0062 — the shared case table, `fixtures/codegen-skip-conformance/cases.json`, run +// against a TypeScript project: run `meta gen` once, apply each case's change, then ask +// the skip decision `meta gen` makes (after loading the model, before rendering) and the +// one a local `verify --codegen` makes. +// +// A case id this runner does not know fails, so a case added to the table reaches this +// port at once. +import { afterAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, writeFileSync } from "node:fs"; +import * as fs from "node:fs"; +import { join, resolve } from "node:path"; +import { genCommand } from "../src/commands/gen.js"; +import { run } from "../src/index.js"; +import { parseGenArgs } from "../src/lib/args.js"; +import { genMaySkip } from "../src/lib/gen-skip.js"; +import { + FINGERPRINT_FILE, computeGenInputs, decideGenSkip, decideVerifyNoDrift, isCi, withModel, + type FingerprintEntry, type GenSelection, +} from "../src/lib/gen-fingerprint.js"; +import { collectionLoadOptions } from "../src/lib/collection-load-options.js"; +import { loadMemory, resolveCollection } from "@metaobjectsdev/sdk"; +import { modelHashTree } from "@metaobjectsdev/codegen-ts"; + +const CASES = JSON.parse(readFileSync( + resolve(import.meta.dirname, "../../../../../fixtures/codegen-skip-conformance/cases.json"), "utf-8", +)) as { cases: { id: string; gen: "skip" | "regenerate"; verify: "may-answer-no-drift" | "must-render" }[] }; + +// Inside the monorepo, so the config's `@metaobjectsdev/*` imports resolve as in the other +// command tests. +const WORKSPACE_TMP = resolve(import.meta.dirname, "fixtures/__tmp__"); +const made: string[] = []; +afterAll(() => { for (const d of made) rmSync(d, { recursive: true, force: true }); }); + +const AUDITED = (extra: unknown[] = []) => ({ + "object.entity": { + name: "Audited", + abstract: true, + children: [{ "field.string": { name: "note" } }, ...extra], + }, +}); + +const entity = (name: string, table: string, parent?: string) => ({ + "object.entity": { + name, + ...(parent !== undefined ? { extends: parent } : {}), + children: [ + { "source.rdb": { "@table": table } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "title" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + ], + }, +}); + +const meta = (pkg: string, ...children: unknown[]) => + JSON.stringify({ "metadata.root": { package: pkg, children } }, null, 2) + "\n"; + +const OWNED = `import { appendFileSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +/** An owned generator that reads a file of its own, declared as an extra input. */ +export function mine(opts: { cache?: boolean } = {}) { + return { + name: "mine", + inputs: ["extra.txt"], + ...(opts.cache === false ? { cache: false } : {}), + generate(ctx: { inputRoot?: string; projectRoot?: string }) { + const dir = ctx.inputRoot ?? ctx.projectRoot ?? "."; + // A tally of renders, so a test can tell a skipped run from one that rendered. + appendFileSync(join(dir, "renders.log"), "x"); + const text = readFileSync(join(dir, "extra.txt"), "utf-8"); + if (text.includes("boom")) throw new Error("boom"); + return [{ path: "mine.txt", content: text }]; + }, + }; +} +`; + +const config = (mineArgs = "") => `import { defineConfig } from "@metaobjectsdev/codegen-ts"; +import { mine } from "./codegen/generators/mine"; +export default defineConfig({ + outDir: "generated", + dialect: "sqlite", + dbImport: "~/db", + extStyle: "none", + generators: ["entity", mine(${mineArgs})], +}); +`; + +interface Project { root: string; } + +function makeProject(opts: { uncacheable?: boolean } = {}): Project { + mkdirSync(WORKSPACE_TMP, { recursive: true }); + const root = mkdtempSync(join(WORKSPACE_TMP, "gen-skip-")); + made.push(root); + mkdirSync(join(root, ".git")); + mkdirSync(join(root, "metaobjects")); + mkdirSync(join(root, ".metaobjects")); + mkdirSync(join(root, "templates")); + mkdirSync(join(root, "codegen", "generators"), { recursive: true }); + writeFileSync(join(root, "metaobjects", "meta.shop.json"), meta("shop", entity("Order", "orders", "Audited"))); + writeFileSync(join(root, "metaobjects", "meta.audit.json"), meta("shop", AUDITED())); + writeFileSync(join(root, "metaobjects", "meta.crm.json"), meta("crm", entity("Customer", "customers"))); + writeFileSync(join(root, ".metaobjects", "config.json"), JSON.stringify({ schema_version: 1, sources: [] }, null, 2) + "\n"); + writeFileSync(join(root, "templates", "note.mustache"), "{{name}}\n"); + writeFileSync(join(root, "codegen", "generators", "mine.ts"), OWNED); + writeFileSync(join(root, "extra.txt"), "extra\n"); + writeFileSync(join(root, "README.md"), "a project\n"); + writeFileSync(join(root, "metaobjects.config.ts"), config(opts.uncacheable === true ? "{ cache: false }" : "")); + return { root }; +} + +const quiet = async (fn: () => Promise): Promise => { + const log = console.log; const err = console.error; + console.log = () => {}; console.error = () => {}; + try { return await fn(); } finally { console.log = log; console.error = err; } +}; + +const gen = (p: Project, args: string[] = []) => quiet(() => genCommand(args, p.root, "text")); +const stateFile = (p: Project) => join(p.root, ".metaobjects", ".gen-state", FINGERPRINT_FILE); + +/** The inputs `meta gen` and `verify` decide from: the generator half, then the loaded model. */ +async function inputsFor(p: Project, selection: GenSelection, engine?: FingerprintEntry[]) { + const c = await resolveCollection(p.root); + const root = await loadMemory(c.configDir, collectionLoadOptions(c)); + return withModel(computeGenInputs(p.root, c, c, selection, engine), modelHashTree(root)); +} + +const selectionOf = (flags: ReturnType): GenSelection => ({ + entities: flags.entities, generators: flags.generators, strict: flags.strict, baseline: flags.baseline, +}); + +async function genSkips(p: Project, r: Runner): Promise { + const flags = parseGenArgs(r.args ?? []); + if (!genMaySkip(flags)) return false; + return decideGenSkip(await inputsFor(p, selectionOf(flags), r.engine)).skip; +} + +/** + * The local `verify --codegen` shortcut. `full` is verify's spelling of `--force`. Verify + * itself takes no selection flags, so a changed selection is asked as the shortcut sees it: + * inputs read with that selection against the key the default run stored. + */ +async function verifyMayAnswer(p: Project, r: Runner): Promise { + if (r.full === true || isCi(r.env ?? {})) return false; + const flags = parseGenArgs(r.args?.filter((a) => a !== "--force") ?? []); + return decideVerifyNoDrift(await inputsFor(p, selectionOf(flags), r.engine)).skip; +} + +/** One case: what to change, and how to ask afterwards. */ +interface Runner { + uncacheable?: boolean; + change?: (p: Project) => void | Promise; + args?: string[]; + env?: NodeJS.ProcessEnv; + engine?: FingerprintEntry[]; + /** `verify --codegen --full`. */ + full?: boolean; +} + +const append = (path: string, text: string) => writeFileSync(path, readFileSync(path, "utf-8") + text); + +const RUNNERS: Record = { + "no-change": {}, + "metadata-touched": { + change: (p) => { + const f = join(p.root, "metaobjects", "meta.shop.json"); + writeFileSync(f, readFileSync(f)); + const later = new Date(Date.now() + 60_000); + utimesSync(f, later, later); + }, + }, + "unrelated-file-edited": { change: (p) => append(join(p.root, "README.md"), "more\n") }, + "metadata-reformatted": { + // Same content, no indentation, every object's keys in reverse order. + change: (p) => { + const f = join(p.root, "metaobjects", "meta.shop.json"); + const reverse = (v: unknown): unknown => Array.isArray(v) ? v.map(reverse) + : v !== null && typeof v === "object" + ? Object.fromEntries(Object.entries(v).reverse().map(([k, x]) => [k, reverse(x)])) + : v; + writeFileSync(f, JSON.stringify(reverse(JSON.parse(readFileSync(f, "utf-8"))))); + }, + }, + "metadata-moved": { + change: (p) => { + unlinkSync(join(p.root, "metaobjects", "meta.crm.json")); + writeFileSync(join(p.root, "metaobjects", "meta.customers.json"), meta("crm", entity("Customer", "customers"))); + }, + }, + "metadata-edited": { + change: (p) => writeFileSync(join(p.root, "metaobjects", "meta.shop.json"), + meta("shop", entity("Order", "orders", "Audited"), entity("Invoice", "invoices"))), + }, + "metadata-added": { change: (p) => writeFileSync(join(p.root, "metaobjects", "meta.billing.json"), meta("billing", entity("Bill", "bills"))) }, + "metadata-removed": { change: (p) => unlinkSync(join(p.root, "metaobjects", "meta.crm.json")) }, + "parent-edited": { + change: (p) => writeFileSync(join(p.root, "metaobjects", "meta.audit.json"), + meta("shop", AUDITED([{ "field.string": { name: "reason" } }]))), + }, + "config-edited": { change: (p) => writeFileSync(join(p.root, "metaobjects.config.ts"), config().replace('"entity", ', "")) }, + "project-config-edited": { + change: (p) => writeFileSync(join(p.root, ".metaobjects", "config.json"), + JSON.stringify({ schema_version: 1, sources: [], libraries: [] }, null, 2) + "\n"), + }, + "template-edited": { change: (p) => append(join(p.root, "templates", "note.mustache"), "{{title}}\n") }, + "template-added": { change: (p) => writeFileSync(join(p.root, "templates", "other.mustache"), "x\n") }, + "owned-generator-edited": { change: (p) => append(join(p.root, "codegen", "generators", "mine.ts"), "// edited\n") }, + "engine-changed": { engine: [{ kind: "engine", name: "@metaobjectsdev/cli/package.json", hash: "a-different-engine" }] }, + "selection-changed": { args: ["--strict"] }, + "declared-extra-edited": { change: (p) => append(join(p.root, "extra.txt"), "more\n") }, + "uncacheable-generator": { uncacheable: true }, + "generated-file-deleted": { change: (p) => unlinkSync(join(p.root, "generated", "mine.txt")) }, + "generated-file-edited": { change: (p) => append(join(p.root, "generated", "mine.txt"), "hand edit\n") }, + "hand-edit-kept": { + change: async (p) => { + append(join(p.root, "generated", "mine.txt"), "hand edit\n"); + expect(await gen(p)).toBe(0); + expect(readFileSync(join(p.root, "generated", "mine.txt"), "utf-8")).toContain("hand edit"); + }, + }, + "fingerprint-missing": { change: (p) => unlinkSync(stateFile(p)) }, + "force": { args: ["--force"], full: true }, + "ci": { env: { CI: "true" } }, + "failed-run": { + change: async (p) => { + const extra = join(p.root, "extra.txt"); + const before = readFileSync(extra); + writeFileSync(extra, "boom\n"); + expect(await gen(p)).not.toBe(0); + writeFileSync(extra, before); + }, + }, +}; + +describe("codegen-skip-conformance (ADR-0062)", () => { + test("every case in the table has a runner, and every runner a case", () => { + expect(CASES.cases.map((c) => c.id).sort()).toEqual(Object.keys(RUNNERS).sort()); + }); + + for (const c of CASES.cases) { + test(`${c.id}: gen ${c.gen}, verify ${c.verify}`, async () => { + const runner = RUNNERS[c.id]; + if (runner === undefined) throw new Error(`no runner for case "${c.id}"`); + const p = makeProject({ uncacheable: runner.uncacheable === true }); + expect(await gen(p)).toBe(0); + expect(existsSync(stateFile(p))).toBe(runner.uncacheable !== true); + await runner.change?.(p); + expect(await genSkips(p, runner)).toBe(c.gen === "skip"); + expect(await verifyMayAnswer(p, runner)).toBe(c.verify === "may-answer-no-drift"); + }, 30_000); + } +}); + +describe("meta gen with nothing changed (ADR-0062)", () => { + test("renders nothing and writes nothing: no file, the manifest and the stored key included", async () => { + const p = makeProject(); + expect(await gen(p)).toBe(0); + const watched = [ + join(p.root, "generated", "mine.txt"), + join(p.root, ".metaobjects", ".gen-state", ".hashes.json"), + stateFile(p), + ]; + const before = watched.map((f) => statSync(f).mtimeMs); + const renders = readFileSync(join(p.root, "renders.log"), "utf-8"); + await new Promise((r) => setTimeout(r, 20)); + expect(await gen(p)).toBe(0); + expect(watched.map((f) => statSync(f).mtimeMs)).toEqual(before); + expect(readFileSync(join(p.root, "renders.log"), "utf-8")).toBe(renders); + // --force renders again. + expect(await gen(p, ["--force"])).toBe(0); + expect(readFileSync(join(p.root, "renders.log"), "utf-8").length).toBeGreaterThan(renders.length); + }, 30_000); + + test("a full run that changes nothing rewrites no generated file and no manifest", async () => { + const p = makeProject(); + expect(await gen(p)).toBe(0); + const watched = [ + join(p.root, "generated", "mine.txt"), + join(p.root, ".metaobjects", ".gen-state", ".hashes.json"), + ]; + const before = watched.map((f) => statSync(f).mtimeMs); + await new Promise((r) => setTimeout(r, 20)); + expect(await gen(p, ["--force"])).toBe(0); + expect(watched.map((f) => statSync(f).mtimeMs)).toEqual(before); + expect(existsSync(stateFile(p))).toBe(true); + }, 30_000); + + test("a run after an input change regenerates and stores a new fingerprint", async () => { + const p = makeProject(); + expect(await gen(p)).toBe(0); + const firstKey = readFileSync(stateFile(p), "utf-8"); + writeFileSync(join(p.root, "extra.txt"), "changed\n"); + expect(await gen(p)).toBe(0); + expect(readFileSync(join(p.root, "generated", "mine.txt"), "utf-8")).toBe("changed\n"); + expect(readFileSync(stateFile(p), "utf-8")).not.toBe(firstKey); + expect(await genSkips(p, {})).toBe(true); + }, 30_000); + + test("--dry-run neither skips nor stores a fingerprint", async () => { + const p = makeProject(); + expect(await gen(p, ["--dry-run"])).toBe(0); + expect(existsSync(stateFile(p))).toBe(false); + }, 30_000); +}); + +describe("an output outside the project root (ADR-0062)", () => { + test("a deleted output there makes the next gen and the local verify shortcut render", async () => { + const p = makeProject(); + const outside = mkdtempSync(join(WORKSPACE_TMP, "gen-skip-out-")); + made.push(outside); + writeFileSync(join(p.root, "metaobjects.config.ts"), + config().replace('outDir: "generated"', `outDir: ${JSON.stringify(outside)}`)); + expect(await gen(p)).toBe(0); + expect(existsSync(join(outside, "mine.txt"))).toBe(true); + expect(await genSkips(p, {})).toBe(true); + + unlinkSync(join(outside, "mine.txt")); + + expect(await genSkips(p, {})).toBe(false); + expect(await verifyMayAnswer(p, {})).toBe(false); + expect(await gen(p)).toBe(0); + expect(existsSync(join(outside, "mine.txt"))).toBe(true); + }, 30_000); +}); + +describe("an orphan the sweep refuses to delete (ADR-0062)", () => { + test("stores no key, so the next gen runs again and repeats the refusal", async () => { + const p = makeProject(); + expect(await gen(p)).toBe(0); + expect(existsSync(stateFile(p))).toBe(true); + const orphan = join(p.root, "generated", "Customer.ts"); + expect(existsSync(orphan)).toBe(true); + append(orphan, "// mine\n"); + unlinkSync(join(p.root, "metaobjects", "meta.crm.json")); + + expect(await gen(p)).toBe(0); + expect(existsSync(orphan)).toBe(true); + expect(existsSync(stateFile(p))).toBe(false); + expect(await genSkips(p, {})).toBe(false); + }, 30_000); +}); + +describe("verify --codegen renders in memory (ADR-0062)", () => { + test("a full render writes no temp tree and no file anywhere", async () => { + const p = makeProject(); + expect(await gen(p)).toBe(0); + const scratch = mkdtempSync(join(WORKSPACE_TMP, "verify-scratch-")); + made.push(scratch); + const saved = { TMPDIR: process.env.TMPDIR, DEV_SCRATCH: process.env.DEV_SCRATCH }; + process.env.TMPDIR = scratch; + process.env.DEV_SCRATCH = scratch; + const genState = join(p.root, ".metaobjects", ".gen-state"); + const before = fs.readdirSync(genState).map((f) => [f, statSync(join(genState, f)).mtimeMs]); + try { + expect(await quiet(() => run(["verify", "--cwd", p.root, "--codegen", "--full"]))).toBe(0); + // A hand edit is still found, in memory. + append(join(p.root, "generated", "mine.txt"), "x\n"); + await quiet(() => run(["verify", "--cwd", p.root, "--codegen", "--full"])); + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + } + // `jiti`, the config loader's own transpile cache, is the only thing allowed there. + expect(fs.readdirSync(scratch).filter((f) => f !== "jiti")).toEqual([]); + expect(fs.readdirSync(genState).map((f) => [f, statSync(join(genState, f)).mtimeMs])).toEqual(before); + }, 60_000); +}); + diff --git a/server/typescript/packages/cli/test/integration/advanced-modeling-drift.test.ts b/server/typescript/packages/cli/test/integration/advanced-modeling-drift.test.ts index 6dce21f34e..f62f17ab2a 100644 --- a/server/typescript/packages/cli/test/integration/advanced-modeling-drift.test.ts +++ b/server/typescript/packages/cli/test/integration/advanced-modeling-drift.test.ts @@ -14,7 +14,7 @@ // the reference implementation, docs, and agent-context all cite. // // Runs against the REAL example directory in place (read-only from this -// gate's perspective — `verify` only writes to a throwaway temp tree), the +// gate's perspective — `verify` renders in memory and writes nothing), the // same directory a contributor edits and `cd`s into to run `meta gen`/`meta // verify` by hand. No fixture copy: the whole point is proving the COMMITTED // tree, not a copy of it. diff --git a/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts b/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts index 144991a8c0..98e11b5c6b 100644 --- a/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts +++ b/server/typescript/packages/cli/test/integration/eject-shared-model.test.ts @@ -225,7 +225,7 @@ describe("shared-model — published by an owned copy, verified by a consumer", // `meta verify --codegen` could not run this generator at all, packaged or owned: it // regenerated without the project's source files ("no source files to load") and read - // the version default from the temp tree it writes into. Both are what `meta gen` gives + // the version default from the temp tree it then wrote into. Both are what `meta gen` gives // the generator, so the gate now gives them too. test("the codegen drift gate runs the packaged generator as `meta gen` does: the project's files and its package.json version", async () => { const { root, publisher } = setupProjects(); @@ -264,12 +264,16 @@ describe("shared-model — published by an owned copy, verified by a consumer", const source = readFileSync(copy, "utf8"); const lookup = "const version = opts.version ?? nearestPackageVersion(ctx.inputRoot ?? ctx.projectRoot ?? process.cwd());"; expect(source).toContain(lookup); + // A file the copy reads that the gen skip key does not cover is declared as an input + // (ADR-0062), so editing it makes `gen` and a local `verify --codegen` render again. writeFileSync( copy, - source.replace( - lookup, - 'const version = opts.version ?? readFileSync(join(ctx.inputRoot ?? ctx.projectRoot ?? process.cwd(), "VERSION"), "utf-8").trim();', - ), + source + .replace( + lookup, + 'const version = opts.version ?? readFileSync(join(ctx.inputRoot ?? ctx.projectRoot ?? process.cwd(), "VERSION"), "utf-8").trim();', + ) + .replace('name: "shared-model",', 'name: "shared-model",\n inputs: ["VERSION"],'), ); expect(await meta(publisher, "gen")).toMatchObject({ exit: 0 }); @@ -278,7 +282,7 @@ describe("shared-model — published by an owned copy, verified by a consumer", // The artifact is the pinned one still: the version is the manifest's, not the document's. expect(owned.artifact.equals(PINNED_ARTIFACT)).toBe(true); - // The drift gate regenerates in a temp tree, and `ctx.inputRoot` is still the PROJECT, + // The drift gate regenerates in memory, and `ctx.inputRoot` is still the PROJECT, // so the copy's own `VERSION` lookup resolves there too: clean now, and convicted when // the file moves on. expect(await meta(publisher, "verify", "--codegen")).toMatchObject({ exit: 0 }); diff --git a/server/typescript/packages/cli/test/unit/args-gen.test.ts b/server/typescript/packages/cli/test/unit/args-gen.test.ts index c19bf66f04..3d0399d1a9 100644 --- a/server/typescript/packages/cli/test/unit/args-gen.test.ts +++ b/server/typescript/packages/cli/test/unit/args-gen.test.ts @@ -11,10 +11,15 @@ describe("parseGenArgs", () => { list: false, probe: false, noAntipatterns: false, strict: false, + force: false, limit: DEFAULT_ADVISORY_LIMIT, }); }); + test("--force", () => { + expect(parseGenArgs(["--force"]).force).toBe(true); + }); + test("--strict", () => { expect(parseGenArgs(["--strict"]).strict).toBe(true); }); 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 fe758ff27a..b4e97928ff 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, 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, full: false, docs: false, deps: 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, 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, full: false, docs: false, deps: 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, 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, full: false, docs: false, deps: 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, 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, full: false, docs: false, deps: 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, 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, full: false, docs: false, deps: 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/unit/config-resolver.test.ts b/server/typescript/packages/cli/test/unit/config-resolver.test.ts index 78ed3469c6..ad933d7d20 100644 --- a/server/typescript/packages/cli/test/unit/config-resolver.test.ts +++ b/server/typescript/packages/cli/test/unit/config-resolver.test.ts @@ -22,13 +22,13 @@ describe("resolveGenConfig", () => { // outDir/dialect/dbImport/extStyle. Only dryRun + entities come from flags. test("passes dryRun and entities through", () => { - const resolved = resolveGenConfig({ dryRun: true, entities: ["User", "Post"], baseline: "default", list: false, probe: false, noAntipatterns: false, strict: false, limit: DEFAULT_ADVISORY_LIMIT }); + const resolved = resolveGenConfig({ dryRun: true, entities: ["User", "Post"], baseline: "default", list: false, probe: false, noAntipatterns: false, strict: false, force: false, limit: DEFAULT_ADVISORY_LIMIT }); expect(resolved.dryRun).toBe(true); expect(resolved.entities).toEqual(["User", "Post"]); }); test("defaults: dryRun false, entities empty", () => { - const resolved = resolveGenConfig({ dryRun: false, entities: [], baseline: "default", list: false, probe: false, noAntipatterns: false, strict: false, limit: DEFAULT_ADVISORY_LIMIT }); + const resolved = resolveGenConfig({ dryRun: false, entities: [], baseline: "default", list: false, probe: false, noAntipatterns: false, strict: false, force: false, limit: DEFAULT_ADVISORY_LIMIT }); expect(resolved.dryRun).toBe(false); expect(resolved.entities).toEqual([]); }); diff --git a/server/typescript/packages/codegen-ts/src/generator.ts b/server/typescript/packages/codegen-ts/src/generator.ts index 93c86ad4ec..8453eb377f 100644 --- a/server/typescript/packages/codegen-ts/src/generator.ts +++ b/server/typescript/packages/codegen-ts/src/generator.ts @@ -156,6 +156,27 @@ export interface Generator { * The same setting, by the same name, exists in every port. */ handEdits?: HandEdits; + /** + * ADR-0062 — `false` when this generator reads something `meta gen` cannot fingerprint + * (the network, an environment variable, a file it cannot name in advance). A run that + * includes it never skips. Default `true`: what a generator reads from the model, its + * options, the config and the project's `templates/` and `codegen/` directories is + * already in the fingerprint. + */ + cache?: boolean; + /** + * ADR-0062 — further files or directories this generator reads, relative to the project + * root (a directory counts every file under it). Their contents join the fingerprint, so + * editing one makes the next `meta gen` regenerate instead of skipping. + */ + inputs?: readonly string[]; + /** + * ADR-0062 — `true` when this generator reads the raw metadata source files beside the + * loaded model (their comments, say), which the model hash does not carry. The files under + * the run's metadata source roots join the fingerprint, so a comment-only edit makes the + * next `meta gen` regenerate instead of skipping. + */ + readsMetadataSources?: boolean; /** Marks the OPT-IN Hono routes generator (routesFileHono). The runner * aggregates this across the active suite into `ctx.config.includeHonoRoutes`, * so a generator that documents the API surface (api-docs) can AUTO-DETECT diff --git a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts index 213ce576bf..d0c158bde6 100644 --- a/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/docs-site-file.ts @@ -51,6 +51,10 @@ export const docsSiteFile = function docsSiteFile(opts?: DocsSiteFileOpts): Gene return { name: "docs-site", target: opts?.target ?? DOCS_TARGET_NAME, + readsMetadataSources: true, + // ADR-0062: the prompts directory is read beside the model. `templates/` and the owned + // copy under `codegen/` are fingerprinted for every run already. + ...(opts?.prompts !== undefined ? { inputs: [opts.prompts] } : {}), async generate(ctx) { const project = ctx.inputRoot ?? ctx.projectRoot ?? process.cwd(); if (ctx.sourceRoots === undefined || ctx.sourceRoots.length === 0) { diff --git a/server/typescript/packages/codegen-ts/src/index.ts b/server/typescript/packages/codegen-ts/src/index.ts index b696f9f0ec..e5b57a90e5 100644 --- a/server/typescript/packages/codegen-ts/src/index.ts +++ b/server/typescript/packages/codegen-ts/src/index.ts @@ -96,6 +96,7 @@ export { decideAndWrite, GitMissingError, WRITE_STATUSES } from "./overwrite-pol // written — which is how the gate scopes itself to its own output instead of // convicting every stranger's file that happens to sit in the same directory. export { contentHash, readGeneratedHash, listGeneratedPaths } from "./overwrite-policy.js"; +export { modelHashTree, MODEL_HASH_FORMAT, type ModelHashTree, type ModelHashNode } from "./model-hash.js"; export { CodegenError } from "./errors.js"; export { GENERATED_HEADER, GENERATED_EDIT_NOTE, NAMES_FILE_SUFFIX, DEFAULT_OUT_DIR, RETIRED_CODEGEN_ATTRS, sidecarLine, type RetiredCodegenAttr } from "./constants.js"; diff --git a/server/typescript/packages/codegen-ts/src/model-hash.ts b/server/typescript/packages/codegen-ts/src/model-hash.ts new file mode 100644 index 0000000000..5b47e11b1d --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/model-hash.ts @@ -0,0 +1,69 @@ +// ADR-0062 §3 — the model half of the `meta gen` skip key, computed from the LOADED model. +// +// Each root-level node is hashed in its canonical EFFECTIVE form (the serializer the +// conformance corpus pins: `extends` and overlays applied, attributes in fixed order, no +// source positions). So reformatting a metadata file, reordering its keys, or moving an +// object to another file leaves the key alone, while editing an abstract parent changes the +// key of every node that inherits from it. +// +// Node hashes roll up into one hash per package and one for the model. The whole tree is +// returned, not just the top: a per-object or per-package key (one generator over one unit) +// reuses the same node and package hashes. +import { createHash } from "node:crypto"; +import { canonicalSerializeEffective, type MetaData } from "@metaobjectsdev/metadata"; + +/** Bumped whenever how a node is hashed changes, so a stored key never matches across it. */ +export const MODEL_HASH_FORMAT = 1; + +export interface ModelHashNode { + /** `type.subType` and the node's effective qualified name: unique among root children. */ + key: string; + package: string; + hash: string; +} + +export interface ModelHashTree { + nodes: ModelHashNode[]; + /** Package name ("" for none) to the hash of its nodes. */ + packages: Map; + model: string; +} + +function sha256(text: string): string { + return createHash("sha256").update(text).digest("hex"); +} + +/** Fold `name hash` lines, sorted, so discovery order never matters. */ +function fold(label: string, lines: string[]): string { + return sha256(`${label} ${MODEL_HASH_FORMAT}\n${[...lines].sort().join("\n")}\n`); +} + +function packageOf(node: MetaData): string { + const key = node.resolutionKey(); + const i = key.lastIndexOf("::"); + return i < 0 ? "" : key.slice(0, i); +} + +/** Hash the loaded model: every root-level node, then each package, then the model. */ +export function modelHashTree(root: MetaData): ModelHashTree { + const nodes: ModelHashNode[] = root.children().map((node) => ({ + key: `${node.type}.${node.subType}:${node.resolutionKey()}`, + package: packageOf(node), + hash: sha256(canonicalSerializeEffective(node)), + })); + const byPackage = new Map(); + for (const n of nodes) { + const lines = byPackage.get(n.package) ?? []; + lines.push(`${n.key}\t${n.hash}`); + byPackage.set(n.package, lines); + } + const packages = new Map(); + for (const [pkg, lines] of byPackage) packages.set(pkg, fold("metaobjects-package", lines)); + // The root's own attributes (anything set on the root itself rather than on a node). + const rootAttrs = [...root.attrs()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); + const model = fold("metaobjects-model", [ + ...[...packages].map(([pkg, h]) => `${pkg}\t${h}`), + `(root)\t${sha256(JSON.stringify(rootAttrs))}`, + ]); + return { nodes, packages, model }; +} diff --git a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts index a1b0d45b55..038a46ec6e 100644 --- a/server/typescript/packages/codegen-ts/src/overwrite-policy.ts +++ b/server/typescript/packages/codegen-ts/src/overwrite-policy.ts @@ -174,18 +174,86 @@ function entryHash(value: unknown): string | undefined { return undefined; } -function loadHashes(genStateDir: string): HashesFile { +function hashesOf(raw: Record): HashesFile { const hashes: HashesFile = {}; - for (const [key, value] of Object.entries(readRawManifest(genStateDir))) { + for (const [key, value] of Object.entries(raw)) { const hash = entryHash(value); if (hash !== undefined) hashes[key] = hash; } return hashes; } +/** + * The manifest held in memory for one run (ADR-0062 §1). `.hashes.json` is read once when + * the run opens the batch and written once when it closes it, and only when an entry was + * added, changed or removed. Without it every recorded file re-read, re-sorted and rewrote + * the whole manifest: at 1,160 objects that was 136 s of a 165 s run, and a run that changed + * nothing still moved the file's timestamp. + */ +interface ManifestBatch { + genStateDir: string; + /** The manifest as read when the batch opened; its object entries' extra fields are kept. */ + raw: Record; + hashes: HashesFile; + dirty: boolean; +} + +let activeBatch: ManifestBatch | undefined; + +function batchFor(genStateDir: string): ManifestBatch | undefined { + return activeBatch !== undefined && activeBatch.genStateDir === resolve(genStateDir) ? activeBatch : undefined; +} + +/** + * Hold `genStateDir`'s manifest in memory until {@link endManifestBatch}. Every read and + * write of that manifest in between goes to the in-memory copy. The runner opens one batch + * per run; a direct `decideAndWrite` caller that opens none still gets a correct manifest, + * written per call and only when it changed. + */ +export function beginManifestBatch(genStateDir: string): void { + const raw = readRawManifest(genStateDir); + activeBatch = { genStateDir: resolve(genStateDir), raw, hashes: hashesOf(raw), dirty: false }; +} + +/** Write the batched manifest once, if anything in it changed, and close the batch. */ +export function endManifestBatch(): void { + const batch = activeBatch; + activeBatch = undefined; + if (batch?.dirty === true) writeManifest(batch.genStateDir, batch.raw, batch.hashes); +} + +function loadHashes(genStateDir: string): HashesFile { + // Inside a batch this is the live in-memory copy, not a clone: a clone per call would + // bring back the per-file cost the batch removes. Callers that change it call + // `saveHashes` with it, which is what marks the batch dirty. + const batch = batchFor(genStateDir); + if (batch !== undefined) return batch.hashes; + return hashesOf(readRawManifest(genStateDir)); +} + +function sameHashes(a: HashesFile, b: HashesFile): boolean { + const ak = Object.keys(a); + if (ak.length !== Object.keys(b).length) return false; + return ak.every((k) => b[k] === a[k]); +} + function saveHashes(genStateDir: string, hashes: HashesFile): void { - mkdirSync(genStateDir, { recursive: true }); + const batch = batchFor(genStateDir); + if (batch !== undefined) { + if (hashes === batch.hashes) batch.dirty = true; + else if (!sameHashes(batch.hashes, hashes)) { + batch.hashes = { ...hashes }; + batch.dirty = true; + } + return; + } const raw = readRawManifest(genStateDir); + if (existsSync(join(genStateDir, HASHES_FILE)) && sameHashes(hashesOf(raw), hashes)) return; + writeManifest(genStateDir, raw, hashes); +} + +function writeManifest(genStateDir: string, raw: Record, hashes: HashesFile): void { + mkdirSync(genStateDir, { recursive: true }); // Keys SORTED, because this file is committed. Insertion order would make the // diff — and any merge conflict between two people who both regenerated — // depend on which entity happened to generate first, which is noise nobody can @@ -338,6 +406,8 @@ export function loadEngineVersion(genStateDir: string): string | undefined { /** Record the codegen engine version alongside the gen-state hashes (#232). */ export function saveEngineVersion(genStateDir: string, version: string): void { + // A run that changed nothing writes nothing (ADR-0062 §1), tool state included. + if (loadEngineVersion(genStateDir) === version) return; mkdirSync(genStateDir, { recursive: true }); writeFileSync( join(genStateDir, ENGINE_FILE), @@ -360,10 +430,16 @@ function advanceSnapshot( content: string, ): void { const dest = snapshotPath(genStateDir, relPath); - mkdirSync(dirname(dest), { recursive: true }); - writeFileSync(dest, content); + // The body is a local cache; rewriting one that already holds these bytes only moves + // its timestamp. + if (!existsSync(dest) || readFileSync(dest, "utf-8") !== content) { + mkdirSync(dirname(dest), { recursive: true }); + writeFileSync(dest, content); + } const hashes = loadHashes(genStateDir); - hashes[relPath] = sha256(content); + const hash = sha256(content); + if (hashes[relPath] === hash) return; + hashes[relPath] = hash; saveHashes(genStateDir, hashes); } @@ -458,11 +534,17 @@ function runGitMergeFile( return { exitCode, stderr: res.stderr ?? "", mergedContent }; } -/** Write `content` to a freshly-named tmpfile under the OS tmpdir; return the - * path. Caller is responsible for cleanup (acceptable for codegen — tmpdir - * is process-scoped). */ +/** The directory merge temporaries go in: `$DEV_SCRATCH` when set, else the OS temp dir. + * Exported for the test that a run leaves nothing behind there. */ +export function mergeTempDir(): string { + const scratch = process.env.DEV_SCRATCH; + return join(scratch !== undefined && scratch !== "" ? scratch : tmpdir(), "meta-gen-merge"); +} + +/** Write `content` to a freshly-named temp file in `mergeTempDir()`; return the path. The + * caller deletes it in a `finally`. */ function writeTmpfile(content: string): string { - const dir = join(tmpdir(), "meta-gen-merge"); + const dir = mergeTempDir(); mkdirSync(dir, { recursive: true }); const path = join(dir, `${Date.now()}-${randomBytes(6).toString("hex")}.tmp`); writeFileSync(path, content); @@ -528,6 +610,8 @@ type WriteCase = | { kind: "no-snapshot-refused"; hasRecord: boolean } | { kind: "no-snapshot-adopt"; currentText: string } | { kind: "snapshot-unchanged" } + | { kind: "fresh-equals-disk" } + | { kind: "snapshot-pristine-overwrite" } | { kind: "snapshot-merge-required"; snapshotText: string }; function classifyWrite( @@ -628,6 +712,13 @@ function classifyWrite( if (current === content && snapshot.text === content) { return { kind: "snapshot-unchanged" }; } + // The file already holds exactly the fresh bytes, so a merge could only rewrite it with + // the same content and move its timestamp (ADR-0062 §2). Advance the base instead. + if (current === content) return { kind: "fresh-equals-disk" }; + // The file is exactly the last generated text: nobody edited it, so there is nothing to + // merge. Write the fresh bytes directly; `git merge-file` (two temp files and a process) + // runs only for a real hand edit. + if (current === snapshot.text) return { kind: "snapshot-pristine-overwrite" }; return { kind: "snapshot-merge-required", snapshotText: snapshot.text }; } @@ -660,9 +751,11 @@ export function previewWriteStatus( case "no-snapshot-fresh-unchanged": case "no-snapshot-unchanged": case "snapshot-unchanged": + case "fresh-equals-disk": return "unchanged"; case "no-snapshot-fresh-overwrite": case "no-snapshot-pristine-overwrite": + case "snapshot-pristine-overwrite": case "hand-edit-overwrite": return "overwrite"; case "no-snapshot-refused": @@ -708,6 +801,7 @@ export function decideAndWrite( case "no-snapshot-fresh-overwrite": case "no-snapshot-pristine-overwrite": + case "snapshot-pristine-overwrite": writeFileSync(path, content); advanceSnapshot(genStateDir, relPath, content); return { path, status: "overwrite" }; @@ -756,11 +850,23 @@ export function decideAndWrite( case "snapshot-unchanged": return { path, status: "unchanged" }; - case "snapshot-merge-required": { - const baseTmp = writeTmpfile(kase.snapshotText); - const freshTmp = writeTmpfile(content); + case "fresh-equals-disk": + advanceSnapshot(genStateDir, relPath, content); + return { path, status: "unchanged" }; - const outcome = runGitMergeFile(path, baseTmp, freshTmp); + case "snapshot-merge-required": { + // The two merge inputs are temporaries, always removed, whatever the merge does. + const temps: string[] = []; + let outcome: MergeOutcome; + try { + const baseTmp = writeTmpfile(kase.snapshotText); + temps.push(baseTmp); + const freshTmp = writeTmpfile(content); + temps.push(freshTmp); + outcome = runGitMergeFile(path, baseTmp, freshTmp); + } finally { + for (const t of temps) rmSync(t, { force: true }); + } if (outcome.exitCode === 0) { // Clean merge — advance the canonical snapshot to fresh. diff --git a/server/typescript/packages/codegen-ts/src/owned-runtime.ts b/server/typescript/packages/codegen-ts/src/owned-runtime.ts index 411b045cba..0a530409a1 100644 --- a/server/typescript/packages/codegen-ts/src/owned-runtime.ts +++ b/server/typescript/packages/codegen-ts/src/owned-runtime.ts @@ -93,9 +93,8 @@ export function httpRuntimeSpecifier( * * Relative rather than absolute so the emitted imports are the same on every machine, * and computed from the two directories rather than configured, so moving `outDir` - * moves the imports with it. `meta verify --codegen` regenerates into a temp tree that - * mirrors each outDir at its project-relative path, so the path it computes there is - * the same one `meta gen` computed. + * moves the imports with it. `meta verify --codegen` renders in memory against the real + * project paths, so the path it computes there is the same one `meta gen` computed. */ export function ownedRuntimeImport( projectRoot: string, diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index b91801fa17..4cd7f3ea58 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -27,7 +27,9 @@ import { sweepOrphans, type OrphanJob } from "./orphan-sweep.js"; import { refusedOrphanMessage } from "./reconcile-orphans.js"; import { effectivePackage } from "./docs-paths.js"; import { + beginManifestBatch, decideAndWrite, + endManifestBatch, previewWriteStatus, hasHashManifest, listGeneratedPaths, @@ -205,6 +207,15 @@ export interface RunGenResult { /** The jobs the orphan sweep ran (or, on a dry run, would run) with, so a caller can * classify an orphan by `orphanVerdict` exactly as the sweep does. */ orphanSweepJobs?: readonly OrphanJob[]; + /** On a dry run only: every rendered file's absolute path and content, so a caller can + * compare the output with disk in memory (`verify --codegen`, ADR-0062) with no temp tree. */ + rendered?: ReadonlyMap; + /** The absolute paths this run wrote outside the project root. The manifest records none of + * them, so the stored skip key lists them and a later skip needs each to exist (ADR-0062). */ + outsidePaths?: readonly string[]; + /** True when the orphan sweep kept an edited orphan. Such a run is incomplete: it stores no + * skip key, so the next run repeats the warning (ADR-0062). */ + sweepRefused?: boolean; } /** @@ -362,9 +373,11 @@ export async function runGen(opts: RunGenOpts): Promise { return rel.startsWith("..") || isAbsolute(rel); }; let untrackedCount = 0; + const outsidePaths: string[] = []; const policyFor = (fullPath: string, handEdits?: HandEdits): DecideAndWriteOpts => { if (outsideProject(fullPath)) { untrackedCount++; + outsidePaths.push(fullPath); // With no record to consult, the default baseline REFUSES any existing file that // differs from fresh output — so a second run over its own earlier output refused // every changed file, the opposite of the warning below. Such a file is overwritten @@ -1133,6 +1146,7 @@ export async function runGen(opts: RunGenOpts): Promise { ] : orphanJobs; + let sweepRefused = false; const sweep = (dryRun: boolean): void => { if (projectRoot === undefined || sweepJobs.length === 0) return; @@ -1186,6 +1200,7 @@ export async function runGen(opts: RunGenOpts): Promise { writes.push({ path: join(projectRoot, relPath), status: "removed" }); } if (result.refused.length > 0) { + sweepRefused = true; // Grouped by the generator that refused, so each message names a generator the // project actually registered. `orphanPolicy` is generic and apps are encouraged // to compose their own, so one blanket message naming `requirement-tests` would @@ -1245,41 +1260,56 @@ export async function runGen(opts: RunGenOpts): Promise { // A preview that hides a pending deletion is worse than no preview at all, so // the sweep still runs — in decide-and-report mode, touching nothing. sweep(true); - return { files: writes, warnings, conflicts, handEditsOverwrite: handEditsOverwrite(), orphanSweepJobs: sweepJobs }; + return { + files: writes, + warnings, + conflicts, + handEditsOverwrite: handEditsOverwrite(), + orphanSweepJobs: sweepJobs, + rendered: new Map(emitted.map((f) => [f.fullPath, f.content])), + }; } - for (const file of emitted) { - // Key the snapshot by project-relative path so multi-target projects keep - // distinct entries (e.g. `database/Post.ts` vs `web/Post.queries.ts`). - // Without an explicit projectRoot we let decideAndWrite derive a stable - // hash-of-path key — fine for ephemeral test runs. - const result = decideAndWrite(file.fullPath, file.content, policyFor(file.fullPath, file.handEdits)); - writes.push(result); - if (result.discardedEdit === true) { - warnings.push( - `overwrote hand-edited ${relativeForDisplay(file.fullPath)} with fresh output ` + - `(handEdits: "overwrite" on ${file.generatedBy})`, - ); - } - if (result.status === "conflict") { - conflicts.push(result); - warnings.push( - `Merge conflict in ${file.fullPath}: resolve diff3 markers and re-run ` + - `'meta gen' to advance the canonical state.`, - ); + // ADR-0062 §1 — the manifest is read once here and written once below, only if an entry + // changed. The `finally` keeps a throwing write from leaving the batch open for the next + // run in this process; what it recorded before the throw is still saved. + beginManifestBatch(genStateDir); + try { + for (const file of emitted) { + // Key the snapshot by project-relative path so multi-target projects keep + // distinct entries (e.g. `database/Post.ts` vs `web/Post.queries.ts`). + // Without an explicit projectRoot we let decideAndWrite derive a stable + // hash-of-path key — fine for ephemeral test runs. + const result = decideAndWrite(file.fullPath, file.content, policyFor(file.fullPath, file.handEdits)); + writes.push(result); + if (result.discardedEdit === true) { + warnings.push( + `overwrote hand-edited ${relativeForDisplay(file.fullPath)} with fresh output ` + + `(handEdits: "overwrite" on ${file.generatedBy})`, + ); + } + if (result.status === "conflict") { + conflicts.push(result); + warnings.push( + `Merge conflict in ${file.fullPath}: resolve diff3 markers and re-run ` + + `'meta gen' to advance the canonical state.`, + ); + } + // Refusals are reported together after the loop (see reportRefusals) so a + // whole-project cause can be stated once instead of once per file. } - // Refusals are reported together after the loop (see reportRefusals) so a - // whole-project cause can be stated once instead of once per file. - } - reportRefusals(); - noteUntracked(); - reportAdoptions(); + reportRefusals(); + noteUntracked(); + reportAdoptions(); - // Sweep AFTER the writes: writing is the primary job, and a deletion that runs - // first would be unrecoverable if a later write threw. Ordering cannot change - // the decision — a path this run emitted is never an orphan either way. - sweep(false); + // Sweep AFTER the writes: writing is the primary job, and a deletion that runs + // first would be unrecoverable if a later write threw. Ordering cannot change + // the decision — a path this run emitted is never an orphan either way. + sweep(false); + } finally { + endManifestBatch(); + } // #232 — stamp the engine version that produced this snapshot, so the NEXT gen can // detect an engine change. Written after a successful run only, and only by a run that @@ -1287,7 +1317,10 @@ export async function runGen(opts: RunGenOpts): Promise { // Amendment 9), tool state included. if (installedEngine !== undefined && config.generators.length > 0) saveEngineVersion(genStateDir, installedEngine); - return { files: writes, warnings, conflicts, handEditsOverwrite: handEditsOverwrite(), orphanSweepJobs: sweepJobs }; + return { + files: writes, warnings, conflicts, handEditsOverwrite: handEditsOverwrite(), orphanSweepJobs: sweepJobs, + outsidePaths, sweepRefused, + }; } /** diff --git a/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts b/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts new file mode 100644 index 0000000000..b45c51b943 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/overwrite-policy/manifest-once.test.ts @@ -0,0 +1,123 @@ +// ADR-0062 §1 and §2: within a run the hash manifest is written once, and only when an +// entry changed; a file whose new bytes equal what is on disk is never rewritten. +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { beginManifestBatch, decideAndWrite, endManifestBatch, mergeTempDir } from "../../src/overwrite-policy.js"; + +let out: string; +let state: string; +beforeEach(() => { + out = mkdtempSync(join(tmpdir(), "codegen-once-")); + state = mkdtempSync(join(tmpdir(), "codegen-once-state-")); +}); +afterEach(() => { + rmSync(out, { recursive: true, force: true }); + rmSync(state, { recursive: true, force: true }); +}); + +const MANIFEST = () => join(state, ".hashes.json"); + +function run(files: Record): void { + beginManifestBatch(state); + try { + for (const [name, content] of Object.entries(files)) { + decideAndWrite(join(out, name), content, { genStateDir: state, outputRelPath: name }); + } + } finally { + endManifestBatch(); + } +} + +const manifestWrites = (spy: { mock: { calls: unknown[][] } }) => + spy.mock.calls.filter((c) => String(c[0]).endsWith(".hashes.json")).length; + +describe("hash manifest, once per run", () => { + test("a run that writes many files writes the manifest once", () => { + const spy = spyOn(fs, "writeFileSync"); + try { + run({ "A.ts": "a\n", "B.ts": "b\n", "C.ts": "c\n" }); + expect(manifestWrites(spy)).toBe(1); + } finally { spy.mockRestore(); } + expect(Object.keys(JSON.parse(readFileSync(MANIFEST(), "utf-8"))).sort()).toEqual(["A.ts", "B.ts", "C.ts"]); + }); + + test("a run that changes nothing does not write the manifest", () => { + run({ "A.ts": "a\n", "B.ts": "b\n" }); + const before = statSync(MANIFEST()).mtimeMs; + const spy = spyOn(fs, "writeFileSync"); + try { + run({ "A.ts": "a\n", "B.ts": "b\n" }); + expect(manifestWrites(spy)).toBe(0); + } finally { spy.mockRestore(); } + expect(statSync(MANIFEST()).mtimeMs).toBe(before); + }); +}); + +describe("identical bytes are never rewritten", () => { + test("new output equal to a file already on disk leaves it untouched", () => { + run({ "A.ts": "a\n" }); + // The file moves on by hand to exactly what the next run renders. + writeFileSync(join(out, "A.ts"), "a2\n"); + const before = statSync(join(out, "A.ts")).mtimeMs; + const spy = spyOn(fs, "writeFileSync"); + try { + run({ "A.ts": "a2\n" }); + expect(spy.mock.calls.filter((c) => String(c[0]) === join(out, "A.ts")).length).toBe(0); + } finally { spy.mockRestore(); } + expect(statSync(join(out, "A.ts")).mtimeMs).toBe(before); + expect(readFileSync(join(out, "A.ts"), "utf-8")).toBe("a2\n"); + // And the record now matches, so the next run is a plain no-change. + const spy2 = spyOn(fs, "writeFileSync"); + try { + run({ "A.ts": "a2\n" }); + expect(spy2.mock.calls.length).toBe(0); + } finally { spy2.mockRestore(); } + }); +}); + +describe("three-way merge temporaries", () => { + let scratch: string; + let saved: string | undefined; + beforeEach(() => { + scratch = mkdtempSync(join(tmpdir(), "codegen-once-scratch-")); + saved = process.env.DEV_SCRATCH; + process.env.DEV_SCRATCH = scratch; + }); + afterEach(() => { + if (saved === undefined) delete process.env.DEV_SCRATCH; else process.env.DEV_SCRATCH = saved; + rmSync(scratch, { recursive: true, force: true }); + }); + + const leftovers = () => { + const dir = mergeTempDir(); + return fs.existsSync(dir) ? fs.readdirSync(dir) : []; + }; + + test("live under $DEV_SCRATCH", () => { + expect(mergeTempDir().startsWith(scratch)).toBe(true); + }); + + test("an untouched file is overwritten without a merge: no temporaries at all", () => { + run({ "A.ts": "a\n" }); + run({ "A.ts": "a2\n" }); + expect(readFileSync(join(out, "A.ts"), "utf-8")).toBe("a2\n"); + expect(fs.existsSync(mergeTempDir())).toBe(false); + }); + + test("a hand-edited file is merged, and the run leaves nothing behind, clean or conflicted", () => { + run({ "A.ts": "one\ntwo\nthree\nfour\nfive\n" }); + // A hand edit at the top, a generator change at the bottom: a clean merge. + writeFileSync(join(out, "A.ts"), "ONE\ntwo\nthree\nfour\nfive\n"); + run({ "A.ts": "one\ntwo\nthree\nfour\nFIVE\n" }); + expect(readFileSync(join(out, "A.ts"), "utf-8")).toBe("ONE\ntwo\nthree\nfour\nFIVE\n"); + expect(leftovers()).toEqual([]); + // Both sides change the same line: a conflict. + writeFileSync(join(out, "A.ts"), "ONE\ntwo\nthree\nfour\nmine\n"); + run({ "A.ts": "one\ntwo\nthree\nfour\ntheirs\n" }); + expect(readFileSync(join(out, "A.ts"), "utf-8")).toContain("<<<<<<<"); + expect(leftovers()).toEqual([]); + }); +}); diff --git a/server/typescript/packages/sdk/package.json b/server/typescript/packages/sdk/package.json index 29428e2d67..154be0412a 100644 --- a/server/typescript/packages/sdk/package.json +++ b/server/typescript/packages/sdk/package.json @@ -11,6 +11,11 @@ "types": "./dist/index.d.ts", "default": "./dist/index.js" }, + "./collection": { + "bun": "./src/collection.ts", + "types": "./dist/collection.d.ts", + "default": "./dist/collection.js" + }, "./agent-context": { "bun": "./src/agent-context/index.ts", "types": "./dist/agent-context/index.d.ts", diff --git a/spec/decisions/ADR-0062-skip-codegen-when-nothing-changed.md b/spec/decisions/ADR-0062-skip-codegen-when-nothing-changed.md new file mode 100644 index 0000000000..e44028a1d6 --- /dev/null +++ b/spec/decisions/ADR-0062-skip-codegen-when-nothing-changed.md @@ -0,0 +1,119 @@ +# ADR-0062: `gen` skips rendering when the loaded model and its generators are unchanged + +## Status + +**Accepted** (2026-11-14), for the 1.2.x line, in all five ports (TypeScript, Python, C#, Java +and Kotlin). Registers no vocabulary: `metamodelVersion` is unchanged. It changes what `gen` and +a local `verify --codegen` do when nothing changed. + +## Context + +No port skipped any work when nothing changed. Every run loaded the metadata, rendered every +file, formatted where the port formats, and only then compared each file with what was on disk. +A no-change `meta gen` on a small project cost the same as a first run (0.92 to 0.98 s), and a +Maven build spent about 5 s in `metaobjects:generate` on every build, changed or not. + +Two defects made the no-change run worse than a first run: + +- Python and C# rewrote the committed hash manifest (`.metaobjects/.gen-state/.hashes.json`) + once per generated file, even when no file changed. TypeScript rewrote it once per written + file. At 1,160 objects that per-file rewrite was 136 s of a 165 s TypeScript run. Java and + Kotlin already loaded it once and saved it once, and only when something changed. +- A file whose fresh bytes equal what is on disk must never be rewritten: a rewrite moves its + timestamp, and every build tool downstream then recompiles it. + +The question this ADR answers is how to skip codegen **without generating anything**: comparing +rendered output with disk still renders every file, so it is not a skip. + +## Decision + +### 1. The manifest is written once per run, and only when it changed + +Every port loads `.hashes.json` once at the start of a run, updates it in memory, and saves it +once at the end, only when an entry was added, changed or removed. Its bytes stay as they are +today (sorted keys, two-space indentation, trailing newline, owner fields kept), so this changes +no committed file. A run that changes nothing leaves the manifest's timestamp alone. + +### 2. Identical bytes are never rewritten + +A generated file whose fresh content equals what is on disk is left untouched in every port, +whatever the manifest or snapshot says: its record is confirmed in memory and it reports +`unchanged`. Its timestamp stays, so a build tool sees nothing changed. + +### 3. The skip key is built from the loaded model, not from source files + +A run is keyed on what its generators are built from, computed after the metadata loads and +before anything renders: + +- **The model.** Each loaded root-level node (an object, a shared field, a template node) is + hashed in its canonical *effective* form, using the port's existing canonical serializer: + `extends` and overlays applied, attributes in fixed order, no source positions. Node hashes + roll up into a hash per package and one for the model. So a metadata file that is reformatted, + reordered, or split into two files without changing what loads does not change the key, and an + edit to an abstract parent changes the key of every object that inherits from it. +- **The generators.** A generator's identity is the hash of its built code, not only the release + version (a linked or locally built engine changes with its content), plus its templates, + partials, helpers and options: in practice the engine package and its MetaObjects + dependencies, the port's codegen config and every owned generator file it reaches, and the + template roots. A generator that reads anything else declares it as an extra input; one that + cannot declare its inputs is marked not cacheable (`cache: false` in TypeScript, the port's + equivalent elsewhere), and a run that includes it never skips. +- **The run.** The project config (`.metaobjects/config.json`) and every flag that changes + output: entity and generator selection, strict mode, the baseline mode. + +`gen` skips rendering when the model hash and every generator identity match the last +successful run's, and every file the manifest records still exists with the bytes that run left +on disk (the stored key records them). It still loads the metadata (that is what the key is made +of) and reads the generated files; it renders nothing and writes nothing, the manifest and the +stored key included. A generated file edited by hand after the last run therefore makes `gen` +render, so it puts the file back or merges the edit, exactly as `verify` tells the user it will; +an edit the last run already merged and kept is unchanged since, and does not. The rule the key keeps: **it may be wrong only in the safe direction.** An input +it over-counts causes an extra render; an input it misses would cause a wrong skip, so anything +in doubt is counted. Timestamps are never an input. + +The stored key lives in `.metaobjects/.gen-state/.fingerprint-.json`, which is not +committed (`.gen-state/*` is ignored except `.hashes.json`). A run deletes it before it writes +anything and stores the new one only after it succeeds with every generator cacheable, so a +failed or half-written run is never mistaken for a current one. The full run comes back with +`meta gen --force` (TypeScript), `metaobjects gen --force` (Python), `dotnet meta gen --force` +(C#) and `-Dmetaobjects.force=true` or `true` (Java and Kotlin). + +### 4. `verify --codegen` renders in CI and before a PR + +In CI (`CI` set to anything but empty, `0` or `false`) `verify --codegen` always renders and +compares everything, whatever the stored key says. Locally it may answer "no drift" without +rendering when the key matches **and** every file the manifest records still hashes to its +record; `--full` (`-Dmetaobjects.verify.full=true` on the JVM) makes it render. A file holding a +kept hand edit no longer matches its record, so `verify` renders for it and classifies it, while +`gen` skips over it. + +When `verify --codegen` renders, it compares the rendered bytes with disk in memory, in every +port: no rendered temp tree is written. + +### 5. One table of cases, run by every port + +`fixtures/codegen-skip-conformance/cases.json` lists the changes that must make `gen` render +and those that may let it skip, with what a local `verify` may do after each. Every port runs +every case against a project of its own shape and fails on a case id it does not know. + +### 6. Per-object and per-package keys come next + +This is the whole-run level. The model hash is a tree (node, package, model) and the generator +identity is a set of named entries, so the next step can key one generator over one object or +one package by reusing the same nodes. Two units claiming one output path already fail the run, +and the manifest is keyed by output path, so per-unit records will not collide. + +## Consequences + +- A no-change `gen` costs a process start, the metadata load and hashing (the model, the + generator inputs and the generated files), in every port: no render, no format, no write. +- A run that does render writes no file whose bytes are unchanged and writes the manifest at + most once, so a build tool downstream sees only real changes, and a large model no longer pays + one manifest write per file. +- TypeScript runs `git merge-file` only for a file edited by hand since it was generated, never + for an untouched one, and deletes its two temporary inputs in a `finally`, under `$DEV_SCRATCH` + when that is set. +- `gen` in Python no longer reports an unchanged file as written. +- A generator that reads something it did not declare could make a skip wrong. The defenses are + the declared extras, `cache: false`, `--force`, and CI's full `verify --codegen`. +- Nothing changes for an adopter who never runs `gen` twice without a change in between. diff --git a/spec/decisions/README.md b/spec/decisions/README.md index 02ad241caf..64f33b43c3 100644 --- a/spec/decisions/README.md +++ b/spec/decisions/README.md @@ -58,6 +58,7 @@ Write one when a decision is **cross-cutting** (affects more than one language p - [ADR-0059 — References resolve once, after the tree](ADR-0059-references-resolve-once-after-the-tree.md) — *Accepted* (sources keep references as written; one resolver per port binds them before freeze and the serializer writes them canonical; supersedes ADR-0032 §3–§4, amends ADR-0042) - [ADR-0060 — Java and Kotlin codegen decide overwrites from the committed hash manifest](ADR-0060-jvm-codegen-hash-manifest.md) — *Accepted* (the JVM plugin records each file it writes in `.metaobjects/.gen-state/.hashes.json`, refuses an edited one, and deletes an untouched orphan, owned per generator and output directory) - [ADR-0061 — A template body may use a per-port engine, chosen by its file](ADR-0061-per-port-template-engines.md) — *Accepted* (Python and TypeScript render and check Jinja bodies — `.jinja` / `.j2` / `.jinja2` — against the same payload check; the metadata never names an engine; Java, Kotlin and C# refuse Jinja with `ERR_TEMPLATE_ENGINE_UNSUPPORTED`) +- [ADR-0062 — `gen` skips rendering when the loaded model and its generators are unchanged](ADR-0062-skip-codegen-when-nothing-changed.md) — *Accepted* (every port keys a run on the loaded model and its generator inputs, and a matching key with every generated file unchanged renders and writes nothing; the manifest is written once per run; a local `verify --codegen` may answer from the key) > **Index gap — ADR-0031 through ADR-0051 are on disk but not listed above.** The index stopped > being maintained after ADR-0030; the files are authoritative, this list is not. Read From f4fe384ea491b3a735f6c07b5dab1239f9aa3858 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:21:04 -0500 Subject: [PATCH 230/267] fix(csharp): the identity-start line names the property through the resolver A key whose property the resolver renames got Property(x => x.WidgetId) in the context and a CS1061. Co-Authored-By: Claude Opus 5.5 --- .../MetaObjects.Codegen/Generators/DbContextGenerator.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 4049b04883..6dcd97f9c4 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -907,11 +907,11 @@ protected virtual IEnumerable DefaultValueConfig(MetaObject entity, Meta /// out ids live rows hold, so the generated design-time services /// () scaffold it as SQL instead. /// - private static void EmitIdentityStartConfig(string owner, MetaObject entity, List modelLines) + private void EmitIdentityStartConfig(string owner, MetaObject entity, List modelLines) { if (IdentityStartOf(entity) is not { } start) return; // One entry, one statement: the guard and its body never split across a chunk boundary. - modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().Property(x => x.{CSharpNaming.Pascal(start.Field.Name)}).HasAnnotation(" + + modelLines.Add($" if (Database.ProviderName == \"{NpgsqlProviderName}\") modelBuilder.Entity<{owner}>().Property(x => x.{PropertyName(start.Field)}).HasAnnotation(" + $"\"{NpgsqlIdentityOptionsAnnotation}\", \"'{start.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)}', '1', '', '', 'False', '1'\");"); } From 66c5f359249b6a1115ec2fb4ab3dd99bbdb78e6a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:21:06 -0500 Subject: [PATCH 231/267] fix(csharp): callable arguments, extractor targets and export cells use the resolver Co-Authored-By: Claude Opus 5.5 --- .../csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs | 2 +- .../csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs | 2 +- .../MetaObjects.Codegen/Generators/ReportExportGenerator.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs index 84f2669543..c74091cd2e 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CallableGenerator.cs @@ -98,7 +98,7 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) // placeholder under FromSqlRaw. var argProps = argsObject is null ? [] - : argsObject.OwnFields().Select(f => CSharpNaming.Pascal(f.Name)).ToList(); + : argsObject.OwnFields().Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); var sqlArgs = string.Join(", ", argProps.Select(p => $"{{args.{p}}}")); var hasArgs = argsObject is not null; diff --git a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs index a8976b86d4..01e6b14e41 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ExtractorGenerator.cs @@ -149,7 +149,7 @@ private static void EmitMapper(StringBuilder sb, MetaData vo, GenContext ctx) { // A readOnly member has a private setter on the POCO: an initializer cannot set it. if (f.IsReadOnlyMutability) continue; - sb.AppendLine($" {CSharpNaming.Pascal(f.Name)} = {StrictArg((MetaObject)vo, f, ctx)},"); + sb.AppendLine($" {CSharpNaming.PropertyName(f, ctx.Config)} = {StrictArg((MetaObject)vo, f, ctx)},"); } sb.AppendLine(" };"); } diff --git a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs index 88141f80f2..8137fc75a8 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/ReportExportGenerator.cs @@ -125,7 +125,7 @@ private string ReportModule(MetaObject report, GenContext ctx) sb.AppendLine($" public static {cell}[] Cells({cls} row) =>"); sb.AppendLine(" ["); foreach (var f in fields) - sb.AppendLine($" {writer}.Cell(row.{CSharpNaming.Pascal(f.Name)}),"); + sb.AppendLine($" {writer}.Cell(row.{CSharpNaming.PropertyName(f, ctx.Config)}),"); sb.AppendLine(" ];"); sb.AppendLine(); sb.AppendLine(" /// Writes the rows as RFC 4180 CSV."); From b6a133bbb583e2830b13f9a93a227ccde3d649a7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:21:07 -0500 Subject: [PATCH 232/267] fix(csharp): the routes name every field property through the resolver Key, sort allowlist, EF.Property names, discriminator, frozen, auto-set, value-object, create-reset and junction members. Co-Authored-By: Claude Opus 5.5 --- .../Generators/RoutesGenerator.cs | 74 ++++++++++--------- 1 file changed, 39 insertions(+), 35 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 8fc2989b7f..bfc22e4e24 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -214,7 +214,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte if (pkField is not null) { pkType = CSharpNaming.ScalarFor(pkField.SubType); - pkProp = CSharpNaming.Pascal(pkField.Name); + pkProp = CSharpNaming.PropertyName(pkField, ctx.Config); } } bool isProjection = entity.IsReadOnlyProjection(); @@ -241,10 +241,10 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // Issue #203 — @autoSet timestamp columns the generated CRUD stamps with now() // (insert stamps all; update stamps onUpdate; the merge loop skips them; an // InsertPreserving escape hatch is emitted when any exist). - var autoSetFields = AutoSetFields(entity); + var autoSetFields = AutoSetFields(entity, ctx.Config); var autoSetNavs = autoSetFields.Select(a => a.Nav).ToList(); // FR-037 R1 — readOnly / writeOnce are excluded from the PATCH merge. - var frozenNavs = FrozenNavs(entity); + var frozenNavs = FrozenNavs(entity, ctx.Config); // #484 — write-denied (@formExclude or credential) keys are ignored on every write; credentials never leave. var deniedFields = WriteDeniedFields(entity); var credentials = CredentialNames(entity); @@ -279,7 +279,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte || (isReport && f.SubType == FIELD_SUBTYPE_ENUM)) && !f.ResolvedIsArray() && !(isReport && IsCredentialField(f))) // a credential column would be a sort oracle - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); // ADR-0019 Amendment 1 (W4): SQLite refuses `ORDER BY` over a decimal expression, and its @@ -288,7 +288,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte var decimalSortFields = entity.Fields() .Where(f => f.SubType == FIELD_SUBTYPE_DECIMAL && !f.ResolvedIsArray() && CSharpNaming.DbColumnTypeClrOverride(f) is null) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToHashSet(StringComparer.Ordinal); bool sqliteSort = sortFields.Any(decimalSortFields.Contains); @@ -315,7 +315,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte foreach (var name in sortFields) sb.AppendLine($" \"{name}\","); sb.AppendLine(" };"); sb.AppendLine(); - AppendSortDefaultOrder(sb, entity, "SortDefaultDesc"); + AppendSortDefaultOrder(sb, entity, "SortDefaultDesc", ctx.Config); AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); sb.AppendLine($" public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); @@ -413,9 +413,9 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte AppendCreateHandler(sb, "/" + route, cls, ValueObjectNames.ContextTypeRef(ctx.Config), dbSet, requiredKeys, CreatedResult("prefix + \"/" + route + "\"", "input", credentials), voFields, mapVoFields, autoSetFields, writeThrough ? (readDbSet, pkProp!, route) : null, parseBody: HasDecimalField(entity) || HasDurationField(entity), - deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials, + deniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), credentials, ServerOwnedCreateResets(entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(entity, ctx.Config)), - RequiredReadOnlyProps(entity)); + RequiredReadOnlyProps(entity, ctx.Config)); // PATCH + PUT share the same handler — TS reference exposes both verbs, and both // return the updated row (HTTP 200), matching the cross-port api-contract. @@ -588,10 +588,10 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t } var pkField = pkFields.Count == 1 ? baseEntity.Fields().FirstOrDefault(f => f.Name == pkFields[0]) : null; var pkType = pkField is not null ? CSharpNaming.ScalarFor(pkField.SubType) : null; - var pkProp = pkField is not null ? CSharpNaming.Pascal(pkField.Name) : null; + var pkProp = pkField is not null ? CSharpNaming.PropertyName(pkField, ctx.Config) : null; bool hasItem = pkType is not null; - var discProp = CSharpNaming.Pascal(tph.DiscriminatorField); + var discProp = baseEntity.FindField(tph.DiscriminatorField) is { } dField ? CSharpNaming.PropertyName(dField, ctx.Config) : CSharpNaming.Pascal(tph.DiscriminatorField); var discField = baseEntity.FindField(tph.DiscriminatorField); // #484 — the polymorphic base rows carry every subtype's columns, so a credential declared // on the base OR on any subtype is omitted from them. @@ -602,7 +602,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // Sortable base scalar fields (the polymorphic list sorts on base columns). var sortFields = baseEntity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); var sb = new StringBuilder(); @@ -628,7 +628,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t foreach (var name in sortFields) sb.AppendLine($" \"{name}\","); sb.AppendLine(" };"); sb.AppendLine(); - AppendSortDefaultOrder(sb, baseEntity, "SortDefaultDesc"); + AppendSortDefaultOrder(sb, baseEntity, "SortDefaultDesc", ctx.Config); // Per-subtype sort allowlists (case-insensitive) over each subtype's EFFECTIVE // scalar fields (inherited base + own). The per-subtype list resolves the qs @@ -640,7 +640,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t var subClsName = CSharpNaming.Pascal(st.Entity.Name); var subSortFields = st.Entity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); sb.Append($" private static readonly global::System.Collections.Generic.HashSet {subClsName}SortAllowlist ="); sb.AppendLine(" new(global::System.StringComparer.OrdinalIgnoreCase)"); @@ -648,7 +648,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t foreach (var name in subSortFields) sb.AppendLine($" \"{name}\","); sb.AppendLine(" };"); sb.AppendLine(); - AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc"); + AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); } AppendUnauthenticatedRoutesDoc(sb, baseCls, readOnly: false); @@ -726,7 +726,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // EF via the subtype CLR type on Add). Only when the subtype has @autoSet columns. if (hasItem) foreach (var st in tph.Subtypes) - if (AutoSetFields(st.Entity).Count > 0) + if (AutoSetFields(st.Entity, ctx.Config).Count > 0) AppendInsertPreserving(sb, ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)), dbSet, ValueObjectNames.ContextTypeRef(ctx.Config)); AppendOmitResultClass(sb); sb.AppendLine("}"); @@ -764,10 +764,10 @@ private static List RequiredCreateKeys(MetaObject obj, Func RequiredReadOnlyProps(MetaObject obj) => + private static List RequiredReadOnlyProps(MetaObject obj, GenConfig config) => obj.Fields() .Where(f => f.IsRequired && f.IsReadOnlyMutability && !f.IsDerived()) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, config)) .ToList(); // Issue #203 — one @autoSet timestamp column the generated CRUD stamps with now(). @@ -791,10 +791,10 @@ private sealed record AutoSetField(string Nav, string NowExpr, bool OnUpdate); /// echoed in the RESPONSE even where EF omitted the column from the UPDATE. Skipping /// the key here is what makes the response and the row agree. /// - private static List FrozenNavs(MetaObject entity) => + private static List FrozenNavs(MetaObject entity, GenConfig config) => entity.Fields() .Where(f => f.Mutability != MetaObjects.Core.Field.FieldConstants.MUTABILITY_READ_WRITE) - .Select(f => CSharpNaming.Pascal(f.Name)) + .Select(f => CSharpNaming.PropertyName(f, config)) .ToList(); // #484 — a credential is a field that declares (or inherits, ADR-0039) a view.password child. @@ -894,7 +894,7 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" }"); } - private static List AutoSetFields(MetaObject entity) + private static List AutoSetFields(MetaObject entity, GenConfig config) { var list = new List(); foreach (var f in entity.Fields()) @@ -902,7 +902,7 @@ private static List AutoSetFields(MetaObject entity) if (f.AutoSet is not (AUTO_SET_ON_CREATE or AUTO_SET_ON_UPDATE)) continue; if (NowExprFor(f) is not { } now) continue; // non-temporal @autoSet — skip list.Add(new AutoSetField( - Nav: CSharpNaming.Pascal(f.Name), + Nav: CSharpNaming.PropertyName(f, config), NowExpr: now, OnUpdate: f.AutoSet == AUTO_SET_ON_UPDATE)); } @@ -956,7 +956,7 @@ private static List MapValueObjectFields(MetaObject entity, MetaRoot if (target is null || !target.IsValue()) continue; // scalar-valued maps have no bean list.Add(new MapVoField( WireName: f.Name, - Nav: CSharpNaming.Pascal(f.Name), + Nav: CSharpNaming.PropertyName(f, config), DeserType: $"global::System.Collections.Generic.Dictionary")); } return list; @@ -975,7 +975,7 @@ private static List ValueObjectFields(MetaObject entity, MetaRoot root, var isArray = f.ResolvedIsArray(); // ADR-0039: resolving array-ness list.Add(new VoField( WireName: f.Name, - Nav: CSharpNaming.Pascal(f.Name), + Nav: CSharpNaming.PropertyName(f, config), DeserType: isArray ? $"global::System.Collections.Generic.List<{voType}>" : voType, JsonColumnRef: CSharpNaming.ColumnRef(entity, f, config.ColumnNamingStrategy, config.IncludeNames), IsArray: isArray, @@ -1119,9 +1119,9 @@ or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID && pk.Fields is [var keyName] && entity.Fields().FirstOrDefault(f => f.Name == keyName) is { } keyField && !keyField.IsReadOnlyMutability) - list.Add($"input.{CSharpNaming.Pascal(keyField.Name)} = default!;"); + list.Add($"input.{CSharpNaming.PropertyName(keyField, config)} = default!;"); if (discField is not null && !discField.IsReadOnlyMutability) - list.Add($"input.{CSharpNaming.Pascal(discField.Name)} = default!;"); + list.Add($"input.{CSharpNaming.PropertyName(discField, config)} = default!;"); foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, _ => { })) { var target = ValueObjectNames.TypeRef(nav.Target, root, config, routesNs); @@ -1501,11 +1501,11 @@ private static void AppendTphSubtypeRoutes( // Issue #203 — @autoSet columns on the subtype's EFFECTIVE fields (a shared // BaseEntity.createdAt/updatedAt is inherited by every subtype). Stamped on // create/update and skipped in the merge, exactly like a vanilla entity. - var autoSetFields = AutoSetFields(st.Entity); + var autoSetFields = AutoSetFields(st.Entity, config); var autoSetNavs = autoSetFields.Select(a => a.Nav).ToList(); // FR-037 R1 — readOnly / writeOnce on the SUBTYPE's effective fields (a shared // base's mode is inherited by every subtype), excluded from the PATCH merge. - var frozenNavs = FrozenNavs(st.Entity); + var frozenNavs = FrozenNavs(st.Entity, config); // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); @@ -1551,7 +1551,7 @@ private static void AppendTphSubtypeRoutes( // (EF-injected) discriminator, so an omitted @required value-type field → 400. var requiredKeys = RequiredCreateKeys(st.Entity, f => { - var p = CSharpNaming.Pascal(f.Name); + var p = CSharpNaming.PropertyName(f, config); return string.Equals(p, pkProp, System.StringComparison.Ordinal) || string.Equals(p, discProp, System.StringComparison.Ordinal); }); @@ -1560,9 +1560,9 @@ private static void AppendTphSubtypeRoutes( AppendCreateHandler(sb, "/" + subRoute, subType, ValueObjectNames.ContextTypeRef(config), dbSet, requiredKeys, CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields, parseBody: HasDecimalField(st.Entity) || HasDurationField(st.Entity), - deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials, + deniedNavs: deniedFields.Select(f => CSharpNaming.PropertyName(f, config)).ToList(), credentials: credentials, serverOwned: ServerOwnedCreateResets(st.Entity, root, config, routesNs, discField, hierarchy[0]), - readOnlyRequired: RequiredReadOnlyProps(st.Entity)); + readOnlyRequired: RequiredReadOnlyProps(st.Entity, config)); // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped // entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404. @@ -1646,6 +1646,10 @@ private static void AppendSaveChanges(StringBuilder sb, string indent = " sb.AppendLine(indent + "}"); } + // A junction/target column's CLR property, through the same resolver its entity class used. + private static string JunctionProperty(MetaObject owner, string fieldName, GenConfig config) => + owner.FindField(fieldName) is { } f ? CSharpNaming.PropertyName(f, config) : CSharpNaming.Pascal(fieldName); + // Emit the M:N traversal handler for one navigation. The junction + target are // mapped DbSets; the handler does the same two-stage join M2MResolver performs at // runtime, but over the generated DbSets via EF.Property (no metadata at runtime). @@ -1681,13 +1685,13 @@ private static void AppendM2mRoute( : $"db.{CSharpNaming.DbSetName(nav.Target)}"; // The DbSet the context declares for the junction, @collectionName included (item 17). var junctionDbSet = CSharpNaming.DbSetName(nav.Junction); - var srcFkProp = CSharpNaming.Pascal(nav.SourceField); - var tgtFkProp = CSharpNaming.Pascal(nav.TargetField); + var srcFkProp = JunctionProperty(nav.Junction, nav.SourceField, config); + var tgtFkProp = JunctionProperty(nav.Junction, nav.TargetField, config); // The junction FK CLR type (the related-id key type) + the target PK property. var fkType = JunctionFkType(nav); var targetPk = nav.Target.PrimaryIdentity()?.Fields is { Count: 1 } tf - ? CSharpNaming.Pascal(tf[0]) : "Id"; + ? JunctionProperty(nav.Target, tf[0], config) : "Id"; sb.AppendLine(); sb.AppendLine(" app.MapGet(prefix + \"/" + sourceRoute + "/{id}/" + relSeg + "\", async (" + pkType + " id, " + ValueObjectNames.ContextTypeRef(config) + " db) =>"); @@ -1757,7 +1761,7 @@ private static string JunctionFkType(M2MNavigation nav) /// default into its map. Attr() is the RESOLVING accessor (ADR-0039), so an /// order inherited via extends is honoured. /// - private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, string constName) + private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, string constName, GenConfig config) { sb.Append($" private static readonly global::System.Collections.Generic.Dictionary {constName} ="); sb.AppendLine(" new(global::System.StringComparer.OrdinalIgnoreCase)"); @@ -1767,7 +1771,7 @@ private static void AppendSortDefaultOrder(StringBuilder sb, MetaObject owner, s if (CSharpNaming.ScalarFor(f.SubType) is null || f.ResolvedIsArray()) continue; if (f.Attr(FIELD_ATTR_SORTABLE_DEFAULT_ORDER) is not string v) continue; if (v != "asc" && v != "desc") continue; - sb.AppendLine($" [\"{CSharpNaming.Pascal(f.Name)}\"] = {(v == "desc" ? "true" : "false")},"); + sb.AppendLine($" [\"{CSharpNaming.PropertyName(f, config)}\"] = {(v == "desc" ? "true" : "false")},"); } sb.AppendLine(" };"); sb.AppendLine(); From 6a2ed91dec364263c3bc0c72bb0613edfcaf394a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:21:10 -0500 Subject: [PATCH 233/267] test(csharp): every emit site that names a property honours the resolver Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 ++ .../PropertyNamingEmitSitesTests.cs | 139 ++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index f7a664c0c5..32d837237b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -660,6 +660,16 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, C#: every generator names a field's property through the one property-naming resolver + (rc.22).** Since rc.20 `GenConfig.PropertyNaming` (and the `PropertyName` hook) renamed a field's + property in the entity, the context's model lines, the reverse finders and the composite key, but + these emit sites still spelled `Pascal(field.Name)`: the `@sequenceStart` identity annotation in + `DbContextGenerator` (a key renamed `WidgetID` got `.Property(x => x.WidgetId)`, CS1061), the + argument properties in `CallableGenerator`, the mapper targets in `ExtractorGenerator`, the row + cells in `ReportExportGenerator`, and the `RoutesGenerator` key, sort-allowlist, `EF.Property`, + frozen, auto-set, value-object, create-reset, TPH discriminator and M:N junction names. With no + resolver set the output is unchanged. + - **Fix, TypeScript and C#: a passthrough may walk a reference backwards when at most one row references it (rc.21).** A reverse hop was always to-many, so a passthrough over it was refused (`ERR_ORIGIN_CARDINALITY`). When the holder declares an `identity.primary` or diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs new file mode 100644 index 0000000000..4530161144 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -0,0 +1,139 @@ +// Every emit site that spells a field's C# property goes through the one resolver +// (GenConfig.PropertyNaming / CSharpNaming.PropertyName), not CSharpNaming.Pascal on the field name. +// A key named `widgetId` that the resolver spells `WidgetID` is declared as `WidgetID` by the entity, +// so the identity-start line, a callable's argument, an extractor's mapper target, a report export +// cell and the routes must all say `WidgetID`; `WidgetId` would not compile. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class PropertyNamingEmitSitesTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "widgetId" } }, + { "field.string": { "name": "label", "@maxLength": 40, "@sortableDefaultOrder": "desc" } }, + { "field.string": { "name": "stamp", "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "widgetId", "@generation": "increment", "@sequenceStart": 1000 } } + ]}}, + { "object.value": { "name": "WidgetArgs", "children": [ + { "field.long": { "name": "widgetId", "@required": true } }, + { "field.int": { "name": "maxRows" } } + ]}}, + { "object.projection": { "name": "WidgetSummary", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_widget_summary", "@parameterRef": "WidgetArgs" } }, + { "field.long": { "name": "widgetId" } } + ]}}, + { "object.value": { "name": "Part", "children": [ + { "field.string": { "name": "partName", "@required": true } } + ]}}, + { "object.value": { "name": "Gadget", "children": [ + { "field.string": { "name": "gadgetId", "@required": true } }, + { "field.object": { "name": "part", "@objectRef": "Part" } } + ]}}, + { "template.prompt": { "name": "GadgetOut", "@payloadRef": "Gadget", "@responseRef": "Gadget", + "@textRef": "ai/gadget", "@format": "text", "@responseFormat": "json", "@promptStyle": "guide" } } + ]}} + """; + + private static string Spelling(MetaField f) => f.Name switch + { + "widgetId" => "WidgetID", + "gadgetId" => "GadgetID", + "maxRows" => "MaxROWS", + "label" => "LABEL", + _ => CSharpNaming.Pascal(f.Name), + }; + + private static GenContext Ctx(string model = Model, string? dialect = null) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "sites.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", PropertyNaming = Spelling, Dialect = dialect }, + }; + } + + private static string One(IEnumerable files, string fileName) => + files.Single(f => System.IO.Path.GetFileName(f.Path) == fileName).Content; + + [Fact] + public void The_identity_start_line_names_the_resolved_property() + { + var files = new DbContextGenerator().Generate(Ctx(dialect: "postgres")).ToList(); + var context = One(files, "AppDbContext.g.cs"); + Assert.Contains("Property(x => x.WidgetID).HasAnnotation(", context); + Assert.DoesNotContain("x.WidgetId", context); + + // The entity and the context agree: the pair compiles (the context's CS1061 was the symptom). + var all = new EntityGenerator().Generate(Ctx(dialect: "postgres")).Concat(files); + var trees = all.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))); + var comp = CSharpCompilation.Create("sites_" + Guid.NewGuid().ToString("N"), trees, + DbContextCompileTests.BuildReferences(), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + Assert.Empty(comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")); + } + + [Fact] + public void A_callable_binds_its_arguments_by_the_resolved_property_names() + { + var src = One(new CallableGenerator().Generate(Ctx()), "WidgetSummary.callable.g.cs"); + Assert.Contains("args.WidgetID", src); + Assert.Contains("args.MaxROWS", src); + Assert.DoesNotContain("args.WidgetId", src); + Assert.DoesNotContain("args.MaxRows", src); + } + + [Fact] + public void An_extractor_maps_onto_the_resolved_property_names() + { + var src = Assert.Single(new ExtractorGenerator().Generate(Ctx())).Content; + Assert.Contains("GadgetID = ", src); + Assert.Contains("Part = ", src); + Assert.DoesNotContain("GadgetId = ", src); + } + + [Fact] + public void The_routes_name_the_resolved_property_for_the_key_sort_and_frozen_members() + { + var src = One(new RoutesGenerator().Generate(Ctx()), "WidgetRoutes.g.cs"); + Assert.Contains("\"WidgetID\"", src); + Assert.Contains("\"LABEL\"", src); + Assert.DoesNotContain("\"WidgetId\"", src); + Assert.DoesNotContain("\"Label\"", src); + Assert.DoesNotContain(".WidgetId", src); + } + + private const string ReportModel = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.entity": { "name": "Line", "children": [ + { "source.rdb": { "@table": "lines" } }, + { "field.long": { "name": "id", "@required": true } }, + { "field.string": { "name": "label", "@maxLength": 40 } }, + { "identity.primary": { "name": "id", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "label", "@of": "Line.label" } }, + { "measure.aggregate": { "name": "lines", "@agg": "count", "@of": "Line.id" } } + ] } }, + { "object.report": { "name": "LineTotals", "@from": "Line", "@dimensions": ["label"], "@measures": ["lines"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_line_totals" } } ] } } + ] } } + """; + + [Fact] + public void A_report_export_reads_the_resolved_property_names_of_the_row() + { + var src = One(new ReportExportGenerator().Generate(Ctx(ReportModel)), "LineTotalsExport.g.cs"); + Assert.Contains("row.LABEL", src); + Assert.DoesNotContain("row.Label", src); + } +} From 4a206b3a4657abcf17d07058a024da8c06f6b951 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:34:34 -0500 Subject: [PATCH 234/267] fix(csharp): credential stripping and PATCH deny and value-object arms match a renamed property The body key of a renamed property is the host's naming policy over the resolved name, so these arms now match the field name and the resolved name. Co-Authored-By: Claude Opus 5.5 --- .../Generators/RoutesGenerator.cs | 77 ++++++++++++------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index bfc22e4e24..0ff6ca57c3 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -247,7 +247,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte var frozenNavs = FrozenNavs(entity, ctx.Config); // #484 — write-denied (@formExclude or credential) keys are ignored on every write; credentials never leave. var deniedFields = WriteDeniedFields(entity); - var credentials = CredentialNames(entity); + var credentials = CredentialNames(entity, ctx.Config); // Physical table + PK column for the post-save array-null clear (EF OwnsMany ToJson // writes [] for a null nav, so a nullable array column is NULLed via raw SQL). Both // are C# EXPRESSIONS — the Names constant when the names artifact is in this @@ -334,12 +334,13 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine($" IQueryable<{readCls}> q = db." + readDbSet + ".AsNoTracking();"); sb.AppendLine(); sb.AppendLine(" // Filter: ?filter[][]= against the per-entity allowlist."); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField));"); + var fm = FilterMapArg($"{cls}FilterAllowlist", entity, ctx.Config); + sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{readCls}>(FilterParser.Parse(qs, {cls}FilterAllowlist.Fields, {cls}FilterAllowlist.OpsByField){fm});"); sb.AppendLine(" if (filter.ErrorEnvelope is not null)"); // `field` names the rejected filter field — required cross-port on every // filter envelope, so a caller with several filters knows which one failed. sb.AppendLine(" return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);"); + sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fm});"); sb.AppendLine(); sb.AppendLine(" // Sort: ?sort=field:asc|desc against the static allowlist."); sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); @@ -382,7 +383,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine($" if (!withCount) return {OkResult("rows", credentials)};"); else sb.AppendLine($" if (!withCount) return format is null ? {OkResult("rows", credentials)} : ReportExportHttp.Json(http, \"{route}\", rows{ExportOmit(credentials, false)});"); - sb.AppendLine($" var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates);"); + sb.AppendLine($" var totalQ = EfCoreFilterDispatch.ApplyFilter(db.{readDbSet}.AsNoTracking(), filter.Predicates{fm});"); sb.AppendLine(" var total = await totalQ.CountAsync();"); if (export is null) sb.AppendLine($" return {OkResult("new { rows, total }", credentials, envelope: true)};"); @@ -451,7 +452,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine(" var entry = db.Entry(existing);"); AppendUpdateAutoSet(sb, autoSetFields); AppendPartialMergeLoop(sb, null, voFields, mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(entity), - deniedFields.Select(f => f.Name).ToList(), HasDurationField(entity)); + deniedFields.SelectMany(f => WireKeys(f, ctx.Config)).ToList(), HasDurationField(entity)); AppendSaveChanges(sb); AppendArrayNullClears(sb, voFields, tableRef, pkColumnRef); // #214 — writes target the table; for a write-through entity re-read the row @@ -595,8 +596,8 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t var discField = baseEntity.FindField(tph.DiscriminatorField); // #484 — the polymorphic base rows carry every subtype's columns, so a credential declared // on the base OR on any subtype is omitted from them. - var baseCredentials = CredentialNames(baseEntity) - .Concat(tph.Subtypes.SelectMany(st => CredentialNames(st.Entity))) + var baseCredentials = CredentialNames(baseEntity, ctx.Config) + .Concat(tph.Subtypes.SelectMany(st => CredentialNames(st.Entity, ctx.Config))) .Distinct(StringComparer.Ordinal).ToList(); // Sortable base scalar fields (the polymorphic list sorts on base columns). @@ -661,9 +662,10 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t sb.AppendLine(" {"); sb.AppendLine(" var qs = http.Request.Query;"); sb.AppendLine($" IQueryable<{baseCls}> q = db.{dbSet}.AsNoTracking();"); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField));"); + var fmB = FilterMapArg($"{baseCls}FilterAllowlist", baseEntity, ctx.Config); + sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{baseCls}>(FilterParser.Parse(qs, {baseCls}FilterAllowlist.Fields, {baseCls}FilterAllowlist.OpsByField){fmB});"); sb.AppendLine(" if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine(" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);"); + sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmB});"); sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); sb.AppendLine(" {"); sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); @@ -678,7 +680,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t sb.AppendLine(" var rows = await q.ToListAsync();"); sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", global::System.StringComparison.OrdinalIgnoreCase));"); sb.AppendLine($" if (!withCount) return {OkResult("rows", baseCredentials)};"); - sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates).CountAsync();"); + sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.AsNoTracking(), filter.Predicates{fmB}).CountAsync();"); sb.AppendLine($" return {OkResult("new { rows, total }", baseCredentials, envelope: true)};"); sb.AppendLine(" });"); @@ -814,10 +816,10 @@ private static List WriteDeniedFields(MetaObject entity) => /// An entity's credential names plus, for a TPH base, those of every subtype: its rows are /// shared-table rows of every subtype (#484). /// - private static List TphUnionCredentialNames(MetaObject entity, MetaRoot root) => - CredentialNames(entity) + private static List TphUnionCredentialNames(MetaObject entity, MetaRoot root, GenConfig config) => + CredentialNames(entity, config) .Concat(TphPlanBuilder.For(entity, root) is { } tph - ? tph.Subtypes.SelectMany(st => CredentialNames(st.Entity)) + ? tph.Subtypes.SelectMany(st => CredentialNames(st.Entity, config)) : Enumerable.Empty()) .Distinct(StringComparer.Ordinal).ToList(); @@ -834,8 +836,26 @@ private static List HierarchyMarkedFields( return subtype.Fields().Where(f => marked.Contains(f.Name)).ToList(); } - private static List CredentialNames(MetaObject entity) => - entity.Fields().Where(IsCredentialField).Select(f => f.Name).ToList(); + // The keys a body can carry a field under: its metadata name and, when a resolver renames the + // property beyond case, the resolved property name (an entity property serializes under the + // host's naming policy applied to the resolved name). Credential stripping and the PATCH + // deny and value-object arms match on both, so a renamed property cannot escape them. Without + // a rename the two differ at most by case and the list is the field name alone. + private static List WireKeys(MetaField f, GenConfig config) => + new[] { f.Name, CSharpNaming.PropertyName(f, config) } + .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + + private static List CredentialNames(MetaObject entity, GenConfig config) => + entity.Fields().Where(IsCredentialField).SelectMany(f => WireKeys(f, config)).ToList(); + + // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. + private static string KeyMatch(IEnumerable keys) => + string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", global::System.StringComparison.OrdinalIgnoreCase)")); + + // The extra argument that hands the filter dispatch the allowlist's field-to-property map: only + // when a resolver renamed a property beyond case (the allowlist emits the map on the same test). + private static string FilterMapArg(string allowlistRef, MetaObject entity, GenConfig config) => + CSharpNaming.RenamedProperties(entity, config).Count > 0 ? $", {allowlistRef}.PropertyByField" : ""; // A C# string[] expression of the names, spliced into the credential-omitting result. private static string NamesLiteral(IEnumerable names) => @@ -925,7 +945,7 @@ private static List AutoSetFields(MetaObject entity, GenConfig con // Program D — a value-object column the entity carries: a field.object whose @objectRef // resolves to an object.value (single or @isArray). The generated create + PATCH handlers - // deserialize, validate, and assign these as CLR owned-nav properties. WireName is the + // deserialize, validate, and assign these as CLR owned-nav properties. WireKeys are the // metadata (camelCase) field name; Nav is the PascalCase property; DeserType is the VO // POCO type (or List for an array); JsonColumnRef is the physical jsonb column (the // .ToJson name) as a C# EXPRESSION — `Names.Column` when the names artifact @@ -933,7 +953,7 @@ private static List AutoSetFields(MetaObject entity, GenConfig con // splicing into the post-save null-clear SQL; IsArray / Required drive the merge semantics // (present-null: a nullable single/array clears, a @required column 400s). private sealed record VoField( - string WireName, string Nav, string DeserType, string JsonColumnRef, bool IsArray, bool Required); + IReadOnlyList WireKeys, string Nav, string DeserType, string JsonColumnRef, bool IsArray, bool Required); // #362 — the `field.map @objectRef` columns, deliberately NOT folded into VoField. // A VoField drives the owned-nav machinery (EF OwnsMany/.ToJson, deserialization as an @@ -941,7 +961,7 @@ private sealed record VoField( // with a jsonb converter and none of that applies. What it DOES share is the nested // value-object graph, which the create and PATCH paths must validate — before this the // map reached neither, so its values were written unchecked on every write path. - private sealed record MapVoField(string WireName, string Nav, string DeserType); + private sealed record MapVoField(IReadOnlyList WireKeys, string Nav, string DeserType); // A value object is named global::-qualified (rc.19 R65): it may live in any package's // namespace, and a same-named type in the routes file's own namespace would otherwise win. @@ -955,7 +975,7 @@ private static List MapValueObjectFields(MetaObject entity, MetaRoot var target = ValueObjectNames.ResolveFieldRef(f, root); if (target is null || !target.IsValue()) continue; // scalar-valued maps have no bean list.Add(new MapVoField( - WireName: f.Name, + WireKeys: WireKeys(f, config), Nav: CSharpNaming.PropertyName(f, config), DeserType: $"global::System.Collections.Generic.Dictionary")); } @@ -974,7 +994,7 @@ private static List ValueObjectFields(MetaObject entity, MetaRoot root, var voType = ValueObjectNames.GlobalRef(target, config); var isArray = f.ResolvedIsArray(); // ADR-0039: resolving array-ness list.Add(new VoField( - WireName: f.Name, + WireKeys: WireKeys(f, config), Nav: CSharpNaming.PropertyName(f, config), DeserType: isArray ? $"global::System.Collections.Generic.List<{voType}>" : voType, JsonColumnRef: CSharpNaming.ColumnRef(entity, f, config.ColumnNamingStrategy, config.IncludeNames), @@ -1341,7 +1361,7 @@ private static void AppendPartialMergeLoop( { var vf = voFields[i]; var v = "__vo" + i; - sb.AppendLine($" if (string.Equals(prop.Name, \"{vf.WireName}\", global::System.StringComparison.OrdinalIgnoreCase))"); + sb.AppendLine($" if ({KeyMatch(vf.WireKeys)})"); sb.AppendLine(" {"); sb.AppendLine(" if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null)"); sb.AppendLine(" {"); @@ -1375,7 +1395,7 @@ private static void AppendPartialMergeLoop( { var mf = mapVoFields[i]; var mv = "__map" + i; - sb.AppendLine($" if (string.Equals(prop.Name, \"{mf.WireName}\", global::System.StringComparison.OrdinalIgnoreCase))"); + sb.AppendLine($" if ({KeyMatch(mf.WireKeys)})"); sb.AppendLine(" {"); sb.AppendLine(" if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null)"); sb.AppendLine($" {{ existing.{mf.Nav} = null; continue; }}"); @@ -1509,7 +1529,7 @@ private static void AppendTphSubtypeRoutes( // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); - var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).Select(f => f.Name).ToList(); + var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => WireKeys(f, config)).ToList(); // Per-subtype list: GET // sb.AppendLine(); @@ -1517,9 +1537,10 @@ private static void AppendTphSubtypeRoutes( sb.AppendLine(" {"); sb.AppendLine(" var qs = http.Request.Query;"); sb.AppendLine($" IQueryable<{subType}> q = db.{dbSet}.OfType<{subType}>().AsNoTracking();"); - sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllowlist}.Fields, {subAllowlist}.OpsByField));"); + var fmS = FilterMapArg(subAllowlist, st.Entity, config); + sb.AppendLine($" var filter = EfCoreFilterDispatch.Validate<{subType}>(FilterParser.Parse(qs, {subAllowlist}.Fields, {subAllowlist}.OpsByField){fmS});"); sb.AppendLine(" if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field });"); - sb.AppendLine(" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates);"); + sb.AppendLine($" q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates{fmS});"); sb.AppendLine(" if (qs.TryGetValue(\"sort\", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw))"); sb.AppendLine(" {"); sb.AppendLine(" var parts = sortRaw.ToString().Split(':', 2);"); @@ -1534,7 +1555,7 @@ private static void AppendTphSubtypeRoutes( sb.AppendLine(" var rows = await q.ToListAsync();"); sb.AppendLine(" var withCount = qs.TryGetValue(\"withCount\", out var wc) && (wc == \"1\" || string.Equals(wc, \"true\", global::System.StringComparison.OrdinalIgnoreCase));"); sb.AppendLine($" if (!withCount) return {OkResult("rows", credentials)};"); - sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates).CountAsync();"); + sb.AppendLine($" var total = await EfCoreFilterDispatch.ApplyFilter(db.{dbSet}.OfType<{subType}>().AsNoTracking(), filter.Predicates{fmS}).CountAsync();"); sb.AppendLine($" return {OkResult("new { rows, total }", credentials, envelope: true)};"); sb.AppendLine(" });"); @@ -1584,7 +1605,7 @@ private static void AppendTphSubtypeRoutes( // ADR-0045 + the 0.19.4 lesson: TPH is a SEPARATE code path per port, so the // per-subtype merge states the same exclusion rather than inheriting it. AppendPartialMergeLoop(sb, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), - deniedFields.Select(f => f.Name).ToList(), HasDurationField(st.Entity)); + deniedFields.SelectMany(f => WireKeys(f, config)).ToList(), HasDurationField(st.Entity)); AppendSaveChanges(sb); sb.AppendLine($" return {OkResult("existing", credentials)};"); sb.AppendLine(" }"); @@ -1727,7 +1748,7 @@ private static void AppendM2mRoute( sb.AppendLine($" var rows = await {targetFrom}.AsNoTracking()"); sb.AppendLine($" .Where(t => relatedIds.Contains(EF.Property<{fkType}>(t, \"{targetPk}\")))"); sb.AppendLine(" .ToListAsync();"); - sb.AppendLine($" return {OkResult("rows", TphUnionCredentialNames(nav.Target, root))};"); + sb.AppendLine($" return {OkResult("rows", TphUnionCredentialNames(nav.Target, root, config))};"); sb.AppendLine(" });"); } From 6d81d46e915d2e662320b34e8acf8be575b68228 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:34:38 -0500 Subject: [PATCH 235/267] fix(csharp): the filter dispatch finds a property the resolver renamed beyond case The allowlist emits a field-to-property map when needed; the dispatch takes it. Co-Authored-By: Claude Opus 5.5 --- .../MetaObjects.Codegen/CSharpNaming.cs | 44 +++++++++++++++++++ .../Generators/FilterAllowlistGenerator.cs | 13 ++++++ .../Runtime/EfCoreFilterDispatch.cs | 21 +++++---- 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 9acccf0d29..5e91008c51 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -337,6 +337,50 @@ public static string Pascal(string name) => public static string PropertyName(MetaField field, GenConfig? config) => config?.PropertyNaming?.Invoke(field) ?? Pascal(field.Name); + /// + /// The fields whose C# property (the run's resolver) + /// is not the field name in another case: the only ones the runtime's case-insensitive + /// property lookup cannot find on its own. Shared with the routes generator, which + /// passes the emitted map to the filter dispatch exactly when this is non-empty. + /// + public static IReadOnlyDictionary RenamedProperties(MetaObject entity, GenConfig config) + { + var map = new Dictionary(System.StringComparer.Ordinal); + foreach (var f in entity.Fields()) + { + var prop = CSharpNaming.PropertyName(f, config); + if (!string.Equals(prop, f.Name, StringComparison.OrdinalIgnoreCase)) map[f.Name] = prop; + } + return map; + } + + /// + /// Refuse a generator whose PropertyName hook is overridden to answer differently from + /// for any field. Only the resolver reaches every + /// generator (the entity, the context, the routes, the callable, the extractor, the report + /// export, the filter map), so a lone override would declare one name and reference another + /// in a different file: output that does not compile, or a sort that fails at run time. + /// + public static void RefuseDivergingPropertyHook( + string generatorName, IEnumerable objects, GenConfig config, Func hook) + { + foreach (var obj in objects) + { + foreach (var f in obj.Fields()) + { + var resolved = PropertyName(f, config); + var hooked = hook(f); + if (!string.Equals(hooked, resolved, StringComparison.Ordinal)) + { + throw new InvalidOperationException( + $"{generatorName}: its PropertyName hook names field \"{obj.Name}.{f.Name}\" \"{hooked}\", but the run's " + + $"property-naming resolver names it \"{resolved}\"; every other generator uses the resolver, so the " + + "generated files would disagree: set GenConfig.PropertyNaming instead of overriding the hook."); + } + } + } + } + // ---------------------------------------------------------------------------- // Generated-SDK SYMBOL names — the single source of truth for the public C# // identifiers the generators emit. Each generator calls one of these instead of diff --git a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs index 0819549a59..bb73c9d2c8 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/FilterAllowlistGenerator.cs @@ -118,6 +118,19 @@ protected override EmittedFile GenerateOne(MetaObject entity, GenContext ctx) sb.AppendLine(" },"); } sb.AppendLine(" };"); + // The field -> CLR property map, only when a property-naming resolver renamed a property + // beyond case (the runtime matches a field to its property case-insensitively, which + // covers every other spelling). Nothing is emitted otherwise, so default output is unchanged. + var renamed = CSharpNaming.RenamedProperties(entity, ctx.Config); + if (renamed.Count > 0) + { + sb.AppendLine(); + sb.AppendLine(" /// The CLR property of each field whose property name is not the field name in another case."); + sb.AppendLine(" public static readonly IReadOnlyDictionary PropertyByField = new Dictionary(global::System.StringComparer.Ordinal)"); + sb.AppendLine(" {"); + foreach (var kvp in renamed) sb.AppendLine($" [\"{kvp.Key}\"] = \"{kvp.Value}\","); + sb.AppendLine(" };"); + } sb.AppendLine("}"); return new EmittedFile(OutputPaths.Of(entity, $"{cls}FilterAllowlist.g.cs"), sb.ToString()); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs b/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs index b319691b2a..9e0b11e998 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/EfCoreFilterDispatch.cs @@ -38,12 +38,13 @@ public static class EfCoreFilterDispatch { public static IQueryable ApplyFilter( IQueryable source, - IReadOnlyList predicates) where T : class + IReadOnlyList predicates, + IReadOnlyDictionary? propertyByField = null) where T : class { if (predicates is null || predicates.Count == 0) return source; foreach (var p in predicates) { - var lambda = BuildLambda(p); + var lambda = BuildLambda(p, propertyByField); source = source.Where(lambda); } return source; @@ -59,13 +60,13 @@ public static IQueryable ApplyFilter( /// duration operand with the duration wire grammar (). /// A failed parse result is returned unchanged. /// - public static FilterParseResult Validate(FilterParseResult parsed) + public static FilterParseResult Validate(FilterParseResult parsed, IReadOnlyDictionary? propertyByField = null) { if (parsed.ErrorEnvelope is not null) return parsed; foreach (var p in parsed.Predicates) { if (p.Op is "isNull" or "like") continue; - var prop = ResolveProperty(typeof(T), p.Field); + var prop = ResolveProperty(typeof(T), p.Field, propertyByField); if (prop is null) continue; // the allowlist gate upstream guarantees a match; BuildLambda reports a miss var memberType = prop.PropertyType; var underlying = Nullable.GetUnderlyingType(memberType) ?? memberType; @@ -88,10 +89,10 @@ public static FilterParseResult Validate(FilterParseResult parsed) /// Build an Expression<Func<T, bool>> for a single predicate /// against the resolved CLR property of . /// - private static Expression> BuildLambda(FilterPredicate p) + private static Expression> BuildLambda(FilterPredicate p, IReadOnlyDictionary? propertyByField) { var x = Expression.Parameter(typeof(T), "x"); - var prop = ResolveProperty(typeof(T), p.Field); + var prop = ResolveProperty(typeof(T), p.Field, propertyByField); // The metadata field name must map to a CLR property — the allowlist gate // upstream guarantees the field exists on the entity, so a miss here is a // generator/runtime contract violation, not user input. @@ -175,10 +176,12 @@ private static Expression> BuildLambda(FilterPredicate p) /// /// Resolve the CLR property on matching the /// metadata field name. The metadata name is camelCase (e.g. "createdAt") and - /// the property is PascalCase ("CreatedAt"); match case-insensitively. + /// the property is PascalCase ("CreatedAt"); match case-insensitively. When the generated + /// allowlist carries a field-to-property map (a property-naming resolver renamed a property + /// beyond case), the mapped property name is the one looked up. /// - private static PropertyInfo? ResolveProperty(Type entityType, string fieldName) => - entityType.GetProperty(fieldName, + private static PropertyInfo? ResolveProperty(Type entityType, string fieldName, IReadOnlyDictionary? propertyByField = null) => + entityType.GetProperty(propertyByField is not null && propertyByField.TryGetValue(fieldName, out var mapped) ? mapped : fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); /// From de42bf3ddb3e0be8ef1621fc971de3cfbc82b4ec Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:34:45 -0500 Subject: [PATCH 236/267] fix(csharp): a PropertyName hook that disagrees with the resolver is refused The hooks default to GenConfig.PropertyNaming and are obsolete; an override that names any field differently stops the run, naming the field. Co-Authored-By: Claude Opus 5.5 --- .../PropertyNamingCodegenTests.cs | 14 +++++++++++++- server/csharp/MetaObjects.Codegen/Generator.cs | 13 ++++++++----- .../Generators/DbContextGenerator.cs | 8 +++++++- .../Generators/EntityGenerator.cs | 9 +++++++-- 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs index f22e6a6936..9df2ed733a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs @@ -141,13 +141,25 @@ private sealed class AcronymContext : DbContextGenerator [Fact] public void The_overridable_hooks_agree_across_both_generators() { - var ctx = Ctx(Load()); + // The hooks agree with the resolver: the run is accepted and compiles. + var ctx = Ctx(Load(), Acronyms); var files = Generate(ctx, new AcronymEntities(), new AcronymContext()); Assert.Empty(CompileErrors(files)); Assert.Contains("e.CustomerID ==", files.Single(f => System.IO.Path.GetFileName(f.Path) == "OrderLineQueries.g.cs").Content); } + [Fact] + public void A_hook_override_that_differs_from_the_resolver_is_refused() + { + // No resolver set: the override alone would rename the entity's property and nothing else. + var ex = Assert.Throws(() => new AcronymEntities().Generate(Ctx(Load())).ToList()); + Assert.Contains("set GenConfig.PropertyNaming", ex.Message); + Assert.Contains("hook names field \"", ex.Message); + var ex2 = Assert.Throws(() => new AcronymContext().Generate(Ctx(Load())).ToList()); + Assert.Contains("set GenConfig.PropertyNaming", ex2.Message); + } + [Fact] public void Without_a_resolver_the_output_is_the_pascal_default() { diff --git a/server/csharp/MetaObjects.Codegen/Generator.cs b/server/csharp/MetaObjects.Codegen/Generator.cs index 1bee973885..eba292c881 100644 --- a/server/csharp/MetaObjects.Codegen/Generator.cs +++ b/server/csharp/MetaObjects.Codegen/Generator.cs @@ -229,11 +229,14 @@ public string? ContextAssemblyName /// /// The C# property name of a field, for every generator that names one: the entity and /// value-object classes, the composite [PrimaryKey], the DbContext's model - /// configuration, the reverse finders and the routes. null, the default, is the - /// PascalCased field name (). Set it to rename a property - /// (an acronym, say) once, so the class that declares it and every line that references it - /// agree. EntityGenerator.PropertyName and DbContextGenerator.PropertyName read - /// it by default; a subclass that overrides one of those hooks must override both. + /// configuration, the reverse finders, the routes (members, sort and filter names, credential + /// and write-deny keys), the callable arguments, the extractor mapper, the report export and + /// the filter allowlist's property map. null, the default, is the PascalCased field name + /// (). Set it to rename a property (an acronym, say) once, so + /// the class that declares it and every line that references it agree. This is the only way + /// to rename consistently: EntityGenerator.PropertyName and + /// DbContextGenerator.PropertyName default to it, are obsolete, and a generator whose + /// override answers differently from this resolver for any field refuses to run. /// public Func? PropertyNaming { get; init; } diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 6dcd97f9c4..84077938cb 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -5,6 +5,8 @@ // jsonb / subdocument / absent → a single json column via .ToJson), and uses // .PrimitiveCollection() for scalar/enum array fields (EF Core 8 API). +// The PropertyName hook is obsolete for adopters (set GenConfig.PropertyNaming); this generator still calls it. +#pragma warning disable CS0618 using System.Text; using MetaObjects.Codegen.Docs; using MetaObjects.Meta; @@ -60,7 +62,10 @@ public class DbContextGenerator : IGenerator /// names one. Default: the run's resolver, else /// PascalCase of the field name — the same answer EntityGenerator.PropertyName gives /// by default, so the two agree. A subclass that overrides the entity generator's hook - /// overrides this one the same way (or sets the resolver on the config instead). + /// overrides this one the same way (or sets the resolver on the config instead). + /// An override that answers differently from the resolver for any field is refused when the + /// generator runs (set GenConfig.PropertyNaming instead). + [Obsolete("set GenConfig.PropertyNaming: it is the one resolver every generator consults. An override that names a field differently from the resolver is refused when the generator runs.")] protected virtual string PropertyName(MetaField field) => CSharpNaming.PropertyName(field, _config); // The run's config, for the PropertyName default. Set when Generate starts. @@ -97,6 +102,7 @@ public virtual IEnumerable Generate(GenContext ctx) .OrderBy(o => o.Name, StringComparer.Ordinal) .ToList(); if (objects.Count == 0) return []; + CSharpNaming.RefuseDivergingPropertyHook(Name, objects, ctx.Config, PropertyName); // One context, one property per name (CS0102 otherwise), claimed as emitted: an object // that gets no DbSet here never takes part. Two objects on one table are EF's to refuse // (it does, at model build), not this generator's. diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index e5756ac332..d573cefc2e 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -12,6 +12,8 @@ // Object-typed fields on read-only projections are not mapped here — that is a // separate projection-materialization concern. +// The PropertyName hook is obsolete for adopters (set GenConfig.PropertyNaming); this generator still calls it. +#pragma warning disable CS0618 using System.Text; using MetaObjects.Codegen.Docs; using MetaObjects.Meta; @@ -43,8 +45,10 @@ public class EntityGenerator : IGenerator /// subclass can override to honor an explicit casing source (an all-caps acronym a plain /// PascalCase of the field name would mangle). Every name this generator emits for a field — /// the property, the composite [PrimaryKey], the reverse finders — goes through here. - /// The DbContext generator names the same properties: set the resolver on the config, or - /// override DbContextGenerator.PropertyName to match. + /// Every other generator that names a property reads + /// only, so an override that answers differently from the resolver for any field is refused + /// when the generator runs (set GenConfig.PropertyNaming instead). + [Obsolete("set GenConfig.PropertyNaming: it is the one resolver every generator consults. An override that names a field differently from the resolver is refused when the generator runs.")] protected virtual string PropertyName(MetaField field) => CSharpNaming.PropertyName(field, _config); // The run's config, for the PropertyName default. Set when Generate starts. @@ -114,6 +118,7 @@ public virtual IEnumerable Generate(GenContext ctx) _wire = ctx.Root.WireFormat; _config = ctx.Config; _ctx = ctx; + CSharpNaming.RefuseDivergingPropertyHook(Name, ReportRows.WithReportRows(ctx), ctx.Config, PropertyName); // FR-044 — a view-backed report joins the set as its ROW MODEL (a keyless, // projection-shaped object carrying its derived fields); every other report node // is dropped. See ReportRows. From 892f1b7d13b8fe60fed3641ab892db530b34471d Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:42:03 -0500 Subject: [PATCH 237/267] test(csharp): every routes site, credentials, the filter map and a golden for the default output Co-Authored-By: Claude Opus 5.5 --- .../pre-rc22-propname/AppDbContext.g.cs | 128 ++++++ .../AppDbContextDesignTimeServices.g.cs | 180 ++++++++ .../pre-rc22-propname/CarFilterAllowlist.g.cs | 24 + .../pre-rc22-propname/GadgetOutExtractor.cs | 54 +++ .../GizmoFilterAllowlist.g.cs | 24 + .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 295 ++++++++++++ .../LineFilterAllowlist.g.cs | 22 + .../Golden/pre-rc22-propname/LineRoutes.g.cs | 183 ++++++++ .../pre-rc22-propname/LineTotalsExport.g.cs | 37 ++ .../LineTotalsFilterAllowlist.g.cs | 26 ++ .../pre-rc22-propname/LineTotalsRoutes.g.cs | 105 +++++ .../pre-rc22-propname/ReportExportWriter.g.cs | 169 +++++++ .../pre-rc22-propname/TagFilterAllowlist.g.cs | 22 + .../Golden/pre-rc22-propname/TagRoutes.g.cs | 185 ++++++++ .../pre-rc22-propname/VanFilterAllowlist.g.cs | 24 + .../VehicleFilterAllowlist.g.cs | 24 + .../pre-rc22-propname/VehicleRoutes.g.cs | 432 ++++++++++++++++++ .../VehicleTagFilterAllowlist.g.cs | 22 + .../pre-rc22-propname/VehicleTagRoutes.g.cs | 88 ++++ .../WidgetSummary.callable.g.cs | 23 + .../WidgetSummaryFilterAllowlist.g.cs | 22 + .../WidgetSummaryRoutes.g.cs | 89 ++++ .../PropertyNamingEmitSitesTests.cs | 234 +++++++++- .../PropertyNamingGoldenTests.cs | 138 ++++++ 24 files changed, 2549 insertions(+), 1 deletion(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs create mode 100644 server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs new file mode 100644 index 0000000000..e0e4d2d55a --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContext.g.cs @@ -0,0 +1,128 @@ +// +// Generated by MetaObjects dbcontext-generator. Do not edit by hand. +#nullable enable +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Acme.Shop; + +namespace Acme.Generated; + +public class AppDbContext : DbContext +{ + public AppDbContext(DbContextOptions options) : base(options) { } + + public DbSet Gizmos { get; set; } = default!; + public DbSet Lines { get; set; } = default!; + public DbSet LineTotals { get; set; } = default!; + public DbSet Tags { get; set; } = default!; + public DbSet Vehicles { get; set; } = default!; + public DbSet VehicleTags { get; set; } = default!; + public DbSet WidgetSummaries { get; set; } = default!; + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity().HasNoKey().ToView("v_line_totals"); + modelBuilder.Entity().HasNoKey().ToView("fn_widget_summary"); + modelBuilder.Entity().OwnsOne(x => x.Dims, b => b.ToJson("dims")); + modelBuilder.Entity().Property(x => x.Extras).HasColumnType("jsonb").HasConversion(MapJsonb.Converter(), MapJsonb.Comparer()); + modelBuilder.Entity().Property(x => x.CreatedAt).HasColumnType("timestamp with time zone"); + modelBuilder.Entity().Property(x => x.UpdatedAt).HasColumnType("timestamp with time zone"); + modelBuilder.Entity().Property(x => x.Stamp).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + modelBuilder.Entity().Property(x => x.Serial).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + if (Database.ProviderName == "Npgsql.EntityFrameworkCore.PostgreSQL") modelBuilder.Entity().Property(x => x.Id).HasAnnotation("Npgsql:IdentitySequenceOptions", "'500', '1', '', '', 'False', '1'"); + modelBuilder.Entity().Property(x => x.Kind).HasConversion(); + modelBuilder.Entity().ToTable(t => t.HasCheckConstraint("vehicles_kind_chk", "\"kind\" IN ('Car', 'Van')")); + modelBuilder.Entity().HasMany(x => x.Tags).WithMany().UsingEntity(l => l.HasOne().WithMany().HasForeignKey(j => j.TagId), r => r.HasOne().WithMany().HasForeignKey(j => j.VehicleId)); + modelBuilder.Entity().HasDiscriminator(e => e.Kind).HasValue(global::Acme.Shop.Vehicle.VehicleKind.Car).HasValue(global::Acme.Shop.Vehicle.VehicleKind.Van); + modelBuilder.Entity().Property(x => x.RegNo).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore); + } + + /// + /// Shared jsonb (de)serialization for field.map columns. The comparer is required: + /// EF snapshots a value-converted property by reference, so without it an in-place + /// edit to the dictionary is never detected and the row is never updated. + /// + private static class MapJsonb + { + private static readonly global::System.Text.Json.JsonSerializerOptions Options = new() + { + Converters = { new global::System.Text.Json.Serialization.JsonStringEnumConverter() } + }; + + internal static global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + global::System.Collections.Generic.Dictionary, string> RequiredConverter() => new( + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options), + v => global::System.Text.Json.JsonSerializer.Deserialize< + global::System.Collections.Generic.Dictionary>(v, Options)!); + + /// Same conversion as RequiredConverter, over the NULLABLE dictionary a + /// non-required map's property carries — keep the two bodies identical. EF Core's + /// nullability-aware HasConversion checks the converter's model type against the + /// property's own annotation, so one factory cannot serve both arms. + internal static global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter< + global::System.Collections.Generic.Dictionary?, string> Converter() => new( + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options), + v => global::System.Text.Json.JsonSerializer.Deserialize< + global::System.Collections.Generic.Dictionary>(v, Options)!); + + /// A whole value-object document (or collection of them) as one jsonb value, + /// for a value object that holds a map (EF Core 8 cannot own a dictionary inside JSON). + internal static global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter ObjectConverter() => new( + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options), + v => global::System.Text.Json.JsonSerializer.Deserialize(v, Options)!); + + internal static global::Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer ObjectComparer() => new( + (a, b) => global::System.Text.Json.JsonSerializer.Serialize(a, Options) == global::System.Text.Json.JsonSerializer.Serialize(b, Options), + v => global::System.Text.Json.JsonSerializer.Serialize(v, Options).GetHashCode(), + v => global::System.Text.Json.JsonSerializer.Deserialize(global::System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!); + + internal static global::Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer< + global::System.Collections.Generic.Dictionary?> Comparer() => new( + (a, b) => Eq(a, b), v => Hash(v), v => Snap(v)); + + /// Order-INDEPENDENT equality: a dictionary rebuilt in a different key + /// order holds the same value, and comparing serialized JSON would call it changed + /// and issue an UPDATE for a row nothing touched. Scalars settle on the default + /// comparer (no serialization at all); a value-object value falls through to a JSON + /// compare, since the generated POCO is a class and compares by reference. + private static bool Eq( + global::System.Collections.Generic.Dictionary? a, + global::System.Collections.Generic.Dictionary? b) + { + if (a is null || b is null) return ReferenceEquals(a, b); + if (a.Count != b.Count) return false; + foreach (var kv in a) + { + if (!b.TryGetValue(kv.Key, out var other)) return false; + if (global::System.Collections.Generic.EqualityComparer.Default.Equals(kv.Value, other)) continue; + if (global::System.Text.Json.JsonSerializer.Serialize(kv.Value, Options) + != global::System.Text.Json.JsonSerializer.Serialize(other, Options)) return false; + } + return true; + } + + /// Keys and count only — order-independent (XOR), allocation-free, and + /// stable for a value-object value whose GetHashCode is reference-based. Equal + /// dictionaries always hash equal, which is all EF requires. + private static int Hash(global::System.Collections.Generic.Dictionary? v) + { + if (v is null) return 0; + var h = v.Count; + foreach (var k in v.Keys) h ^= k.GetHashCode(); + return h; + } + + /// The change-tracking snapshot. A value-object value needs a DEEP copy or + /// an in-place edit to a nested object mutates the snapshot too and goes undetected; + /// an immutable scalar only needs the dictionary copied. + private static global::System.Collections.Generic.Dictionary? Snap( + global::System.Collections.Generic.Dictionary? v) => + v is null + ? null + : typeof(TValue).IsValueType || typeof(TValue) == typeof(string) + ? new global::System.Collections.Generic.Dictionary(v) + : global::System.Text.Json.JsonSerializer.Deserialize< + global::System.Collections.Generic.Dictionary>( + global::System.Text.Json.JsonSerializer.Serialize(v, Options), Options)!; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs new file mode 100644 index 0000000000..e364d94417 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/AppDbContextDesignTimeServices.g.cs @@ -0,0 +1,180 @@ +// +// Generated by MetaObjects db-context. Do not edit by hand. +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; + +namespace Acme.Generated; + +/// Design-time only: a start-only identity change scaffolds as SQL that records the +/// start and moves the counter forward to it, never back, instead of Npgsql's RESTART; and a +/// JSON column's comment, which EF 8 cannot carry, scaffolds as COMMENT ON COLUMN. EF runs +/// it for dotnet ef migrations add; nothing is registered at runtime. +public sealed class AppDbContextDesignTimeServices : IDesignTimeServices +{ + private const string Options = "Npgsql:IdentitySequenceOptions"; + private const string Strategy = "Npgsql:ValueGenerationStrategy"; + + /// Wraps the differ already registered (the context's own, by default), once. + public void ConfigureDesignTimeServices(IServiceCollection services) + { + // Found by the startup scan and by the reference both, or one such class per + // context in one assembly (EF applies every reference): wrap once. The marker is + // matched by name, so another context's services class counts too. + if (services.Any(d => d.ServiceType.Name == nameof(MetaObjectsDesignTimeApplied))) return; + services.AddSingleton(); + var inner = services.LastOrDefault(d => d.ServiceType == typeof(IMigrationsModelDiffer) && d.ServiceKey is null); + services.Add(new ServiceDescriptor(typeof(IMigrationsModelDiffer), + sp => new Differ(Resolve(inner, sp), sp.GetRequiredService().Context.GetService()), + inner?.Lifetime ?? ServiceLifetime.Transient)); + } + + private sealed class MetaObjectsDesignTimeApplied { } + + private static IMigrationsModelDiffer Resolve(ServiceDescriptor? inner, IServiceProvider sp) => inner switch + { + { ImplementationInstance: IMigrationsModelDiffer differ } => differ, + { ImplementationFactory: { } factory } => (IMigrationsModelDiffer)factory(sp), + { ImplementationType: { } type } => (IMigrationsModelDiffer)ActivatorUtilities.CreateInstance(sp, type), + _ => sp.GetRequiredService().Context.GetService(), + }; + + private sealed class Differ(IMigrationsModelDiffer inner, ISqlGenerationHelper sql) : IMigrationsModelDiffer + { + public bool HasDifferences(IRelationalModel? source, IRelationalModel? target) => inner.HasDifferences(source, target); + + public IReadOnlyList GetDifferences(IRelationalModel? source, IRelationalModel? target) + { + var result = new List(); + foreach (var operation in inner.GetDifferences(source, target)) + { + if (operation is not AlterColumnOperation alter || StartChange(alter, sql) is not { } change) + { + result.Add(operation); + continue; + } + result.AddRange(change.Statements.Select(s => new SqlOperation { Sql = s })); + if (OnlyTheStart(alter, change.OldOptions)) continue; + // The rest of the change, with the old start made the new one: no start change is left in it. + alter.OldColumn[Options] = change.OldOptions; + result.Add(alter); + } + result.AddRange(JsonColumnComments(source, target, sql).Select(s => new SqlOperation { Sql = s })); + return result; + } + } + + // Ruling R59: EF 8's JsonColumn carries no comment, so a JSON column's comment rides on + // its owned type as an annotation and is scaffolded here, after every other operation + // (a new table's column exists by then). Down is the same diff the other way. + private const string JsonComment = "MetaObjects:JsonColumnComment"; + + private static IEnumerable JsonColumnComments(IRelationalModel? source, IRelationalModel? target, ISqlGenerationHelper sql) + { + var from = JsonCommentsOf(source); + foreach (var (column, text) in JsonCommentsOf(target)) + if (!from.TryGetValue(column, out var old) || old != text) + yield return CommentOn(column, text, sql); + foreach (var (column, _) in from) + if (!JsonCommentsOf(target).ContainsKey(column) + && target?.FindTable(column.Table, column.Schema)?.FindColumn(column.Column) is not null) + yield return CommentOn(column, null, sql); + } + + private static Dictionary<(string? Schema, string Table, string Column), string> JsonCommentsOf(IRelationalModel? model) + { + var comments = new Dictionary<(string? Schema, string Table, string Column), string>(); + if (model is null) return comments; + foreach (var type in model.Model.GetEntityTypes()) + if (type.FindAnnotation(JsonComment)?.Value is string text + && type.GetContainerColumnName() is { } column && type.GetTableName() is { } table) + comments[(type.GetSchema(), table, column)] = text; + return comments; + } + + private static string CommentOn((string? Schema, string Table, string Column) c, string? text, ISqlGenerationHelper sql) => + "COMMENT ON COLUMN " + sql.DelimitIdentifier(c.Table, c.Schema) + "." + sql.DelimitIdentifier(c.Column) + + " IS " + (text is null ? "NULL" : Literal(text)) + sql.StatementTerminator; + + // The serialized options are "'start', 'increment', 'min', 'max', 'cyclic', 'cache'"; + // a missing annotation is Npgsql's defaults, and an empty start is no start. + private const string Defaults = "'', '1', '', '', 'False', '1'"; + private static string[] Parts(string? options) => (options ?? Defaults).Split(',').Select(p => p.Trim().Trim('\'')).ToArray(); + private static string? Start(string? options) => Parts(options)[0] is { Length: > 0 } start ? start : null; + + /// with the start replaced: what the old column + /// must say for Npgsql to see no start change. + private static string WithStart(string? options, string? start) => + "'" + (start ?? "") + "'" + (options ?? Defaults)[(options ?? Defaults).IndexOf(',')..]; + + private static bool Descending(string? options) => long.TryParse(Parts(options)[1], out var increment) && increment < 0; + + /// Where an identity without a start begins: its minimum ascending, its + /// maximum descending (PostgreSQL's default). + private static string DefaultStart(string? options) + { + var p = Parts(options); + return Descending(options) ? (p[3] is { Length: > 0 } max ? max : "-1") : (p[2] is { Length: > 0 } min ? min : "1"); + } + + private static bool IsIdentity(object? strategy) => strategy?.ToString()?.StartsWith("Identity", StringComparison.Ordinal) == true; + + private static string Literal(string text) => "'" + text.Replace("'", "''") + "'"; + + /// The SQL of the start-only change an alter carries, or null when it moves no start. + private static (IReadOnlyList Statements, string OldOptions)? StartChange(AlterColumnOperation operation, ISqlGenerationHelper sql) + { + if (!IsIdentity(operation[Strategy]) || !IsIdentity(operation.OldColumn[Strategy])) return null; + var to = operation[Options] as string; + var from = operation.OldColumn[Options] as string; + if (Start(to) == Start(from)) return null; + var table = sql.DelimitIdentifier(operation.Table, operation.Schema); + var column = sql.DelimitIdentifier(operation.Name); + var statements = new List + { + "ALTER TABLE " + table + " ALTER COLUMN " + column + " SET START WITH " + (Start(to) ?? DefaultStart(to)) + sql.StatementTerminator, + }; + // A declared start also moves the counter forward to it, or past the highest id, and + // never back. A removed start, or a descending identity, records the start only. + if (Start(to) is { } start && !Descending(to)) + statements.Add( + "DO $$\n" + + "DECLARE\n" + + " mo_seq regclass := pg_get_serial_sequence(" + Literal(table) + ", " + Literal(operation.Name) + ")::regclass;\n" + + " mo_target bigint;\n" + + " mo_next bigint;\n" + + "BEGIN\n" + + " SELECT GREATEST(" + start + ", COALESCE(MAX(" + column + "), 0) + 1) INTO mo_target FROM " + table + ";\n" + + " EXECUTE 'SELECT CASE WHEN is_called THEN last_value + ' || (SELECT seqincrement FROM pg_sequence WHERE seqrelid = mo_seq)\n" + + " || ' ELSE last_value END FROM ' || mo_seq INTO mo_next;\n" + + " IF mo_next < mo_target THEN PERFORM setval(mo_seq, mo_target, false); END IF;\n" + + "END $$;"); + return (statements, WithStart(from, Start(to))); + } + + /// Whether the alter changes nothing but its identity start. + private static bool OnlyTheStart(AlterColumnOperation operation, string oldOptions) + { + var o = operation.OldColumn; + if (operation.ClrType != o.ClrType || operation.ColumnType != o.ColumnType || operation.IsNullable != o.IsNullable + || operation.IsUnicode != o.IsUnicode || operation.IsFixedLength != o.IsFixedLength || operation.MaxLength != o.MaxLength + || operation.Precision != o.Precision || operation.Scale != o.Scale || operation.IsRowVersion != o.IsRowVersion + || !Equals(operation.DefaultValue, o.DefaultValue) || operation.DefaultValueSql != o.DefaultValueSql + || operation.ComputedColumnSql != o.ComputedColumnSql || operation.IsStored != o.IsStored + || operation.Comment != o.Comment || operation.Collation != o.Collation) + return false; + var names = operation.GetAnnotations().Select(a => a.Name).Union(o.GetAnnotations().Select(a => a.Name)); + return names.All(n => n == Options + ? Parts(operation[n] as string).SequenceEqual(Parts(oldOptions)) + : Equals(operation[n], o[n])); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs new file mode 100644 index 0000000000..361ae41966 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/CarFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Car. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class CarFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + "plate", + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + ["plate"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs new file mode 100644 index 0000000000..c4ab21e8d7 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GadgetOutExtractor.cs @@ -0,0 +1,54 @@ +// +// Generated by MetaObjects extractor-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using MetaObjects.Render.Extract; + +namespace Acme.Generated; + +/// The extract tier for the GadgetOut template.prompt — turns dirty LLM +/// text into a fully-typed graph (nested objects + arrays-of-objects +/// populated) in one call, by delegating to the nested-capable extract and mapping the all-nullable +/// GadgetExtracted mirror onto the value object. No registry / binding / factory. +public static class GadgetOutExtractor +{ + /// Extract a fully-typed from dirty using + /// the runtime (the loaded value object). Runs the tolerant extract, then maps + /// the extracted mirror onto the value object. + /// iff a @required field was lost or malformed (the strict opt-in gate). + public static global::Acme.Shop.Gadget Extract(global::MetaObjects.Meta.MetaObject mo, string text) + { + var r = GadgetOutParser.ExtractLenient(mo, text); + if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired()) + throw new ExtractException(r.Report); + return ToStrict_Gadget(r.Data!); + } + + /// Extract with explicit . + /// iff a @required field was lost or malformed. + public static global::Acme.Shop.Gadget Extract(global::MetaObjects.Meta.MetaObject mo, string text, ExtractOptions opts) + { + var r = GadgetOutParser.ExtractLenient(mo, text, opts); + if (r.Report.HasLostRequired() || r.Report.HasMalformedRequired()) + throw new ExtractException(r.Report); + return ToStrict_Gadget(r.Data!); + } + + /// Re-exposes the nested-capable tolerant extract; never throws. Inspect Report for + /// lost/defaulted fields. Returns the all-nullable mirror (not the value object). + public static ExtractionResult ExtractLenient(global::MetaObjects.Meta.MetaObject mo, string text) => + GadgetOutParser.ExtractLenient(mo, text); + + /// Map the all-nullable GadgetExtracted mirror onto Gadget. Generated. + private static global::Acme.Shop.Gadget ToStrict_Gadget(global::Acme.Shop.GadgetExtracted m) => new global::Acme.Shop.Gadget + { + GadgetId = m.gadgetId!, + Part = m.part is null ? null : ToStrict_Part(m.part), + }; + + /// Map the all-nullable PartExtracted mirror onto Part. Generated. + private static global::Acme.Shop.Part ToStrict_Part(global::Acme.Shop.PartExtracted m) => new global::Acme.Shop.Part + { + PartName = m.partName!, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs new file mode 100644 index 0000000000..18902e8305 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Gizmo. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class GizmoFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + "title", + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + ["title"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs new file mode 100644 index 0000000000..4f7032f829 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -0,0 +1,295 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class GizmoRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Title", + "Stamp", + "Serial", + "PinHash", + "TokenHash", + "CreatedAt", + "UpdatedAt", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + ["Title"] = true, + }; + + /// Maps Gizmo REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapGizmoRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Gizmos.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, GizmoFilterAllowlist.Fields, GizmoFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortGizmo(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "pinHash" }); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Gizmos.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "pinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Gizmos.FindAsync(id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "pinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + global::System.Text.Json.JsonDocument __body; + try { __body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + using var __bodyScope = __body; + if (__body.RootElement.ValueKind != global::System.Text.Json.JsonValueKind.Object) + return Results.BadRequest(new { error = "validation" }); + var __present = new global::System.Collections.Generic.HashSet(global::System.StringComparer.OrdinalIgnoreCase); + foreach (var __p in __body.RootElement.EnumerateObject()) + if (__p.Value.ValueKind != global::System.Text.Json.JsonValueKind.Null) __present.Add(__p.Name); + foreach (var __req in new[] { "title" }) + if (!__present.Contains(__req)) return Results.BadRequest(new { error = "validation" }); + Gizmo? input; + try { input = global::System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + if (input is null) return Results.BadRequest(new { error = "validation" }); + // @formExclude / credential: not settable through the generated create; the value is ignored. + input.PinHash = default!; + input.TokenHash = default!; + var __vr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateObject( + input, new global::System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true) + && __vr.Exists(r => !global::System.Linq.Enumerable.Any(r.MemberNames) + || global::System.Linq.Enumerable.Any(r.MemberNames, m => global::System.Array.IndexOf(new[] { "Serial" }, m) < 0))) + return Results.BadRequest(new { error = "validation" }); + if (!ValueObjectValidator.Validate(input.Dims)) return Results.BadRequest(new { error = "validation" }); + if (!ValueObjectValidator.Validate(input.Extras)) return Results.BadRequest(new { error = "validation" }); + input.CreatedAt = global::System.DateTimeOffset.UtcNow; + input.UpdatedAt = global::System.DateTimeOffset.UtcNow; + db.Gizmos.Add(input); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(input, new string[] { "pinHash" }, status: 201, location: prefix + "/gizmos"); + }); + + async global::System.Threading.Tasks.Task UpdateGizmo(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Gizmos.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + using var bodyScope = body; + // Deserialize each value with the app's CONFIGURED JSON options, not defaults — + // a field.timestamp binds to DateTimeOffset via a custom converter registered on + // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + existing.UpdatedAt = global::System.DateTimeOffset.UtcNow; + foreach (var prop in body.RootElement.EnumerateObject()) + { + if (string.Equals(prop.Name, "pinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "tokenHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + if (string.Equals(prop.Name, "dims", global::System.StringComparison.OrdinalIgnoreCase)) + { + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { + existing.Dims = null; + continue; + } + global::Acme.Shop.Dims __vo0; + try { __vo0 = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), jsonOpts); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + if (!ValueObjectValidator.Validate(__vo0)) return Results.BadRequest(new { error = "validation" }); + existing.Dims = __vo0; + continue; + } + if (string.Equals(prop.Name, "extras", global::System.StringComparison.OrdinalIgnoreCase)) + { + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { existing.Extras = null; continue; } + global::System.Collections.Generic.Dictionary? __map0; + try { __map0 = global::System.Text.Json.JsonSerializer.Deserialize>(prop.Value.GetRawText(), jsonOpts); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + if (!ValueObjectValidator.Validate(__map0)) return Results.BadRequest(new { error = "validation" }); + existing.Extras = __map0; + continue; + } + var target = entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (string.Equals(target.Name, "CreatedAt", global::System.StringComparison.Ordinal)) continue; // @autoSet: server-owned + if (string.Equals(target.Name, "UpdatedAt", global::System.StringComparison.Ordinal)) continue; // @autoSet: server-owned + if (string.Equals(target.Name, "Stamp", global::System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (string.Equals(target.Name, "Serial", global::System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = null; + continue; + } + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + var __pr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(__val, + new global::System.ComponentModel.DataAnnotations.ValidationContext(existing) { MemberName = target.Name }, __pr)) + return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = __val; + } + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(existing, new string[] { "pinHash" }); + } + app.MapPatch(prefix + "/gizmos/{id}", UpdateGizmo); + app.MapPut(prefix + "/gizmos/{id}", UpdateGizmo); + + app.MapDelete(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Gizmos.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Gizmos.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortGizmo(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Title" => desc ? q.OrderByDescending(x => EF.Property(x!, "Title") == null).ThenByDescending(x => EF.Property(x!, "Title")) : q.OrderBy(x => EF.Property(x!, "Title") == null).ThenBy(x => EF.Property(x!, "Title")), + "Stamp" => desc ? q.OrderByDescending(x => EF.Property(x!, "Stamp") == null).ThenByDescending(x => EF.Property(x!, "Stamp")) : q.OrderBy(x => EF.Property(x!, "Stamp") == null).ThenBy(x => EF.Property(x!, "Stamp")), + "Serial" => desc ? q.OrderByDescending(x => EF.Property(x!, "Serial") == null).ThenByDescending(x => EF.Property(x!, "Serial")) : q.OrderBy(x => EF.Property(x!, "Serial") == null).ThenBy(x => EF.Property(x!, "Serial")), + "PinHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "PinHash") == null).ThenByDescending(x => EF.Property(x!, "PinHash")) : q.OrderBy(x => EF.Property(x!, "PinHash") == null).ThenBy(x => EF.Property(x!, "PinHash")), + "TokenHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "TokenHash") == null).ThenByDescending(x => EF.Property(x!, "TokenHash")) : q.OrderBy(x => EF.Property(x!, "TokenHash") == null).ThenBy(x => EF.Property(x!, "TokenHash")), + "CreatedAt" => desc ? q.OrderByDescending(x => EF.Property(x!, "CreatedAt") == null).ThenByDescending(x => EF.Property(x!, "CreatedAt")) : q.OrderBy(x => EF.Property(x!, "CreatedAt") == null).ThenBy(x => EF.Property(x!, "CreatedAt")), + "UpdatedAt" => desc ? q.OrderByDescending(x => EF.Property(x!, "UpdatedAt") == null).ThenByDescending(x => EF.Property(x!, "UpdatedAt")) : q.OrderBy(x => EF.Property(x!, "UpdatedAt") == null).ThenBy(x => EF.Property(x!, "UpdatedAt")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } + + /// Escape hatch: insert without @autoSet stamping (created-at/updated-at + /// written verbatim from ) for import / restore / replication. + public static async global::System.Threading.Tasks.Task InsertPreserving(global::Acme.Generated.AppDbContext db, Gizmo input) + { + db.Gizmos.Add(input); + await db.SaveChangesAsync(); + return input; + } + + // #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled. + // Serializes with the app's configured JSON options, then removes the named keys from each row. + private sealed class CredentialOmittingResult : IResult + { + private readonly object _value; + private readonly string[] _names; + private readonly bool _envelope; + private readonly int _status; + private readonly string? _location; + public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null) + { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; } + public async global::System.Threading.Tasks.Task ExecuteAsync(HttpContext http) + { + var opts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); + Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node); + http.Response.StatusCode = _status; + if (_location is not null) http.Response.Headers.Location = _location; + await http.Response.WriteAsJsonAsync(node, opts); + } + private void Strip(global::System.Text.Json.Nodes.JsonNode? n) + { + if (n is global::System.Text.Json.Nodes.JsonArray a) { foreach (var e in a) Strip(e); return; } + if (n is not global::System.Text.Json.Nodes.JsonObject o) return; + foreach (var key in o.Select(p => p.Key).Where(k => _names.Any(x => string.Equals(x, k, global::System.StringComparison.OrdinalIgnoreCase))).ToList()) + o.Remove(key); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs new file mode 100644 index 0000000000..8a24693ac8 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Line. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class LineFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs new file mode 100644 index 0000000000..d65688d376 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -0,0 +1,183 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class LineRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Label", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps Line REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapLineRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapLineRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/lines", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Lines.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, LineFilterAllowlist.Fields, LineFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortLine(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Lines.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapGet(prefix + "/lines/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Lines.FindAsync(id) is { } found + ? Results.Ok(found) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/lines", async (Line input, global::Acme.Generated.AppDbContext db) => + { + var __vr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateObject( + input, new global::System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true)) + return Results.BadRequest(new { error = "validation" }); + db.Lines.Add(input); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Created(prefix + "/lines", input); + }); + + async global::System.Threading.Tasks.Task UpdateLine(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Lines.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + using var bodyScope = body; + // Deserialize each value with the app's CONFIGURED JSON options, not defaults — + // a field.timestamp binds to DateTimeOffset via a custom converter registered on + // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var target = entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = null; + continue; + } + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + var __pr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(__val, + new global::System.ComponentModel.DataAnnotations.ValidationContext(existing) { MemberName = target.Name }, __pr)) + return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = __val; + } + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Ok(existing); + } + app.MapPatch(prefix + "/lines/{id}", UpdateLine); + app.MapPut(prefix + "/lines/{id}", UpdateLine); + + app.MapDelete(prefix + "/lines/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Lines.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Lines.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortLine(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Label" => desc ? q.OrderByDescending(x => EF.Property(x!, "Label") == null).ThenByDescending(x => EF.Property(x!, "Label")) : q.OrderBy(x => EF.Property(x!, "Label") == null).ThenBy(x => EF.Property(x!, "Label")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs new file mode 100644 index 0000000000..0f92d48114 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsExport.g.cs @@ -0,0 +1,37 @@ +// +// Generated by MetaObjects report-export. Do not edit by hand. +#nullable enable +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace Acme.Shop; + +/// The CSV and XML export of the LineTotals report: its columns, in derived-field order, over the generated row. +public static class LineTotalsExport +{ + /// The XML root element. + public const string Root = "LineTotals"; + + /// The derived field names, in derived-field order: the CSV header row and the XML element names. + public static readonly IReadOnlyList Columns = + [ + "label", + "lines", + ]; + + /// One row's cells in wire form, in order. + public static global::Acme.Generated.ReportExportCell[] Cells(LineTotals row) => + [ + global::Acme.Generated.ReportExportWriter.Cell(row.Label), + global::Acme.Generated.ReportExportWriter.Cell(row.Lines), + ]; + + /// Writes the rows as RFC 4180 CSV. + public static void WriteCsv(TextWriter writer, IEnumerable rows) => + global::Acme.Generated.ReportExportWriter.WriteCsv(writer, Columns, rows.Select(Cells)); + + /// Writes the rows as XML. + public static void WriteXml(TextWriter writer, IEnumerable rows) => + global::Acme.Generated.ReportExportWriter.WriteXml(writer, Root, Columns, rows.Select(Cells)); +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs new file mode 100644 index 0000000000..d25a0e4d5d --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsFilterAllowlist.g.cs @@ -0,0 +1,26 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for LineTotals. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class LineTotalsFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + "label", + "lines", + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + ["label"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + ["lines"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "gt", "gte", "lt", "lte", "in", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs new file mode 100644 index 0000000000..089fda3185 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineTotalsRoutes.g.cs @@ -0,0 +1,105 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class LineTotalsRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Label", + "Lines", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps LineTotals REST routes. Unauthenticated — see remarks. + /// + /// These read endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapLineTotalsRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those read endpoints. + /// + public static IEndpointRouteBuilder MapLineTotalsRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/line_totals", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.LineTotals.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, LineTotalsFilterAllowlist.Fields, LineTotalsFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortLineTotals(q, resolved, desc); + } + + // Pagination (report): every row up to the cap, refused above it. + const int maxRows = 10000; + long? limit = null; + long offset = 0; + if (qs.TryGetValue("limit", out var limitRaw)) + { + if (!long.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var parsedLimit) || parsedLimit < 1) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "limit", value = limitRaw.ToString(), expected = $"an integer from 1 to {maxRows}" }); + if (parsedLimit > maxRows) + return Results.BadRequest(new { error = "report_too_large", maxRows }); + limit = parsedLimit; + } + if (qs.TryGetValue("offset", out var offsetRaw) + && (!long.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out offset) || offset < 0)) + return Results.BadRequest(new { error = "pagination.invalid_value", param = "offset", value = offsetRaw.ToString(), expected = "a non-negative integer (0 or more)" }); + if (offset > 0) q = q.Skip((int)global::System.Math.Min(offset, int.MaxValue)); + q = q.Take((int)(limit ?? maxRows + 1L)); + + var rows = await q.ToListAsync(); + if (limit is null && rows.Count > maxRows) + return Results.BadRequest(new { error = "report_too_large", maxRows }); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.LineTotals.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapPost(prefix + "/line_totals", () => + Results.Json(new { error = "method_not_allowed", message = "POST is not supported on a report (read-only)." }, statusCode: 405)); + + return mount; + } + + private static IOrderedQueryable ApplySortLineTotals(IQueryable q, string field, bool desc) + { + return field switch + { + "Label" => desc ? q.OrderByDescending(x => EF.Property(x!, "Label") == null).ThenByDescending(x => EF.Property(x!, "Label")) : q.OrderBy(x => EF.Property(x!, "Label") == null).ThenBy(x => EF.Property(x!, "Label")), + "Lines" => desc ? q.OrderByDescending(x => EF.Property(x!, "Lines") == null).ThenByDescending(x => EF.Property(x!, "Lines")) : q.OrderBy(x => EF.Property(x!, "Lines") == null).ThenBy(x => EF.Property(x!, "Lines")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs new file mode 100644 index 0000000000..2c516fe2c9 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/ReportExportWriter.g.cs @@ -0,0 +1,169 @@ +// +// Generated by MetaObjects report-export. Do not edit by hand. +// +// The shared writer of every report export: CSV and XML over cells already in wire form. +#nullable enable +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Net; +using System.Text; +using System.Xml; + +namespace Acme.Generated; + +/// One exported cell: its wire-form text (null for a null) and whether the CSV formula-injection guard applies to it. +public readonly record struct ReportExportCell(string? Value, bool IsText); + +/// CSV and XML writers for a report export, and the wire-form conversion of a cell. +public static class ReportExportWriter +{ + /// Start the CSV with a UTF-8 byte order mark. Flip it here, or regenerate with CsvBom = true. + public static readonly bool ExportCsvBom = false; + + /// The project's wire.decimals setting: write a decimal as its canonical string (12.5) rather than as System.Text.Json does (12.50). + public static readonly bool DecimalsAsString = false; + + /// Write a null field as an empty element carrying xsi:nil="true" (and declare xmlns:xsi on the root) instead of as a bare empty element. + public static readonly bool XmlNil = true; + + private const string XsiNamespace = "http://www.w3.org/2001/XMLSchema-instance"; + + /// The wire form of a row property: currency as integer minor units, a date as YYYY-MM-DD, a timestamp as UTC with Z, a boolean as true/false, a null as null. + public static ReportExportCell Cell(object? value) + { + switch (value) + { + case null: return new(null, false); + case string s: return new(s, true); + case bool b: return new(b ? "true" : "false", false); + case DateOnly d: return new(d.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), false); + case TimeOnly t: return new(t.ToString("HH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture), false); + case DateTimeOffset o: return new(Timestamp(o), false); + case DateTime dt: return new(dt.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture), false); + case Guid g: return new(g.ToString("D", CultureInfo.InvariantCulture), false); + case decimal m: return new(DecimalsAsString ? Canonical(m) : m.ToString(CultureInfo.InvariantCulture), false); + case Enum e: return new(e.ToString(), true); + case Uri u: return new(u.OriginalString, true); + case IPAddress ip: return new(ip.ToString(), false); + case IEnumerable: return new(System.Text.Json.JsonSerializer.Serialize(value), false); + case IFormattable f: return new(f.ToString(null, CultureInfo.InvariantCulture), false); + default: return new(Convert.ToString(value, CultureInfo.InvariantCulture), true); + } + } + + // A timestamp as the list route writes it (Iso8601TimestampConverter): UTC with Z, and + // milliseconds only when the instant has a fraction. + private static string Timestamp(DateTimeOffset value) + { + var utc = value.UtcDateTime; + var format = utc.Ticks % TimeSpan.TicksPerSecond == 0 + ? "yyyy-MM-dd'T'HH:mm:ss'Z'" + : "yyyy-MM-dd'T'HH:mm:ss.fff'Z'"; + return utc.ToString(format, CultureInfo.InvariantCulture); + } + + // The canonical decimal string: plain notation, no trailing fraction zeros, zero as "0". + private static string Canonical(decimal value) + { + var s = value.ToString(CultureInfo.InvariantCulture); + if (s.IndexOf('.') >= 0) + { + s = s.TrimEnd('0'); + if (s.EndsWith('.')) s = s.Substring(0, s.Length - 1); + } + return s == "-0" || s.Length == 0 ? "0" : s; + } + + /// + /// Writes RFC 4180 CSV: UTF-8 text, a header row of , CRLF after every record + /// including the last. A cell containing ", ,, CR or LF is quoted with embedded quotes doubled. + /// A string-valued cell starting with =, +, -, @, TAB or CR is prefixed with an + /// apostrophe first (the formula-injection guard); a number, date or boolean never is. A null is an empty cell. + /// + public static void WriteCsv(TextWriter writer, IReadOnlyList columns, IEnumerable rows) + { + if (ExportCsvBom) writer.Write(''); + for (var i = 0; i < columns.Count; i++) + { + if (i > 0) writer.Write(','); + writer.Write(CsvQuote(columns[i])); + } + writer.Write("\r\n"); + foreach (var row in rows) + { + for (var i = 0; i < row.Length; i++) + { + if (i > 0) writer.Write(','); + writer.Write(CsvField(row[i])); + } + writer.Write("\r\n"); + } + } + + /// One CSV field: the injection guard (text cells only), then the quoting. + public static string CsvField(ReportExportCell cell) + { + if (cell.Value is not { } value) return ""; + if (cell.IsText && value.Length > 0 && value[0] is '=' or '+' or '-' or '@' or '\t' or '\r') + value = "'" + value; + return CsvQuote(value); + } + + private static string CsvQuote(string value) => + value.AsSpan().IndexOfAny("\",\r\n") >= 0 ? "\"" + value.Replace("\"", "\"\"", StringComparison.Ordinal) + "\"" : value; + + /// + /// Writes <root><row><field>value</field>...</row>...</root>: no XML declaration, no indentation, + /// text escaped by XmlWriter (& < >, and a CR as a character reference so a parse keeps it). + /// There is no injection guard in XML. A null follows . A character XML 1.0 cannot carry + /// is written as U+FFFD rather than failing the whole export. + /// + public static void WriteXml(TextWriter writer, string root, IReadOnlyList columns, IEnumerable rows) + { + var settings = new XmlWriterSettings + { + OmitXmlDeclaration = true, + Indent = false, + NewLineHandling = NewLineHandling.Entitize, + }; + using var xml = XmlWriter.Create(writer, settings); + xml.WriteStartElement(root); + if (XmlNil) xml.WriteAttributeString("xmlns", "xsi", null, XsiNamespace); + foreach (var row in rows) + { + xml.WriteStartElement("row"); + for (var i = 0; i < columns.Count; i++) + { + xml.WriteStartElement(columns[i]); + if (row[i].Value is { } text) xml.WriteString(XmlSafe(text)); + else if (XmlNil) xml.WriteAttributeString("xsi", "nil", XsiNamespace, "true"); + xml.WriteEndElement(); + } + xml.WriteEndElement(); + } + xml.WriteEndElement(); + } + + private static string XmlSafe(string text) + { + StringBuilder? fixedUp = null; + for (var i = 0; i < text.Length; i++) + { + var c = text[i]; + var ok = XmlConvert.IsXmlChar(c); + if (!ok && i + 1 < text.Length && XmlConvert.IsXmlSurrogatePair(text[i + 1], c)) + { + fixedUp?.Append(c).Append(text[i + 1]); + i++; + continue; + } + if (ok) { fixedUp?.Append(c); continue; } + fixedUp ??= new StringBuilder(text.Length).Append(text, 0, i); + fixedUp.Append('�'); + } + return fixedUp?.ToString() ?? text; + } +} \ No newline at end of file diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs new file mode 100644 index 0000000000..005447dc71 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Tag. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class TagFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs new file mode 100644 index 0000000000..0f591c19cb --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -0,0 +1,185 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class TagRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Name", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps Tag REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapTagRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapTagRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Tags.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, TagFilterAllowlist.Fields, TagFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortTag(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Tags.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapGet(prefix + "/tags/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Tags.FindAsync(id) is { } found + ? Results.Ok(found) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/tags", async (Tag input, global::Acme.Generated.AppDbContext db) => + { + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; + var __vr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateObject( + input, new global::System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true)) + return Results.BadRequest(new { error = "validation" }); + db.Tags.Add(input); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Created(prefix + "/tags", input); + }); + + async global::System.Threading.Tasks.Task UpdateTag(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Tags.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + using var bodyScope = body; + // Deserialize each value with the app's CONFIGURED JSON options, not defaults — + // a field.timestamp binds to DateTimeOffset via a custom converter registered on + // ConfigureHttpJsonOptions, and default options cannot read the wire format, throwing 500. + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + foreach (var prop in body.RootElement.EnumerateObject()) + { + var target = entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = null; + continue; + } + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + var __pr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(__val, + new global::System.ComponentModel.DataAnnotations.ValidationContext(existing) { MemberName = target.Name }, __pr)) + return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = __val; + } + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.Ok(existing); + } + app.MapPatch(prefix + "/tags/{id}", UpdateTag); + app.MapPut(prefix + "/tags/{id}", UpdateTag); + + app.MapDelete(prefix + "/tags/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Tags.FindAsync(id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Tags.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortTag(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Name" => desc ? q.OrderByDescending(x => EF.Property(x!, "Name") == null).ThenByDescending(x => EF.Property(x!, "Name")) : q.OrderBy(x => EF.Property(x!, "Name") == null).ThenBy(x => EF.Property(x!, "Name")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs new file mode 100644 index 0000000000..01cf350d6c --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VanFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Van. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class VanFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + "plate", + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + ["plate"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs new file mode 100644 index 0000000000..3ca9ca06e1 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleFilterAllowlist.g.cs @@ -0,0 +1,24 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for Vehicle. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class VehicleFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + "plate", + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + ["plate"] = new(global::System.StringComparer.Ordinal) { "eq", "ne", "in", "like", "isNull" }, + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs new file mode 100644 index 0000000000..629882cc32 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -0,0 +1,432 @@ +// +// Generated by MetaObjects routes-generator (TPH). Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class VehicleRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Plate", + "VinHash", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + private static readonly global::System.Collections.Generic.HashSet CarSortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Plate", + "VinHash", + "SeatCount", + "RegNo", + }; + + private static readonly global::System.Collections.Generic.Dictionary CarSortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + private static readonly global::System.Collections.Generic.HashSet VanSortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "Id", + "Plate", + "VinHash", + "PayloadKg", + }; + + private static readonly global::System.Collections.Generic.Dictionary VanSortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps Vehicle REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapVehicleRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/vehicles", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Vehicles.AsNoTracking(); + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VehicleFilterAllowlist.Fields, VehicleFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + if (!SortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySort(q, resolved, desc); + } + if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) q = q.Skip(off); + if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) q = q.Take(lim); + var rows = await q.ToListAsync(); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "vinHash" }); + var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.AsNoTracking(), filter.Predicates).CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "vinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/vehicles/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "vinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapGet(prefix + "/vehicles/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + { + var relatedIds = (await db.VehicleTags.AsNoTracking() + .Where(j => EF.Property(j, "VehicleId").Equals(id)) + .Select(j => EF.Property(j, "TagId")) + .ToListAsync()).ToHashSet(); + if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List()); + var rows = await db.Tags.AsNoTracking() + .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) + .ToListAsync(); + return Results.Ok(rows); + }); + + app.MapGet(prefix + "/vehicles/car", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Vehicles.OfType().AsNoTracking(); + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, CarFilterAllowlist.Fields, CarFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + if (!CarSortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : CarSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); + } + if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) q = q.Skip(off); + if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) q = q.Take(lim); + var rows = await q.ToListAsync(); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "vinHash" }); + var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "vinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "vinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/vehicles/car", async (Car input, global::Acme.Generated.AppDbContext db) => + { + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; + input.Kind = default!; + input.Tags = new global::System.Collections.Generic.List(); + // @formExclude / credential: not settable through the generated create; the value is ignored. + input.VinHash = default!; + var __vr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateObject( + input, new global::System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true)) + return Results.BadRequest(new { error = "validation" }); + db.Vehicles.Add(input); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(input, new string[] { "vinHash" }, status: 201, location: prefix + "/vehicles/car/" + input.Id); + }); + + async global::System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + // Configured JSON options (not defaults) so a custom converter — e.g. the + // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it. + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + foreach (var prop in body.RootElement.EnumerateObject()) + { + if (string.Equals(prop.Name, "vinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + var target = entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (string.Equals(target.Name, "Kind", global::System.StringComparison.Ordinal)) continue; // discriminator is immutable + if (string.Equals(target.Name, "RegNo", global::System.StringComparison.Ordinal)) continue; // @mutability: not patch-settable + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = null; + continue; + } + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + var __pr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(__val, + new global::System.ComponentModel.DataAnnotations.ValidationContext(existing) { MemberName = target.Name }, __pr)) + return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = __val; + } + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(existing, new string[] { "vinHash" }); + } + app.MapPatch(prefix + "/vehicles/car/{id}", UpdateCar); + app.MapPut(prefix + "/vehicles/car/{id}", UpdateCar); + + app.MapDelete(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Vehicles.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + app.MapGet(prefix + "/vehicles/car/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + { + if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) + return Results.Ok(new global::System.Collections.Generic.List()); + var relatedIds = (await db.VehicleTags.AsNoTracking() + .Where(j => EF.Property(j, "VehicleId").Equals(id)) + .Select(j => EF.Property(j, "TagId")) + .ToListAsync()).ToHashSet(); + if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List()); + var rows = await db.Tags.AsNoTracking() + .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) + .ToListAsync(); + return Results.Ok(rows); + }); + + app.MapGet(prefix + "/vehicles/van", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.Vehicles.OfType().AsNoTracking(); + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VanFilterAllowlist.Fields, VanFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + if (!VanSortAllowlist.TryGetValue(parts[0], out var resolved)) return Results.BadRequest(new { error = "invalid_sort", field = parts[0] }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : VanSortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = desc ? q.OrderByDescending(x => EF.Property(x!, resolved) == null).ThenByDescending(x => EF.Property(x!, resolved)) : q.OrderBy(x => EF.Property(x!, resolved) == null).ThenBy(x => EF.Property(x!, resolved)); + } + if (qs.TryGetValue("offset", out var offRaw) && int.TryParse(offRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var off) && off > 0) q = q.Skip(off); + if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) q = q.Take(lim); + var rows = await q.ToListAsync(); + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "vinHash" }); + var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "vinHash" }, envelope: true); + }); + + app.MapGet(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found + ? (IResult)new CredentialOmittingResult(found, new string[] { "vinHash" }) + : Results.NotFound(new { error = "not_found" })); + + app.MapPost(prefix + "/vehicles/van", async (Van input, global::Acme.Generated.AppDbContext db) => + { + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; + input.Kind = default!; + input.Tags = new global::System.Collections.Generic.List(); + // @formExclude / credential: not settable through the generated create; the value is ignored. + input.VinHash = default!; + var __vr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateObject( + input, new global::System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true)) + return Results.BadRequest(new { error = "validation" }); + db.Vehicles.Add(input); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(input, new string[] { "vinHash" }, status: 201, location: prefix + "/vehicles/van/" + input.Id); + }); + + async global::System.Threading.Tasks.Task UpdateVan(long id, HttpContext http, global::Acme.Generated.AppDbContext db) + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + global::System.Text.Json.JsonDocument body; + try { body = await global::System.Text.Json.JsonDocument.ParseAsync(http.Request.Body); } + catch (global::System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } + // Configured JSON options (not defaults) so a custom converter — e.g. the + // field.timestamp DateTimeOffset converter — is honored; defaults throw 500 on it. + var jsonOpts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var entry = db.Entry(existing); + foreach (var prop in body.RootElement.EnumerateObject()) + { + if (string.Equals(prop.Name, "vinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable + var target = entry.Metadata.FindProperty(prop.Name) + ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); + if (target is null) continue; + if (target.IsPrimaryKey()) continue; // PK is route-authoritative + if (string.Equals(target.Name, "Kind", global::System.StringComparison.Ordinal)) continue; // discriminator is immutable + if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) + { + // FR-035 PATCH-2: explicit null clears a nullable column; on a + // NOT-NULL (@required) column it is a 400 (matching the cross-port contract). + if (!target.IsNullable) return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = null; + continue; + } + var clr = global::System.Nullable.GetUnderlyingType(target.ClrType) ?? target.ClrType; + var __val = global::System.Text.Json.JsonSerializer.Deserialize(prop.Value.GetRawText(), clr, jsonOpts); + // FR-036 A2 — validate the PRESENT, non-null value with the same per-field + // DataAnnotations as create. This validates ONLY the present value (never the + // whole row) so an ABSENT @required field is untouched, not a 400. + var __pr = new global::System.Collections.Generic.List(); + if (!global::System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(__val, + new global::System.ComponentModel.DataAnnotations.ValidationContext(existing) { MemberName = target.Name }, __pr)) + return Results.BadRequest(new { error = "validation" }); + entry.CurrentValues[target] = __val; + } + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return (IResult)new CredentialOmittingResult(existing, new string[] { "vinHash" }); + } + app.MapPatch(prefix + "/vehicles/van/{id}", UpdateVan); + app.MapPut(prefix + "/vehicles/van/{id}", UpdateVan); + + app.MapDelete(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => + { + var existing = await db.Vehicles.OfType().FirstOrDefaultAsync(x => x.Id == id); + if (existing is null) return Results.NotFound(new { error = "not_found" }); + db.Vehicles.Remove(existing); + try { await db.SaveChangesAsync(); } + catch (global::System.Exception __saveError) + { + if (ConstraintErrors.Classify(__saveError) is { } __constraint) + return Results.Json( + new { error = __constraint.Error, constraint = __constraint.Constraint }, + statusCode: __constraint.Status); + throw; + } + return Results.NoContent(); + }); + + app.MapGet(prefix + "/vehicles/van/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => + { + if (!await db.Vehicles.OfType().AnyAsync(x => x.Id == id)) + return Results.Ok(new global::System.Collections.Generic.List()); + var relatedIds = (await db.VehicleTags.AsNoTracking() + .Where(j => EF.Property(j, "VehicleId").Equals(id)) + .Select(j => EF.Property(j, "TagId")) + .ToListAsync()).ToHashSet(); + if (relatedIds.Count == 0) return Results.Ok(new global::System.Collections.Generic.List()); + var rows = await db.Tags.AsNoTracking() + .Where(t => relatedIds.Contains(EF.Property(t, "Id"))) + .ToListAsync(); + return Results.Ok(rows); + }); + + return mount; + } + + private static IOrderedQueryable ApplySort(IQueryable q, string field, bool desc) + { + return field switch + { + "Id" => desc ? q.OrderByDescending(x => EF.Property(x!, "Id") == null).ThenByDescending(x => EF.Property(x!, "Id")) : q.OrderBy(x => EF.Property(x!, "Id") == null).ThenBy(x => EF.Property(x!, "Id")), + "Plate" => desc ? q.OrderByDescending(x => EF.Property(x!, "Plate") == null).ThenByDescending(x => EF.Property(x!, "Plate")) : q.OrderBy(x => EF.Property(x!, "Plate") == null).ThenBy(x => EF.Property(x!, "Plate")), + "VinHash" => desc ? q.OrderByDescending(x => EF.Property(x!, "VinHash") == null).ThenByDescending(x => EF.Property(x!, "VinHash")) : q.OrderBy(x => EF.Property(x!, "VinHash") == null).ThenBy(x => EF.Property(x!, "VinHash")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } + + // #484 — a credential (view.password) is never sent: the key is OMITTED from the body, not nulled. + // Serializes with the app's configured JSON options, then removes the named keys from each row. + private sealed class CredentialOmittingResult : IResult + { + private readonly object _value; + private readonly string[] _names; + private readonly bool _envelope; + private readonly int _status; + private readonly string? _location; + public CredentialOmittingResult(object value, string[] names, bool envelope = false, int status = 200, string? location = null) + { _value = value; _names = names; _envelope = envelope; _status = status; _location = location; } + public async global::System.Threading.Tasks.Task ExecuteAsync(HttpContext http) + { + var opts = ((global::Microsoft.Extensions.Options.IOptions) + http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) + .Value.SerializerOptions; + var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); + Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node); + http.Response.StatusCode = _status; + if (_location is not null) http.Response.Headers.Location = _location; + await http.Response.WriteAsJsonAsync(node, opts); + } + private void Strip(global::System.Text.Json.Nodes.JsonNode? n) + { + if (n is global::System.Text.Json.Nodes.JsonArray a) { foreach (var e in a) Strip(e); return; } + if (n is not global::System.Text.Json.Nodes.JsonObject o) return; + foreach (var key in o.Select(p => p.Key).Where(k => _names.Any(x => string.Equals(x, k, global::System.StringComparison.OrdinalIgnoreCase))).ToList()) + o.Remove(key); + } + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs new file mode 100644 index 0000000000..c75bfbd98b --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for VehicleTag. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class VehicleTagFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs new file mode 100644 index 0000000000..8ed44140be --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleTagRoutes.g.cs @@ -0,0 +1,88 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class VehicleTagRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "VehicleId", + "TagId", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps VehicleTag REST routes. Unauthenticated — see remarks. + /// + /// These endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapVehicleTagRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those endpoints. + /// + public static IEndpointRouteBuilder MapVehicleTagRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/vehicle_tags", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.VehicleTags.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, VehicleTagFilterAllowlist.Fields, VehicleTagFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortVehicleTag(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.VehicleTags.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + return mount; + } + + private static IOrderedQueryable ApplySortVehicleTag(IQueryable q, string field, bool desc) + { + return field switch + { + "VehicleId" => desc ? q.OrderByDescending(x => EF.Property(x!, "VehicleId") == null).ThenByDescending(x => EF.Property(x!, "VehicleId")) : q.OrderBy(x => EF.Property(x!, "VehicleId") == null).ThenBy(x => EF.Property(x!, "VehicleId")), + "TagId" => desc ? q.OrderByDescending(x => EF.Property(x!, "TagId") == null).ThenByDescending(x => EF.Property(x!, "TagId")) : q.OrderBy(x => EF.Property(x!, "TagId") == null).ThenBy(x => EF.Property(x!, "TagId")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs new file mode 100644 index 0000000000..59cc33e859 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummary.callable.g.cs @@ -0,0 +1,23 @@ +// +// Generated by MetaObjects callable-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; + +namespace Acme.Generated; + +/// +/// FR-015: typed wrapper around the fn_widget_summary stored procedure. Arguments bind in +/// declaration order from the @parameterRef value-object (acme::shop::WidgetArgs). +/// +public static class WidgetSummaryCallable +{ + public static async Task> Call(global::Acme.Generated.AppDbContext db, global::Acme.Shop.WidgetArgs args) + { + return await db.Set() + .FromSqlInterpolated($"SELECT * FROM fn_widget_summary({args.WidgetId}, {args.MaxRows})") + .AsNoTracking() + .ToListAsync(); + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs new file mode 100644 index 0000000000..626419e911 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryFilterAllowlist.g.cs @@ -0,0 +1,22 @@ +// +// Generated by MetaObjects filter-allowlist-generator. Do not edit by hand. +#nullable enable +using System.Collections.Generic; + +namespace Acme.Shop; + +/// +/// GENERATED — per-entity FR-009 filter allowlist for WidgetSummary. +/// lists the filterable field names; +/// constrains the operator vocabulary for each field by its subtype. +/// +public static class WidgetSummaryFilterAllowlist +{ + public static readonly HashSet Fields = new(global::System.StringComparer.Ordinal) + { + }; + + public static readonly Dictionary> OpsByField = new(global::System.StringComparer.Ordinal) + { + }; +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs new file mode 100644 index 0000000000..ab9fd4f4a4 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/WidgetSummaryRoutes.g.cs @@ -0,0 +1,89 @@ +// +// Generated by MetaObjects routes-generator. Do not edit by hand. +#nullable enable +using System.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.EntityFrameworkCore; +using MetaObjects.Codegen.Runtime; + +namespace Acme.Shop; + +public static class WidgetSummaryRoutes +{ + private static readonly global::System.Collections.Generic.HashSet SortAllowlist = new(global::System.StringComparer.OrdinalIgnoreCase) + { + "WidgetId", + }; + + private static readonly global::System.Collections.Generic.Dictionary SortDefaultDesc = new(global::System.StringComparer.OrdinalIgnoreCase) + { + }; + + /// Maps WidgetSummary REST routes. Unauthenticated — see remarks. + /// + /// These read endpoints are unauthenticated. Guard them by mapping on a group that requires + /// authorization, e.g. app.MapGroup("").RequireAuthorization().MapWidgetSummaryRoutes(); + /// A row-ownership rule ("only the owner may read this row") cannot be expressed on a mount: + /// eject this generator with dotnet meta eject and hand-write those read endpoints. + /// + public static IEndpointRouteBuilder MapWidgetSummaryRoutes(this IEndpointRouteBuilder app, string prefix = "/api") + { + IEndpointRouteBuilder mount = app; + app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); + app.MapGet(prefix + "/widget_summaries", async (HttpContext http, global::Acme.Generated.AppDbContext db) => + { + var qs = http.Request.Query; + IQueryable q = db.WidgetSummaries.AsNoTracking(); + + // Filter: ?filter[][]= against the per-entity allowlist. + var filter = EfCoreFilterDispatch.Validate(FilterParser.Parse(qs, WidgetSummaryFilterAllowlist.Fields, WidgetSummaryFilterAllowlist.OpsByField)); + if (filter.ErrorEnvelope is not null) + return Results.BadRequest(new { error = filter.ErrorEnvelope, field = filter.Field }); + q = EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates); + + // Sort: ?sort=field:asc|desc against the static allowlist. + if (qs.TryGetValue("sort", out var sortRaw) && !string.IsNullOrWhiteSpace(sortRaw)) + { + var parts = sortRaw.ToString().Split(':', 2); + var field = parts[0]; + if (!SortAllowlist.TryGetValue(field, out var resolved)) + return Results.BadRequest(new { error = "invalid_sort", field }); + var desc = parts.Length > 1 + ? string.Equals(parts[1], "desc", global::System.StringComparison.OrdinalIgnoreCase) + : SortDefaultDesc.TryGetValue(resolved, out var dd) && dd; + q = ApplySortWidgetSummary(q, resolved, desc); + } + + // Pagination: ?offset=N first (skip), then ?limit=N (take). + if (qs.TryGetValue("offset", out var offsetRaw) && int.TryParse(offsetRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var offset) && offset > 0) + q = q.Skip(offset); + if (qs.TryGetValue("limit", out var limitRaw) && int.TryParse(limitRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var limit) && limit > 0) + q = q.Take(limit); + + var rows = await q.ToListAsync(); + + // withCount=1 → { rows, total } envelope; otherwise bare row array. + var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); + if (!withCount) return Results.Ok(rows); + var totalQ = EfCoreFilterDispatch.ApplyFilter(db.WidgetSummaries.AsNoTracking(), filter.Predicates); + var total = await totalQ.CountAsync(); + return Results.Ok(new { rows, total }); + }); + + app.MapPost(prefix + "/widget_summaries", () => + Results.Json(new { error = "method_not_allowed", message = "POST is not supported on a projection (read-only)." }, statusCode: 405)); + + return mount; + } + + private static IOrderedQueryable ApplySortWidgetSummary(IQueryable q, string field, bool desc) + { + return field switch + { + "WidgetId" => desc ? q.OrderByDescending(x => EF.Property(x!, "WidgetId") == null).ThenByDescending(x => EF.Property(x!, "WidgetId")) : q.OrderBy(x => EF.Property(x!, "WidgetId") == null).ThenBy(x => EF.Property(x!, "WidgetId")), + _ => (IOrderedQueryable)q.OrderBy(x => 0), + }; + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index 4530161144..fd62918023 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -4,6 +4,7 @@ // so the identity-start line, a callable's argument, an extractor's mapper target, a report export // cell and the routes must all say `WidgetID`; `WidgetId` would not compile. +using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using MetaObjects.Codegen; @@ -99,7 +100,6 @@ public void An_extractor_maps_onto_the_resolved_property_names() { var src = Assert.Single(new ExtractorGenerator().Generate(Ctx())).Content; Assert.Contains("GadgetID = ", src); - Assert.Contains("Part = ", src); Assert.DoesNotContain("GadgetId = ", src); } @@ -136,4 +136,236 @@ public void A_report_export_reads_the_resolved_property_names_of_the_row() Assert.Contains("row.LABEL", src); Assert.DoesNotContain("row.Label", src); } + + // ---- every routes site, every field renamed beyond case ---- + + private const string AllSitesModel = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.value": { "name": "Dims", "children": [ + { "field.string": { "name": "unit", "@maxLength": 10 } }, + { "field.int": { "name": "size" } } + ]}}, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@maxLength": 40 } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Gizmo", "children": [ + { "source.rdb": { "@table": "gizmos" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 60, "@filterable": true, "@sortableDefaultOrder": "desc" } }, + { "field.string": { "name": "stamp", "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "serial", "@required": true, "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "field.string": { "name": "tokenHash", "@maxLength": 100, "@formExclude": true } }, + { "field.timestamp": { "name": "createdAt", "@required": true, "@autoSet": "onCreate" } }, + { "field.timestamp": { "name": "updatedAt", "@required": true, "@autoSet": "onUpdate" } }, + { "field.object": { "name": "dims", "@objectRef": "Dims" } }, + { "field.map": { "name": "extras", "@objectRef": "Dims" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["Car", "Van"] } }, + { "field.string": { "name": "plate", "@maxLength": 20, "@filterable": true } }, + { "field.string": { "name": "vinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "VehicleTag" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "Car", "extends": "Vehicle", "@discriminatorValue": "Car", "children": [ + { "field.int": { "name": "seatCount" } }, + { "field.string": { "name": "regNo", "@maxLength": 20, "@mutability": "readOnly" } } + ]}}, + { "object.entity": { "name": "Van", "extends": "Vehicle", "@discriminatorValue": "Van", "children": [ + { "field.int": { "name": "payloadKg" } } + ]}}, + { "object.entity": { "name": "VehicleTag", "children": [ + { "source.rdb": { "@table": "vehicle_tags" } }, + { "field.long": { "name": "vehicleId", "@required": true } }, + { "field.long": { "name": "tagId", "@required": true } }, + { "identity.primary": { "@fields": ["vehicleId", "tagId"] } }, + { "identity.reference": { "name": "fkVehicle", "@fields": "vehicleId", "@references": "Vehicle" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ]}} + ]}} + """; + + // Every field spelled beyond case: nothing here is the PascalCase of its name. + private static string XSpelling(MetaField f) => "X" + CSharpNaming.Pascal(f.Name); + + private static GenContext AllSitesCtx() => AllSitesCtx(XSpelling); + + private static GenContext AllSitesCtx(Func? naming) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(AllSitesModel, id: "all-sites.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig + { + OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal, + PropertyNaming = naming, + }, + }; + } + + private static List AllSites(GenContext ctx) => + new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new FilterAllowlistGenerator().Generate(ctx)) + .Concat(new RoutesGenerator().Generate(ctx)) + .ToList(); + + private static List CompileAll(IEnumerable files) + { + var trees = files.Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)).ToList(); + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + var tpa = (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!; + foreach (var p in tpa.Split(Path.PathSeparator)) if (p.Length > 0) paths.Add(p); + paths.Add(typeof(Microsoft.EntityFrameworkCore.DbContext).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.ModelBuilder).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.PrimaryKeyAttribute).Assembly.Location); + paths.Add(typeof(MetaObjects.Codegen.Runtime.FilterParser).Assembly.Location); + var refs = paths.Where(File.Exists).Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); + var comp = CSharpCompilation.Create("all_sites_" + Guid.NewGuid().ToString("N"), trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + return comp.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()} @ {d.Location}").ToList(); + } + + [Fact] + public void A_model_with_every_routes_site_compiles_with_every_field_renamed() + { + var errors = CompileAll(AllSites(AllSitesCtx())); + Assert.True(errors.Count == 0, "entity + context + filter allowlist + routes should compile:\n" + string.Join("\n", errors)); + } + + [Fact] + public void Without_a_resolver_the_same_model_compiles_and_names_the_pascal_properties() + { + var files = AllSites(AllSitesCtx(null)); + Assert.Empty(CompileAll(files)); + Assert.DoesNotContain("PropertyByField", One(files, "GizmoFilterAllowlist.g.cs")); + } + + [Fact] + public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_every_write() + { + var files = AllSites(AllSitesCtx()); + var gizmo = One(files, "GizmoRoutes.g.cs"); + var vehicle = One(files, "VehicleRoutes.g.cs"); + + // Strip keys: the field name and the resolved name (the body key is the host's naming policy over it). + Assert.Contains("new string[] { \"pinHash\", \"XPinHash\" }", gizmo); + Assert.Contains("new string[] { \"vinHash\", \"XVinHash\" }", vehicle); + + // No response shape bypasses the stripping result: read, list, list-with-count, create, PATCH. + Assert.DoesNotContain("Results.Ok(rows", gizmo); + Assert.DoesNotContain("Results.Ok(found", gizmo); + Assert.DoesNotContain("Results.Ok(existing", gizmo); + Assert.DoesNotContain("Results.Ok(new { rows, total })", gizmo); + Assert.DoesNotContain("Results.Created(", gizmo); + Assert.Contains("new CredentialOmittingResult(", gizmo); + // The TPH routes' only plain Results.Ok(rows) are the M:N Tag lists (no credential on a Tag). + Assert.DoesNotContain("Results.Created(", vehicle); + Assert.DoesNotContain("Results.Ok(existing", vehicle); + Assert.Contains("new CredentialOmittingResult(", vehicle); + + // PATCH refuses to write it: the deny arm matches both spellings (and the form-excluded field's). + foreach (var k in new[] { "pinHash", "XPinHash", "tokenHash", "XTokenHash" }) + Assert.Contains($"string.Equals(prop.Name, \"{k}\", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential", gizmo); + // Create resets the resolved property, so the two writes agree. + Assert.Contains("input.XPinHash = default!;", gizmo); + Assert.Contains("input.XTokenHash = default!;", gizmo); + // The TPH subtype PATCH matches the base's credential under both spellings too. + Assert.Contains("\"XVinHash\"", vehicle); + Assert.Contains("input.XVinHash = default!;", vehicle); + } + + [Fact] + public void A_renamed_value_object_and_map_patch_arm_matches_both_spellings() + { + var gizmo = One(AllSites(AllSitesCtx()), "GizmoRoutes.g.cs"); + Assert.Contains("string.Equals(prop.Name, \"dims\", global::System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XDims\", global::System.StringComparison.OrdinalIgnoreCase)", gizmo); + Assert.Contains("string.Equals(prop.Name, \"extras\", global::System.StringComparison.OrdinalIgnoreCase) || string.Equals(prop.Name, \"XExtras\", global::System.StringComparison.OrdinalIgnoreCase)", gizmo); + Assert.Contains("existing.XDims =", gizmo); + Assert.Contains("existing.XExtras =", gizmo); + } + + [Fact] + public void Sort_and_EF_property_names_are_the_resolved_names_at_every_site() + { + var files = AllSites(AllSitesCtx()); + var gizmo = One(files, "GizmoRoutes.g.cs"); + var vehicle = One(files, "VehicleRoutes.g.cs"); + Assert.Contains("\"XTitle\" =>", gizmo); + Assert.Contains("EF.Property(x!, \"XTitle\")", gizmo); + Assert.Contains("[\"XTitle\"] = true", gizmo); // @sortableDefaultOrder keys + Assert.DoesNotContain("\"Title\"", gizmo); + Assert.Contains("EF.Property(x!, \"XPlate\")", vehicle); // TPH base + Assert.Contains("\"XSeatCount\",", vehicle); // per-subtype sort allowlist + Assert.DoesNotContain("\"Plate\"", vehicle); + // M:N junction: the FK properties and the target key, by their resolved names. + Assert.Contains("EF.Property(j, \"XVehicleId\")", vehicle); + Assert.Contains("EF.Property(j, \"XTagId\")", vehicle); + Assert.Contains("EF.Property(t, \"XId\")", vehicle); + Assert.DoesNotContain("\"VehicleId\"", vehicle); + } + + [Fact] + public void Frozen_autoset_readonly_and_discriminator_members_use_the_resolved_names() + { + var files = AllSites(AllSitesCtx()); + var gizmo = One(files, "GizmoRoutes.g.cs"); + var vehicle = One(files, "VehicleRoutes.g.cs"); + // Frozen (readOnly) members are skipped in the PATCH merge by their property name. + Assert.Contains("\"XStamp\"", gizmo); + Assert.Contains("\"XSerial\"", gizmo); + Assert.DoesNotContain("\"Stamp\"", gizmo); + // @autoSet columns are stamped through the resolved properties. + Assert.Contains("XCreatedAt", gizmo); + Assert.Contains("XUpdatedAt", gizmo); + Assert.DoesNotContain(".CreatedAt", gizmo); + // The TPH discriminator is immutable under its resolved name, and is reset on create. + Assert.Contains("\"XKind\"", vehicle); + Assert.Contains("input.XKind = default!;", vehicle); + Assert.Contains("input.Tags = new", vehicle); // the M:N navigation reset: a navigation, not a field + } + + [Fact] + public void The_filter_dispatch_is_given_the_property_map_when_a_rename_goes_beyond_case() + { + var files = AllSites(AllSitesCtx()); + var allowlist = One(files, "GizmoFilterAllowlist.g.cs"); + Assert.Contains("[\"title\"] = \"XTitle\"", allowlist); + var gizmo = One(files, "GizmoRoutes.g.cs"); + Assert.Contains("GizmoFilterAllowlist.PropertyByField", gizmo); + Assert.Contains("EfCoreFilterDispatch.ApplyFilter(q, filter.Predicates, GizmoFilterAllowlist.PropertyByField)", gizmo); + } + + private sealed class FilterRow + { + public long OwnerKey { get; set; } + } + + [Fact] + public void The_filter_dispatch_finds_a_property_the_resolver_renamed_beyond_case() + { + var predicates = new[] { new MetaObjects.Codegen.Runtime.FilterPredicate("ownerRef", "eq", "5") }; + var map = new Dictionary { ["ownerRef"] = "OwnerKey" }; + var rows = new[] { new FilterRow { OwnerKey = 5 }, new FilterRow { OwnerKey = 6 } }.AsQueryable(); + + // With the map the field resolves to its property; without it the lookup misses (the 500 this guards). + var filtered = MetaObjects.Codegen.Runtime.EfCoreFilterDispatch.ApplyFilter(rows, predicates, map).ToList(); + Assert.Equal(5, Assert.Single(filtered).OwnerKey); + Assert.Throws(() => MetaObjects.Codegen.Runtime.EfCoreFilterDispatch.ApplyFilter(rows, predicates)); + + var bad = MetaObjects.Codegen.Runtime.EfCoreFilterDispatch.Validate( + MetaObjects.Codegen.Runtime.FilterParseResult.Ok([new MetaObjects.Codegen.Runtime.FilterPredicate("ownerRef", "eq", "not-a-number")]), map); + Assert.Equal("invalid_filter_value", bad.ErrorEnvelope); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs new file mode 100644 index 0000000000..52dfb7c92a --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -0,0 +1,138 @@ +// The default output (no property-naming resolver) of the generators the rc.22 property-naming fix +// touched, compared byte for byte against files captured from the generators BEFORE the fix +// (de59161f5): the routes, the callable, the extractor, the report export, the filter allowlist and +// the DbContext (Postgres, so the @sequenceStart identity line is in it). The fix routes each +// field's property name through the resolver; with none set the output must not move. +// +// Capture (only ever against a checkout that predates the fix): GOLDEN_WRITE=1 dotnet test +// --filter PropertyNamingGoldenTests. Compare mode is the default. + +using System.Runtime.CompilerServices; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class PropertyNamingGoldenTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme::shop", "children": [ + { "object.value": { "name": "Dims", "children": [ + { "field.string": { "name": "unit", "@maxLength": 10 } }, + { "field.int": { "name": "size" } } + ]}}, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "name", "@maxLength": 40 } }, + { "identity.primary": { "@fields": "id", "@generation": "increment", "@sequenceStart": 500 } } + ]}}, + { "object.entity": { "name": "Gizmo", "children": [ + { "source.rdb": { "@table": "gizmos" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 60, "@filterable": true, "@sortableDefaultOrder": "desc" } }, + { "field.string": { "name": "stamp", "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "serial", "@required": true, "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "field.string": { "name": "tokenHash", "@maxLength": 100, "@formExclude": true } }, + { "field.timestamp": { "name": "createdAt", "@required": true, "@autoSet": "onCreate" } }, + { "field.timestamp": { "name": "updatedAt", "@required": true, "@autoSet": "onUpdate" } }, + { "field.object": { "name": "dims", "@objectRef": "Dims" } }, + { "field.map": { "name": "extras", "@objectRef": "Dims" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Vehicle", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "vehicles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["Car", "Van"] } }, + { "field.string": { "name": "plate", "@maxLength": 20, "@filterable": true } }, + { "field.string": { "name": "vinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "VehicleTag" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "Car", "extends": "Vehicle", "@discriminatorValue": "Car", "children": [ + { "field.int": { "name": "seatCount" } }, + { "field.string": { "name": "regNo", "@maxLength": 20, "@mutability": "readOnly" } } + ]}}, + { "object.entity": { "name": "Van", "extends": "Vehicle", "@discriminatorValue": "Van", "children": [ + { "field.int": { "name": "payloadKg" } } + ]}}, + { "object.entity": { "name": "VehicleTag", "children": [ + { "source.rdb": { "@table": "vehicle_tags" } }, + { "field.long": { "name": "vehicleId", "@required": true } }, + { "field.long": { "name": "tagId", "@required": true } }, + { "identity.primary": { "@fields": ["vehicleId", "tagId"] } }, + { "identity.reference": { "name": "fkVehicle", "@fields": "vehicleId", "@references": "Vehicle" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ]}} + ,{ "object.value": { "name": "WidgetArgs", "children": [ + { "field.long": { "name": "widgetId", "@required": true } }, + { "field.int": { "name": "maxRows" } } + ]}}, + { "object.projection": { "name": "WidgetSummary", "children": [ + { "source.rdb": { "@kind": "storedProc", "@proc": "fn_widget_summary", "@parameterRef": "WidgetArgs" } }, + { "field.long": { "name": "widgetId" } } + ]}}, + { "object.value": { "name": "Part", "children": [ + { "field.string": { "name": "partName", "@required": true } } + ]}}, + { "object.value": { "name": "Gadget", "children": [ + { "field.string": { "name": "gadgetId", "@required": true } }, + { "field.object": { "name": "part", "@objectRef": "Part" } } + ]}}, + { "template.prompt": { "name": "GadgetOut", "@payloadRef": "Gadget", "@responseRef": "Gadget", + "@textRef": "ai/gadget", "@format": "text", "@responseFormat": "json", "@promptStyle": "guide" } }, + { "object.entity": { "name": "Line", "children": [ + { "source.rdb": { "@table": "lines" } }, + { "field.long": { "name": "id", "@required": true } }, + { "field.string": { "name": "label", "@maxLength": 40 } }, + { "identity.primary": { "name": "id", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "label", "@of": "Line.label" } }, + { "measure.aggregate": { "name": "lines", "@agg": "count", "@of": "Line.id" } } + ]}}, + { "object.report": { "name": "LineTotals", "@from": "Line", "@dimensions": ["label"], "@measures": ["lines"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_line_totals" } } ] } } + ]}} + """; + + private static string GoldenDir([CallerFilePath] string here = "") => + Path.Combine(Path.GetDirectoryName(here)!, "Golden", "pre-rc22-propname"); + + [Fact] + public void Default_output_matches_the_output_captured_before_the_property_naming_fix() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "golden-rc22.json")]); + Assert.Empty(r.Errors); + GenContext Ctx(string? dialect = null) => new() + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal, Dialect = dialect }, + }; + var files = new RoutesGenerator().Generate(Ctx()) + .Concat(new CallableGenerator().Generate(Ctx())) + .Concat(new ExtractorGenerator().Generate(Ctx())) + .Concat(new ReportExportGenerator().Generate(Ctx())) + .Concat(new FilterAllowlistGenerator().Generate(Ctx())) + .Concat(new DbContextGenerator().Generate(Ctx("postgres"))) + .ToList(); + var names = files.Select(f => System.IO.Path.GetFileName(f.Path)).ToList(); + foreach (var name in new[] { "VehicleRoutes.g.cs", "GizmoRoutes.g.cs", "WidgetSummary.callable.g.cs", "LineTotalsExport.g.cs", "AppDbContext.g.cs", "GizmoFilterAllowlist.g.cs" }) + Assert.Contains(name, names); + Assert.True(names.Any(n => n.Contains("Extractor")), string.Join(",", names)); + + var dir = GoldenDir(); + if (Environment.GetEnvironmentVariable("GOLDEN_WRITE") == "1") + { + Directory.CreateDirectory(dir); + foreach (var f in files) File.WriteAllText(Path.Combine(dir, System.IO.Path.GetFileName(f.Path)), f.Content); + return; + } + var expected = Directory.GetFiles(dir).Select(p => Path.GetFileName(p)).Order().ToList(); + Assert.Equal(expected, files.Select(f => System.IO.Path.GetFileName(f.Path)).Order().ToList()); + foreach (var f in files) + Assert.Equal(File.ReadAllText(Path.Combine(dir, System.IO.Path.GetFileName(f.Path))), f.Content); + } +} From 7a208757d833dc728baf04a3f9da81ed999ad5f3 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:42:06 -0500 Subject: [PATCH 238/267] docs(changelog): the security fix, the sort-key and hook behaviour changes, a narrower fix claim Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 49 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32d837237b..aba4c9bd67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -380,6 +380,21 @@ vocabulary; upgrade every port together. ### Changed +- **Behaviour change, C#: with a property rename beyond case, the accepted `?sort=` key is the + resolved property name (rc.22).** The sort allowlist, `@sortableDefaultOrder` keys and the + `EF.Property` names carry the resolved name (EF matches the model's property name, so before + this any rename made a sort return 500). A project with no resolver, or one whose rename differs + only in case, is unchanged (the key is matched case-insensitively). With `ownerRef` spelled + `OwnerKey`, `?sort=ownerRef` becomes `400 invalid_sort` and `?sort=OwnerKey` is accepted. + `?filter[]` keeps the field name. + +- **Behaviour change, C#: a `PropertyName` hook that disagrees with `GenConfig.PropertyNaming` is + refused (rc.22).** `EntityGenerator.PropertyName` and `DbContextGenerator.PropertyName` default to + the resolver and are now `[Obsolete]`. Only the resolver reaches every generator (routes, callable, + extractor, report export, filter map), so an override that names any field differently from it + stops the run with an error naming the field and saying to set `GenConfig.PropertyNaming`. Move + the override's logic into the resolver. An override that agrees with the resolver is unaffected. + - **Behaviour change: the registry manifest no longer lists `@dbColumnType`'s `allowedValues` (rc.21).** The sized text spellings (`varchar(n)`, `character varying(n)`, `character(n)`) are no closed set, so the value is parsed by each port's loader instead (a misspelling is still @@ -658,17 +673,33 @@ vocabulary; upgrade every port together. already named a missing variable, regenerate and fix the name; the generated helper text changes (TypeScript `prompts.ts` and Python helpers gain a `verify` argument). +### Security + +- **Fix, C#: a credential or write-denied field renamed by the property-naming resolver can no longer + escape its protection (rc.22).** The routes keyed credential stripping (`view.password` fields are + omitted from every body), the PATCH write-deny of `@formExclude` and credential fields, and the + PATCH value-object and map arms on the metadata field name. An entity property serializes under + the host's naming policy applied to the resolved property name, so with a rename beyond case + (`pinHash` spelled `Secret`) the stripping missed the key and sent the credential in every read, + list, create and update response, and `PATCH {"secret": "x"}` wrote it. Stripping and the PATCH + arms now match the field name and the resolved name, so create and PATCH agree. A rename that is + only a different case was never affected. Regenerate any project that sets + `GenConfig.PropertyNaming`. + ### Fixed -- **Fix, C#: every generator names a field's property through the one property-naming resolver - (rc.22).** Since rc.20 `GenConfig.PropertyNaming` (and the `PropertyName` hook) renamed a field's - property in the entity, the context's model lines, the reverse finders and the composite key, but - these emit sites still spelled `Pascal(field.Name)`: the `@sequenceStart` identity annotation in - `DbContextGenerator` (a key renamed `WidgetID` got `.Property(x => x.WidgetId)`, CS1061), the - argument properties in `CallableGenerator`, the mapper targets in `ExtractorGenerator`, the row - cells in `ReportExportGenerator`, and the `RoutesGenerator` key, sort-allowlist, `EF.Property`, - frozen, auto-set, value-object, create-reset, TPH discriminator and M:N junction names. With no - resolver set the output is unchanged. +- **Fix, C#: the generators name a field's property through the one property-naming resolver + (rc.22).** Since rc.20 `GenConfig.PropertyNaming` renamed a field's property in the entity, the + context's model lines, the reverse finders and the composite key, but these emit sites still + spelled `Pascal(field.Name)`: the `@sequenceStart` identity annotation in `DbContextGenerator` (a + key renamed `WidgetID` got `.Property(x => x.WidgetId)`, CS1061), the argument properties in + `CallableGenerator`, the mapper targets in `ExtractorGenerator`, the row cells in + `ReportExportGenerator`, and the `RoutesGenerator` key, sort-allowlist, `EF.Property`, frozen, + auto-set, value-object, create-reset, TPH discriminator and M:N junction names. The runtime filter + dispatch looked a property up by the field name, so `?filter[]` on a property renamed + beyond case threw (500); the generated allowlist now carries a field-to-property map, emitted only + when a rename goes beyond case, and `EfCoreFilterDispatch.ApplyFilter` and `Validate` take it as an + optional argument. With no resolver set the output is byte-identical (pinned by a golden test). - **Fix, TypeScript and C#: a passthrough may walk a reference backwards when at most one row references it (rc.21).** A reverse hop was always to-many, so a passthrough over it was refused From be17ec1d5f54f0ace578271c4027e3d75b5d2f93 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:59:34 -0500 Subject: [PATCH 239/267] fix(csharp): credential stripping and the PATCH key lookup use the serializer's own JSON keys The key a property is written under comes from JsonSerializerOptions.GetTypeInfo, so a naming policy (snake, kebab, camel), a rename or an attribute cannot escape the omit list, and a multi-word field is found by PATCH under any policy. The DbContext hook guard now covers value-object members and subtype fields. Co-Authored-By: Claude Opus 5.5 --- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 31 ++++--- .../Golden/pre-rc22-propname/LineRoutes.g.cs | 5 +- .../Golden/pre-rc22-propname/TagRoutes.g.cs | 5 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 49 +++++------ .../PropertyNamingEmitSitesTests.cs | 13 ++- .../ReportCredentialCodegenTests.cs | 8 +- .../ReportExportGeneratorTests.cs | 2 +- .../SecretFieldsCodegenTests.cs | 4 +- .../Generators/DbContextGenerator.cs | 4 +- .../Generators/RoutesGenerator.cs | 39 +++++---- .../MetaObjects.Codegen/HelperRuntime.cs | 3 + .../MetaObjects.Codegen.csproj | 1 + .../Runtime/ReportExportHttp.cs | 14 +--- .../Runtime/SerializerKeys.cs | 82 +++++++++++++++++++ 14 files changed, 181 insertions(+), 79 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 4f7032f829..5086b0bc8d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -74,15 +74,15 @@ public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder ap // withCount=1 → { rows, total } envelope; otherwise bare row array. var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); - if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "pinHash" }); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "PinHash" }); var totalQ = EfCoreFilterDispatch.ApplyFilter(db.Gizmos.AsNoTracking(), filter.Predicates); var total = await totalQ.CountAsync(); - return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "pinHash" }, envelope: true); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "PinHash" }, envelope: true); }); app.MapGet(prefix + "/gizmos/{id}", async (long id, global::Acme.Generated.AppDbContext db) => await db.Gizmos.FindAsync(id) is { } found - ? (IResult)new CredentialOmittingResult(found, new string[] { "pinHash" }) + ? (IResult)new CredentialOmittingResult(found, new string[] { "PinHash" }) : Results.NotFound(new { error = "not_found" })); app.MapPost(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -128,7 +128,7 @@ await db.Gizmos.FindAsync(id) is { } found statusCode: __constraint.Status); throw; } - return (IResult)new CredentialOmittingResult(input, new string[] { "pinHash" }, status: 201, location: prefix + "/gizmos"); + return (IResult)new CredentialOmittingResult(input, new string[] { "PinHash" }, status: 201, location: prefix + "/gizmos"); }); async global::System.Threading.Tasks.Task UpdateGizmo(long id, HttpContext http, global::Acme.Generated.AppDbContext db) @@ -147,11 +147,14 @@ await db.Gizmos.FindAsync(id) is { } found .Value.SerializerOptions; var entry = db.Entry(existing); existing.UpdatedAt = global::System.DateTimeOffset.UtcNow; + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); foreach (var prop in body.RootElement.EnumerateObject()) { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + if (__clr is "PinHash" or "TokenHash") continue; // @formExclude / credential: not writable if (string.Equals(prop.Name, "pinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable if (string.Equals(prop.Name, "tokenHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable - if (string.Equals(prop.Name, "dims", global::System.StringComparison.OrdinalIgnoreCase)) + if (string.Equals(prop.Name, "dims", global::System.StringComparison.OrdinalIgnoreCase) || __clr == "Dims") { if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { @@ -165,7 +168,7 @@ await db.Gizmos.FindAsync(id) is { } found existing.Dims = __vo0; continue; } - if (string.Equals(prop.Name, "extras", global::System.StringComparison.OrdinalIgnoreCase)) + if (string.Equals(prop.Name, "extras", global::System.StringComparison.OrdinalIgnoreCase) || __clr == "Extras") { if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null) { existing.Extras = null; continue; } @@ -176,7 +179,8 @@ await db.Gizmos.FindAsync(id) is { } found existing.Extras = __map0; continue; } - var target = entry.Metadata.FindProperty(prop.Name) + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; if (target.IsPrimaryKey()) continue; // PK is route-authoritative @@ -212,7 +216,7 @@ await db.Gizmos.FindAsync(id) is { } found statusCode: __constraint.Status); throw; } - return (IResult)new CredentialOmittingResult(existing, new string[] { "pinHash" }); + return (IResult)new CredentialOmittingResult(existing, new string[] { "PinHash" }); } app.MapPatch(prefix + "/gizmos/{id}", UpdateGizmo); app.MapPut(prefix + "/gizmos/{id}", UpdateGizmo); @@ -279,17 +283,12 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); - Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node); + // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. + SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, + SerializerKeys.KeysOf(_value, _envelope, opts, _names)); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); } - private void Strip(global::System.Text.Json.Nodes.JsonNode? n) - { - if (n is global::System.Text.Json.Nodes.JsonArray a) { foreach (var e in a) Strip(e); return; } - if (n is not global::System.Text.Json.Nodes.JsonObject o) return; - foreach (var key in o.Select(p => p.Key).Where(k => _names.Any(x => string.Equals(x, k, global::System.StringComparison.OrdinalIgnoreCase))).ToList()) - o.Remove(key); - } } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs index d65688d376..868d94285a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/LineRoutes.g.cs @@ -112,9 +112,12 @@ await db.Lines.FindAsync(id) is { } found http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); foreach (var prop in body.RootElement.EnumerateObject()) { - var target = entry.Metadata.FindProperty(prop.Name) + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; if (target.IsPrimaryKey()) continue; // PK is route-authoritative diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs index 0f591c19cb..9ef4ee823e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/TagRoutes.g.cs @@ -114,9 +114,12 @@ await db.Tags.FindAsync(id) is { } found http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); foreach (var prop in body.RootElement.EnumerateObject()) { - var target = entry.Metadata.FindProperty(prop.Name) + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; if (target.IsPrimaryKey()) continue; // PK is route-authoritative diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 629882cc32..d6cc9882f7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -79,14 +79,14 @@ public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) q = q.Take(lim); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); - if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "vinHash" }); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.AsNoTracking(), filter.Predicates).CountAsync(); - return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "vinHash" }, envelope: true); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); }); app.MapGet(prefix + "/vehicles/{id}", async (long id, global::Acme.Generated.AppDbContext db) => await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found - ? (IResult)new CredentialOmittingResult(found, new string[] { "vinHash" }) + ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) : Results.NotFound(new { error = "not_found" })); app.MapGet(prefix + "/vehicles/{id}/tags", async (long id, global::Acme.Generated.AppDbContext db) => @@ -122,14 +122,14 @@ await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } fou if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) q = q.Take(lim); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); - if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "vinHash" }); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); - return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "vinHash" }, envelope: true); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); }); app.MapGet(prefix + "/vehicles/car/{id}", async (long id, global::Acme.Generated.AppDbContext db) => await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found - ? (IResult)new CredentialOmittingResult(found, new string[] { "vinHash" }) + ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) : Results.NotFound(new { error = "not_found" })); app.MapPost(prefix + "/vehicles/car", async (Car input, global::Acme.Generated.AppDbContext db) => @@ -154,7 +154,7 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == statusCode: __constraint.Status); throw; } - return (IResult)new CredentialOmittingResult(input, new string[] { "vinHash" }, status: 201, location: prefix + "/vehicles/car/" + input.Id); + return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/car/" + input.Id); }); async global::System.Threading.Tasks.Task UpdateCar(long id, HttpContext http, global::Acme.Generated.AppDbContext db) @@ -170,10 +170,14 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); foreach (var prop in body.RootElement.EnumerateObject()) { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + if (__clr is "VinHash") continue; // @formExclude / credential: not writable if (string.Equals(prop.Name, "vinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable - var target = entry.Metadata.FindProperty(prop.Name) + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; if (target.IsPrimaryKey()) continue; // PK is route-authoritative @@ -207,7 +211,7 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == statusCode: __constraint.Status); throw; } - return (IResult)new CredentialOmittingResult(existing, new string[] { "vinHash" }); + return (IResult)new CredentialOmittingResult(existing, new string[] { "VinHash" }); } app.MapPatch(prefix + "/vehicles/car/{id}", UpdateCar); app.MapPut(prefix + "/vehicles/car/{id}", UpdateCar); @@ -264,14 +268,14 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == if (qs.TryGetValue("limit", out var limRaw) && int.TryParse(limRaw, global::System.Globalization.NumberStyles.Integer, global::System.Globalization.CultureInfo.InvariantCulture, out var lim) && lim > 0) q = q.Take(lim); var rows = await q.ToListAsync(); var withCount = qs.TryGetValue("withCount", out var wc) && (wc == "1" || string.Equals(wc, "true", global::System.StringComparison.OrdinalIgnoreCase)); - if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "vinHash" }); + if (!withCount) return (IResult)new CredentialOmittingResult(rows, new string[] { "VinHash" }); var total = await EfCoreFilterDispatch.ApplyFilter(db.Vehicles.OfType().AsNoTracking(), filter.Predicates).CountAsync(); - return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "vinHash" }, envelope: true); + return (IResult)new CredentialOmittingResult(new { rows, total }, new string[] { "VinHash" }, envelope: true); }); app.MapGet(prefix + "/vehicles/van/{id}", async (long id, global::Acme.Generated.AppDbContext db) => await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == id) is { } found - ? (IResult)new CredentialOmittingResult(found, new string[] { "vinHash" }) + ? (IResult)new CredentialOmittingResult(found, new string[] { "VinHash" }) : Results.NotFound(new { error = "not_found" })); app.MapPost(prefix + "/vehicles/van", async (Van input, global::Acme.Generated.AppDbContext db) => @@ -296,7 +300,7 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == statusCode: __constraint.Status); throw; } - return (IResult)new CredentialOmittingResult(input, new string[] { "vinHash" }, status: 201, location: prefix + "/vehicles/van/" + input.Id); + return (IResult)new CredentialOmittingResult(input, new string[] { "VinHash" }, status: 201, location: prefix + "/vehicles/van/" + input.Id); }); async global::System.Threading.Tasks.Task UpdateVan(long id, HttpContext http, global::Acme.Generated.AppDbContext db) @@ -312,10 +316,14 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var entry = db.Entry(existing); + var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts); foreach (var prop in body.RootElement.EnumerateObject()) { + var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null; + if (__clr is "VinHash") continue; // @formExclude / credential: not writable if (string.Equals(prop.Name, "vinHash", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable - var target = entry.Metadata.FindProperty(prop.Name) + var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr)) + ?? entry.Metadata.FindProperty(prop.Name) ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase)); if (target is null) continue; if (target.IsPrimaryKey()) continue; // PK is route-authoritative @@ -348,7 +356,7 @@ await db.Vehicles.OfType().AsNoTracking().FirstOrDefaultAsync(x => x.Id == statusCode: __constraint.Status); throw; } - return (IResult)new CredentialOmittingResult(existing, new string[] { "vinHash" }); + return (IResult)new CredentialOmittingResult(existing, new string[] { "VinHash" }); } app.MapPatch(prefix + "/vehicles/van/{id}", UpdateVan); app.MapPut(prefix + "/vehicles/van/{id}", UpdateVan); @@ -416,17 +424,12 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); - Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node); + // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. + SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, + SerializerKeys.KeysOf(_value, _envelope, opts, _names)); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); } - private void Strip(global::System.Text.Json.Nodes.JsonNode? n) - { - if (n is global::System.Text.Json.Nodes.JsonArray a) { foreach (var e in a) Strip(e); return; } - if (n is not global::System.Text.Json.Nodes.JsonObject o) return; - foreach (var key in o.Select(p => p.Key).Where(k => _names.Any(x => string.Equals(x, k, global::System.StringComparison.OrdinalIgnoreCase))).ToList()) - o.Remove(key); - } } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index fd62918023..51a65f656a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -259,9 +259,12 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ var gizmo = One(files, "GizmoRoutes.g.cs"); var vehicle = One(files, "VehicleRoutes.g.cs"); - // Strip keys: the field name and the resolved name (the body key is the host's naming policy over it). - Assert.Contains("new string[] { \"pinHash\", \"XPinHash\" }", gizmo); - Assert.Contains("new string[] { \"vinHash\", \"XVinHash\" }", vehicle); + // The credential is named by its CLR property; the JSON key is the serializer's, read at run time + // (SerializerKeys.KeysOf), never spelled here. + Assert.Contains("new string[] { \"XPinHash\" }", gizmo); + Assert.Contains("new string[] { \"XVinHash\" }", vehicle); + Assert.Contains("SerializerKeys.KeysOf(_value, _envelope, opts, _names)", gizmo); + Assert.DoesNotContain("OrdinalIgnoreCase))\n o.Remove", gizmo); // No response shape bypasses the stripping result: read, list, list-with-count, create, PATCH. Assert.DoesNotContain("Results.Ok(rows", gizmo); @@ -275,7 +278,9 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ Assert.DoesNotContain("Results.Ok(existing", vehicle); Assert.Contains("new CredentialOmittingResult(", vehicle); - // PATCH refuses to write it: the deny arm matches both spellings (and the form-excluded field's). + // PATCH refuses to write it: the deny arm matches the serializer-resolved property, and both spellings. + Assert.Contains("if (__clr is \"XPinHash\" or \"XTokenHash\") continue;", gizmo); + Assert.Contains("SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts)", gizmo); foreach (var k in new[] { "pinHash", "XPinHash", "tokenHash", "XTokenHash" }) Assert.Contains($"string.Equals(prop.Name, \"{k}\", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential", gizmo); // Create resets the resolved property, so the two writes agree. diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs index e295d890d7..39caf0d6d7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportCredentialCodegenTests.cs @@ -78,10 +78,10 @@ public void A_report_over_a_credential_omits_it_from_rows_and_export(string repo { var ctx = Ctx(Load()); var routes = Routes(ctx, report); - Assert.Contains($"new string[] {{ \"{column}\" }}", routes); + Assert.Contains($"new string[] {{ \"{char.ToUpperInvariant(column[0])}{column[1..]}\" }}", routes); Assert.DoesNotContain("Results.Ok(rows)", routes); // The JSON export strips it too; the CSV / XML column list names no credential. - Assert.Contains($"rows, new string[] {{ \"{column}\" }}", routes); + Assert.Contains($"rows, new string[] {{ \"{char.ToUpperInvariant(column[0])}{column[1..]}\" }}", routes); var export = Export(ctx, report); Assert.DoesNotContain($"\"{column}\"", export); Assert.DoesNotContain($"row.{char.ToUpperInvariant(column[0])}{column[1..]}", export); @@ -113,7 +113,9 @@ public void A_credential_column_is_neither_filterable_nor_sortable(string report var routes = Routes(ctx, report); var pascal = char.ToUpperInvariant(column[0]) + column[1..]; - Assert.DoesNotContain($"\"{pascal}\"", routes); + // The credential's CLR name appears once, in the omit list; never as a sort-allowlist entry or sort arm. + Assert.DoesNotContain($" \"{pascal}\",", routes); + Assert.DoesNotContain($"\"{pascal}\" =>", routes); Assert.Contains($"\"{char.ToUpperInvariant(kept[0])}{kept[1..]}\"", routes); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs index f3b9c3a665..df64e8deb9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportExportGeneratorTests.cs @@ -317,7 +317,7 @@ public sealed record PinRow(string Name, string PinHash, long Accounts); RequestServices = Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(services), }; http.Response.Body = new MemoryStream(); - await ReportExportHttp.Json(http, "accounts-by-pin", body, ["pinHash"], envelope).ExecuteAsync(http); + await ReportExportHttp.Json(http, "accounts-by-pin", body, ["PinHash"], envelope).ExecuteAsync(http); Assert.Equal("attachment; filename=\"accounts-by-pin.json\"", http.Response.Headers.ContentDisposition.ToString()); http.Response.Body.Position = 0; return System.Text.Json.Nodes.JsonNode.Parse(http.Response.Body)!; diff --git a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs index b02a9da1b0..ec10196e5f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SecretFieldsCodegenTests.cs @@ -96,7 +96,7 @@ public void A_tph_column_marked_on_another_subtype_is_hidden_and_ignored_on_this Assert.True(start >= 0 && end > start, src); var aRoutes = src[start..end]; - Assert.Contains("new string[] { \"token\" }", aRoutes); + Assert.Contains("new string[] { \"Token\" }", aRoutes); Assert.Contains("input.Token = default!;", aRoutes); Assert.Contains("input.Memo = default!;", aRoutes); Assert.Contains("string.Equals(prop.Name, \"token\", global::System.StringComparison.OrdinalIgnoreCase)) continue;", aRoutes); @@ -118,7 +118,7 @@ public void Write_paths_name_both_denied_fields_and_read_hides_only_the_credenti Assert.Contains("string.Equals(prop.Name, \"pinHash\", global::System.StringComparison.OrdinalIgnoreCase)) continue;", src); // Only the credential is omitted on read (list, get, create echo, update echo). - Assert.Contains("new string[] { \"pinHash\" }", src); + Assert.Contains("new string[] { \"PinHash\" }", src); Assert.DoesNotContain("\"tokenHash\" }", src); Assert.DoesNotContain("new string[] { \"tokenHash\"", src); Assert.DoesNotContain("Results.Ok(rows)", src); diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 84077938cb..31826361d7 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -102,7 +102,9 @@ public virtual IEnumerable Generate(GenContext ctx) .OrderBy(o => o.Name, StringComparer.Ordinal) .ToList(); if (objects.Count == 0) return []; - CSharpNaming.RefuseDivergingPropertyHook(Name, objects, ctx.Config, PropertyName); + // Every object the context names a property of: the DbSet entities and views, but also the value-object + // members its owned and flattened configuration reaches and a TPH subtype's own fields. + CSharpNaming.RefuseDivergingPropertyHook(Name, ReportRows.WithReportRows(ctx), ctx.Config, PropertyName); // One context, one property per name (CS0102 otherwise), claimed as emitted: an object // that gets no DbSet here never takes part. Two objects on one table are EF's to refuse // (it does, at model build), not this generator's. diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 0ff6ca57c3..acb75724f2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -452,7 +452,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine(" var entry = db.Entry(existing);"); AppendUpdateAutoSet(sb, autoSetFields); AppendPartialMergeLoop(sb, null, voFields, mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(entity), - deniedFields.SelectMany(f => WireKeys(f, ctx.Config)).ToList(), HasDurationField(entity)); + deniedFields.SelectMany(f => WireKeys(f, ctx.Config)).ToList(), deniedFields.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(), HasDurationField(entity)); AppendSaveChanges(sb); AppendArrayNullClears(sb, voFields, tableRef, pkColumnRef); // #214 — writes target the table; for a write-through entity re-read the row @@ -845,8 +845,10 @@ private static List WireKeys(MetaField f, GenConfig config) => new[] { f.Name, CSharpNaming.PropertyName(f, config) } .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + // The CLR property names of an entity's credentials. The JSON key each is written under is not + // derived here: the generated result asks the host's serializer (SerializerKeys.KeysOf). private static List CredentialNames(MetaObject entity, GenConfig config) => - entity.Fields().Where(IsCredentialField).SelectMany(f => WireKeys(f, config)).ToList(); + entity.Fields().Where(IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. private static string KeyMatch(IEnumerable keys) => @@ -899,18 +901,13 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" http.RequestServices.GetService(typeof(global::Microsoft.Extensions.Options.IOptions))!)"); sb.AppendLine(" .Value.SerializerOptions;"); sb.AppendLine(" var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); - sb.AppendLine(" Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node);"); + sb.AppendLine(" // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names."); + sb.AppendLine($" SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node,"); + sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names));"); sb.AppendLine(" http.Response.StatusCode = _status;"); sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); sb.AppendLine(" }"); - sb.AppendLine(" private void Strip(global::System.Text.Json.Nodes.JsonNode? n)"); - sb.AppendLine(" {"); - sb.AppendLine(" if (n is global::System.Text.Json.Nodes.JsonArray a) { foreach (var e in a) Strip(e); return; }"); - sb.AppendLine(" if (n is not global::System.Text.Json.Nodes.JsonObject o) return;"); - sb.AppendLine(" foreach (var key in o.Select(p => p.Key).Where(k => _names.Any(x => string.Equals(x, k, global::System.StringComparison.OrdinalIgnoreCase))).ToList())"); - sb.AppendLine(" o.Remove(key);"); - sb.AppendLine(" }"); sb.AppendLine(" }"); } @@ -1335,7 +1332,7 @@ private static void AppendPartialMergeLoop( StringBuilder sb, string? discProp, IReadOnlyList voFields, IReadOnlyList mapVoFields, IReadOnlyList autoSetNavs, IReadOnlyList frozenNavs, bool hasDecimal, - IReadOnlyList deniedKeys, bool hasDuration = false) + IReadOnlyList deniedKeys, IReadOnlyList deniedClr, bool hasDuration = false) { // A nullable array-of-VO column that a request clears to null (present-null) can NOT be // NULLed by an owned-nav assignment — EF OwnsMany(...).ToJson writes `[]` for a null @@ -1345,10 +1342,17 @@ private static void AppendPartialMergeLoop( if (voFields[i].IsArray && !voFields[i].Required) sb.AppendLine($" var __clearVo{i} = false;"); + // The body key -> CLR property map comes from the host serializer's own contract (a naming policy + // such as SnakeCaseLower, a rename, an attribute), never from a guess at the name: the keys a + // client echoes from a response are the keys this resolves. + sb.AppendLine($" var __keys = SerializerKeys.PropertyByKey(existing.GetType(), jsonOpts);"); sb.AppendLine(" foreach (var prop in body.RootElement.EnumerateObject())"); sb.AppendLine(" {"); + sb.AppendLine(" var __clr = __keys.TryGetValue(prop.Name, out var __mapped) ? __mapped : null;"); // #484 — @formExclude / credential keys are IGNORED (never a 400), ahead of every arm below - // (a present null is a write too). + // (a present null is a write too). Denied by the serializer-resolved property AND by the field-name spellings. + if (deniedClr.Count > 0) + sb.AppendLine($" if (__clr is {string.Join(" or ", deniedClr.Select(n => "\"" + n + "\""))}) continue; // @formExclude / credential: not writable"); foreach (var key in deniedKeys) sb.AppendLine($" if (string.Equals(prop.Name, \"{key}\", global::System.StringComparison.OrdinalIgnoreCase)) continue; // @formExclude / credential: not writable"); // Program D — typed value-object arms FIRST (owned-nav columns are invisible to @@ -1361,7 +1365,7 @@ private static void AppendPartialMergeLoop( { var vf = voFields[i]; var v = "__vo" + i; - sb.AppendLine($" if ({KeyMatch(vf.WireKeys)})"); + sb.AppendLine($" if ({KeyMatch(vf.WireKeys)} || __clr == \"{vf.Nav}\")"); sb.AppendLine(" {"); sb.AppendLine(" if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null)"); sb.AppendLine(" {"); @@ -1395,7 +1399,7 @@ private static void AppendPartialMergeLoop( { var mf = mapVoFields[i]; var mv = "__map" + i; - sb.AppendLine($" if ({KeyMatch(mf.WireKeys)})"); + sb.AppendLine($" if ({KeyMatch(mf.WireKeys)} || __clr == \"{mf.Nav}\")"); sb.AppendLine(" {"); sb.AppendLine(" if (prop.Value.ValueKind == global::System.Text.Json.JsonValueKind.Null)"); sb.AppendLine($" {{ existing.{mf.Nav} = null; continue; }}"); @@ -1407,7 +1411,8 @@ private static void AppendPartialMergeLoop( sb.AppendLine(" continue;"); sb.AppendLine(" }"); } - sb.AppendLine(" var target = entry.Metadata.FindProperty(prop.Name)"); + sb.AppendLine(" var target = (__clr is null ? null : entry.Metadata.FindProperty(__clr))"); + sb.AppendLine(" ?? entry.Metadata.FindProperty(prop.Name)"); sb.AppendLine(" ?? entry.Metadata.GetProperties().FirstOrDefault(p => string.Equals(p.Name, prop.Name, global::System.StringComparison.OrdinalIgnoreCase));"); sb.AppendLine(" if (target is null) continue;"); sb.AppendLine(" if (target.IsPrimaryKey()) continue; // PK is route-authoritative"); @@ -1529,7 +1534,7 @@ private static void AppendTphSubtypeRoutes( // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); - var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => WireKeys(f, config)).ToList(); + var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); // Per-subtype list: GET // sb.AppendLine(); @@ -1605,7 +1610,7 @@ private static void AppendTphSubtypeRoutes( // ADR-0045 + the 0.19.4 lesson: TPH is a SEPARATE code path per port, so the // per-subtype merge states the same exclusion rather than inheriting it. AppendPartialMergeLoop(sb, discProp, [], mapVoFields, autoSetNavs, frozenNavs, HasDecimalField(st.Entity), - deniedFields.SelectMany(f => WireKeys(f, config)).ToList(), HasDurationField(st.Entity)); + deniedFields.SelectMany(f => WireKeys(f, config)).ToList(), deniedFields.Select(f => CSharpNaming.PropertyName(f, config)).ToList(), HasDurationField(st.Entity)); AppendSaveChanges(sb); sb.AppendLine($" return {OkResult("existing", credentials)};"); sb.AppendLine(" }"); diff --git a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs index e8c26ed74d..3afd71bc5c 100644 --- a/server/csharp/MetaObjects.Codegen/HelperRuntime.cs +++ b/server/csharp/MetaObjects.Codegen/HelperRuntime.cs @@ -60,6 +60,8 @@ public static class HelperRuntime /// DurationWire.cs is the field.duration wire form it parses duration operands with. /// ReportExportHttp.cs is the HTTP side of report export: a report list route that /// is built with a report-export generator wired calls it. + /// SerializerKeys.cs reads the host serializer's own JSON key for a property, so credential + /// stripping and the PATCH key lookup agree with it under any naming policy. /// public static readonly IReadOnlyList Files = [ @@ -74,6 +76,7 @@ public static class HelperRuntime "DurationWire.cs", "DecimalRangeEndpointFilter.cs", "ReportExportHttp.cs", + "SerializerKeys.cs", ]; /// Runtime/ files that are CORE and never copied (see the header). diff --git a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj index efb66e0ff7..03146ba8e6 100644 --- a/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj +++ b/server/csharp/MetaObjects.Codegen/MetaObjects.Codegen.csproj @@ -91,5 +91,6 @@ + diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs index 4c655bce8d..51b65a3fe2 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs @@ -66,7 +66,7 @@ public static IResult TooLarge(int maxRows) => /// /// The JSON export with credential columns (a derived field over a view.password field) OMITTED from - /// every row; says the body is { rows, total } rather than the rows. + /// every row ( names their CLR properties); says the body is { rows, total } rather than the rows. /// public static IResult Json(HttpContext http, string segment, T body, string[] omit, bool envelope = false) { @@ -78,18 +78,12 @@ is Microsoft.Extensions.Options.IOptions p.Key).Where(k => omit.Any(x => string.Equals(x, k, StringComparison.OrdinalIgnoreCase))).ToList()) - o.Remove(key); - } - /// The CSV export: fills a UTF-8 (no BOM of the encoder's own) body. public static IResult Csv(HttpContext http, string segment, Action write) => Body(http, segment, "csv", "text/csv; charset=utf-8", write); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs b/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs new file mode 100644 index 0000000000..a2c9589699 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen/Runtime/SerializerKeys.cs @@ -0,0 +1,82 @@ +// SerializerKeys — the JSON key the host's serializer gives a CLR property, read from the +// serializer's own contract (JsonSerializerOptions.GetTypeInfo) and never re-derived from names. +// +// A generated entity property carries no [JsonPropertyName]; its key is whatever the host's +// JsonSerializerOptions make of it: a naming policy (CamelCase, SnakeCaseLower, KebabCaseLower, a +// custom one), a property-naming resolver's rename, an attribute an adopter's emit hook added, or a +// JsonTypeInfo modifier. The generated routes need that key in two places: to omit a credential from +// a response, and to find which property a PATCH or PUT body key names. Both ask here, so they +// agree with the serializer by construction under every policy. +// +// Part of the codegen runtime surface, referenced by the generated routes. + +using System.Collections; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +namespace MetaObjects.Codegen.Runtime; + +public static class SerializerKeys +{ + /// + /// The JSON keys under which writes the CLR properties named + /// on every runtime type found in (a row, a list of + /// rows, or, with , the rows of a { rows, total } envelope). A + /// polymorphic list contributes each element's own type, so a subtype-declared property is found. + /// + public static HashSet KeysOf(object? body, bool envelope, JsonSerializerOptions options, IReadOnlyCollection clrNames) + { + var keys = new HashSet(StringComparer.Ordinal); + foreach (var type in RowTypes(body, envelope)) + { + var info = options.GetTypeInfo(type); + if (info.Kind != JsonTypeInfoKind.Object) continue; + foreach (var p in info.Properties) + if (p.AttributeProvider is MemberInfo member && clrNames.Contains(member.Name)) + keys.Add(p.Name); + } + return keys; + } + + /// Remove every key in from the object, or from each object of the array. + public static void Strip(JsonNode? node, HashSet keys) + { + if (keys.Count == 0) return; + if (node is JsonArray a) { foreach (var e in a) Strip(e, keys); return; } + if (node is not JsonObject o) return; + foreach (var key in o.Select(p => p.Key).Where(keys.Contains).ToList()) o.Remove(key); + } + + /// + /// The map from a body's JSON key (compared ignoring case, as the PATCH merge always has) to the CLR + /// property name gives that key on . + /// + public static Dictionary PropertyByKey(Type type, JsonSerializerOptions options) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + var info = options.GetTypeInfo(type); + if (info.Kind != JsonTypeInfoKind.Object) return map; + foreach (var p in info.Properties) + if (p.AttributeProvider is MemberInfo member) + map.TryAdd(p.Name, member.Name); + return map; + } + + private static IEnumerable RowTypes(object? body, bool envelope) + { + if (body is null) yield break; + object? rows = body; + if (envelope && body.GetType().GetProperty("rows") is { } rowsProp) rows = rowsProp.GetValue(body); + if (rows is null) yield break; + if (rows is IEnumerable list and not string) + { + var seen = new HashSet(); + foreach (var e in list) + if (e is not null && seen.Add(e.GetType())) yield return e.GetType(); + yield break; + } + yield return rows.GetType(); + } +} From b173c772e70c337eefe83f4ddda0363cbd01414b Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 22:59:59 -0500 Subject: [PATCH 240/267] test(csharp): the context hook guard covers value-object members and subtype fields Co-Authored-By: Claude Opus 5.5 --- .../PropertyNamingCodegenTests.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs index 9df2ed733a..211c0416d6 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingCodegenTests.cs @@ -160,6 +160,23 @@ public void A_hook_override_that_differs_from_the_resolver_is_refused() Assert.Contains("set GenConfig.PropertyNaming", ex2.Message); } + // A context hook that differs from the resolver only on a value-object member, or only on a TPH + // subtype's own field, would reference a name the class does not declare: refused up front. + private sealed class DivergesOn(string field) : DbContextGenerator + { + protected override string PropertyName(MetaField f) => f.Name == field ? "Diverged" : base.PropertyName(f); + } + + [Theory] + [InlineData("zipCode")] // PostalAddress, a value object + [InlineData("seatCount")] // Car, a TPH subtype + public void The_context_hook_guard_covers_value_object_members_and_subtype_fields(string field) + { + var ex = Assert.Throws(() => new DivergesOn(field).Generate(Ctx(Load())).ToList()); + Assert.Contains($".{field}\"", ex.Message); + Assert.Contains("set GenConfig.PropertyNaming", ex.Message); + } + [Fact] public void Without_a_resolver_the_output_is_the_pascal_default() { From 449cc77802a4a23f1abeb379f41bd173f6dd1281 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:03:50 -0500 Subject: [PATCH 241/267] test(csharp): live credential and PATCH key checks over rename, snake-policy and subtype hosts Co-Authored-By: Claude Opus 5.5 --- .../ApiContractCredentialHostVariantsTest.cs | 258 ++++++++++++++++++ .../Api/SecretFieldsFixture.cs | 4 +- .../Api/SecretFieldsGeneratedServerFactory.cs | 26 +- .../Api/TphFixture.cs | 4 +- .../Api/TphGeneratedServerFactory.cs | 23 +- 5 files changed, 301 insertions(+), 14 deletions(-) create mode 100644 server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs new file mode 100644 index 0000000000..268ea271fd --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs @@ -0,0 +1,258 @@ +// ApiContractCredentialHostVariantsTest — the live proof that a credential never leaves, and a +// write-denied field is never written, whatever the host does to a property's JSON key. +// +// The generated routes serialize an entity with the host's JsonOptions. A property's key is the host's +// naming policy applied to the property name, and the property name is whatever GenConfig.PropertyNaming +// made of the field. The credential omit list and the PATCH/PUT key lookup read the serializer's own key +// (SerializerKeys), so these variants must all hold: +// 1. a property renamed beyond case, default (camelCase) host; +// 2. the same rename under JsonNamingPolicy.SnakeCaseLower; +// 3. no rename under SnakeCaseLower (the leak that predates the resolver: pinHash -> pin_hash). +// Plus a credential declared on a TPH SUBTYPE, through the polymorphic list and the per-subtype routes. +// +// A response may not carry the credential under any key; a PATCH or PUT body naming it under any +// spelling is ignored (200) and the stored column stays; a POST stores null; and a multi-word ordinary +// field IS applied by PATCH under a snake policy (the key lookup is the serializer's). + +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using MetaObjects.Codegen; +using MetaObjects.IntegrationTests.Runner; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.IntegrationTests.Api; + +public sealed class ApiContractCredentialHostVariantsTest +{ + // pinHash is the credential (view.password); tokenHash is @formExclude (write-denied, still returned). + // displayName is an ordinary multi-word field that PATCH must apply under every policy. + private static string AccountMeta() => File.ReadAllText(ApiContractCorpusPaths.SecretFieldsMetaJson).Replace( + "{ \"field.string\": { \"name\": \"role\"", + "{ \"field.string\": { \"name\": \"displayName\", \"@maxLength\": 100 } },\n { \"field.string\": { \"name\": \"role\""); + + private const string AccountDdl = "ALTER TABLE \"accounts\" ADD COLUMN \"displayName\" VARCHAR(100) NULL;"; + + private static string AccountSpelling(MetaField f) => f.Name switch + { + "pinHash" => "Secret", + "tokenHash" => "ApiToken", + "displayName" => "ShownAs", + _ => CSharpNaming.Pascal(f.Name), + }; + + public static IEnumerable Hosts() => + [ + ["rename", "camel"], + ["rename", "snake"], + ["plain", "snake"], + ]; + + private static SecretFieldsHost AccountHost(string naming, string policy) => new( + PropertyNaming: naming == "rename" ? AccountSpelling : null, + JsonPolicy: policy == "snake" ? JsonNamingPolicy.SnakeCaseLower : JsonNamingPolicy.CamelCase, + MetaJson: AccountMeta(), ExtraDdl: AccountDdl); + + // A key is a credential key iff it spells the credential (or its resolved name) ignoring case and `_`/`-`. + private static readonly string[] CredentialKeys = ["pinhash", "secret"]; + + private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); + + private static void AssertNoCredential(JsonNode? node, string where) + { + switch (node) + { + case JsonObject o: + foreach (var kv in o) + { + Assert.False(CredentialKeys.Contains(Normalize(kv.Key)), $"{where}: credential key \"{kv.Key}\" in {o.ToJsonString()}"); + AssertNoCredential(kv.Value, where); + } + break; + case JsonArray a: + foreach (var e in a) AssertNoCredential(e, where); + break; + } + } + + private static async Task<(int Status, JsonNode? Body)> SendAsync(HttpClient c, string method, string path, object? body = null) + { + var req = new HttpRequestMessage(new HttpMethod(method), path); + if (body is not null) req.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); + var res = await c.SendAsync(req); + var text = await res.Content.ReadAsStringAsync(); + return ((int)res.StatusCode, string.IsNullOrEmpty(text) ? null : JsonNode.Parse(text)); + } + + private static async Task>> ReadAccountsAsync(string connString) + { + await using var c = new Npgsql.NpgsqlConnection(connString); + await c.OpenAsync(); + await using var cmd = c.CreateCommand(); + cmd.CommandText = "SELECT \"id\", \"name\", \"tokenHash\", \"pinHash\", \"displayName\" FROM \"accounts\" ORDER BY \"id\""; + await using var r = await cmd.ExecuteReaderAsync(); + var rows = new List>(); + while (await r.ReadAsync()) + { + string? S(int i) => r.IsDBNull(i) ? null : Convert.ToString(r.GetValue(i)); + rows.Add(new() { ["id"] = S(0), ["name"] = S(1), ["tokenHash"] = S(2), ["pinHash"] = S(3), ["displayName"] = S(4) }); + } + return rows; + } + + // Every spelling a client could send for the denied fields: the field name, the resolved property name + // under the camel and the snake host, and their capitalized forms. + private static Dictionary ForgedBody(string name) => new() + { + ["name"] = name, + ["pinHash"] = "forged", ["tokenHash"] = "forged", ["role"] = "admin", + ["secret"] = "forged", ["Secret"] = "forged", ["apiToken"] = "forged", ["ApiToken"] = "forged", + ["pin_hash"] = "forged", ["token_hash"] = "forged", ["api_token"] = "forged", + }; + + [Theory] + [MemberData(nameof(Hosts))] + public async Task A_credential_is_never_returned_and_never_written_whatever_the_host_does_to_keys(string naming, string policy) + { + await using var pg = await PostgresContainer.StartAsync(); + await using var server = await SecretFieldsGeneratedServerFactory.StartAsync(pg, AccountHost(naming, policy)); + await server.ApplySeedAsync(); + using var client = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + + // Reads: item, list, list with count. No credential key under any spelling; the form-excluded token stays. + var item = await SendAsync(client, "GET", "/api/accounts/1"); + Assert.Equal(200, item.Status); + AssertNoCredential(item.Body, "GET item"); + Assert.Contains(item.Body!.AsObject(), kv => Normalize(kv.Key) is "tokenhash" or "apitoken"); + var list = await SendAsync(client, "GET", "/api/accounts?sort=id:asc"); + Assert.Equal(200, list.Status); + AssertNoCredential(list.Body, "GET list"); + Assert.Equal(2, list.Body!.AsArray().Count); + var counted = await SendAsync(client, "GET", "/api/accounts?withCount=1&sort=id:asc"); + Assert.Equal(200, counted.Status); + AssertNoCredential(counted.Body, "GET list withCount"); + Assert.Equal(2, counted.Body!["rows"]!.AsArray().Count); + + // Writes: PATCH and PUT with the denied fields under every spelling are ignored; the multi-word + // ordinary field is applied under the host's own key for it. + // The key a client echoes is the serializer's: the policy over the (possibly renamed) property. + var displayKey = (naming, policy) switch + { + ("rename", "snake") => "shown_as", ("rename", _) => "shownAs", + (_, "snake") => "display_name", _ => "displayName", + }; + foreach (var (method, id) in new[] { ("PATCH", 1), ("PUT", 2) }) + { + var body = ForgedBody($"{method}-probe"); + body[displayKey] = $"{method}-shown"; + var res = await SendAsync(client, method, $"/api/accounts/{id}", body); + Assert.Equal(200, res.Status); + AssertNoCredential(res.Body, method); + Assert.Equal($"{method}-probe", res.Body!["name"]!.GetValue()); + } + + // Creates: the denied fields are ignored (stored null), the response carries no credential. + var created = await SendAsync(client, "POST", "/api/accounts", ForgedBody("Grace Hopper")); + Assert.Equal(201, created.Status); + AssertNoCredential(created.Body, "POST"); + + var stored = await ReadAccountsAsync(pg.ConnectionString); + Assert.Equal(3, stored.Count); + Assert.Equal("pin-hash-1", stored[0]["pinHash"]); + Assert.Equal("token-hash-1", stored[0]["tokenHash"]); + Assert.Equal("pin-hash-2", stored[1]["pinHash"]); + Assert.Equal("token-hash-2", stored[1]["tokenHash"]); + Assert.Equal("PATCH-shown", stored[0]["displayName"]); // N3: a multi-word key is applied under the policy + Assert.Equal("PUT-shown", stored[1]["displayName"]); + Assert.Null(stored[2]["pinHash"]); + Assert.Null(stored[2]["tokenHash"]); + } + + // ---- a credential declared on a TPH subtype ---- + + private static string TphMeta() => File.ReadAllText(ApiContractCorpusPaths.TphMetaJson).Replace( + "{ \"field.string\": { \"name\": \"approver\", \"@maxLength\": 80, \"@filterable\": true, \"@sortable\": true } }", + "{ \"field.string\": { \"name\": \"approver\", \"@maxLength\": 80, \"@filterable\": true, \"@sortable\": true } },\n" + + " { \"field.string\": { \"name\": \"pinHash\", \"@maxLength\": 80, \"children\": [ { \"view.password\": {} } ] } },\n" + + " { \"field.string\": { \"name\": \"permitNote\", \"@maxLength\": 80 } }"); + + private const string TphDdl = "ALTER TABLE \"auths\" ADD COLUMN \"pinHash\" VARCHAR(80) NULL;\nALTER TABLE \"auths\" ADD COLUMN \"permitNote\" VARCHAR(80) NULL;"; + + private static string TphSpelling(MetaField f) => f.Name switch + { + "pinHash" => "PermitSecret", + "permitNote" => "PermitMemo", + _ => CSharpNaming.Pascal(f.Name), + }; + + public static IEnumerable TphHosts() => + [ + ["rename", "snake"], + ["plain", "snake"], + ["rename", "camel"], + ]; + + [Theory] + [MemberData(nameof(TphHosts))] + public async Task A_subtype_credential_is_never_returned_or_written_on_the_polymorphic_and_subtype_routes(string naming, string policy) + { + await using var pg = await PostgresContainer.StartAsync(); + var host = new TphHost( + PropertyNaming: naming == "rename" ? TphSpelling : null, + JsonPolicy: policy == "snake" ? JsonNamingPolicy.SnakeCaseLower : JsonNamingPolicy.CamelCase, + MetaJson: TphMeta(), ExtraDdl: TphDdl); + await using var server = await TphGeneratedServerFactory.StartAsync(pg, host); + await server.ApplySeedAsync(); + await using (var c = new Npgsql.NpgsqlConnection(pg.ConnectionString)) + { + await c.OpenAsync(); + await using var cmd = c.CreateCommand(); + cmd.CommandText = "UPDATE \"auths\" SET \"pinHash\" = 'permit-secret' WHERE \"id\" = 3"; + await cmd.ExecuteNonQueryAsync(); + } + using var client = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; + + foreach (var path in new[] { "/api/auths?sort=id:asc", "/api/auths/permit?sort=id:asc", "/api/auths/permit/3", "/api/auths/3" }) + { + var res = await SendAsync(client, "GET", path); + Assert.Equal(200, res.Status); + AssertNoCredential(res.Body, "GET " + path); + } + Assert.DoesNotContain("permit-secret", (await SendAsync(client, "GET", "/api/auths")).Body!.ToJsonString()); + + var noteKey = (naming, policy) switch + { + ("rename", "snake") => "permit_memo", ("rename", _) => "permitMemo", + (_, "snake") => "permit_note", _ => "permitNote", + }; + foreach (var method in new[] { "PATCH", "PUT" }) + { + var res = await SendAsync(client, method, "/api/auths/permit/3", new Dictionary + { + ["approver"] = $"{method}-approver", [noteKey] = $"{method}-note", + ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["PermitSecret"] = "forged", ["permit_secret"] = "forged", + }); + Assert.Equal(200, res.Status); + AssertNoCredential(res.Body, method + " permit"); + Assert.Equal($"{method}-approver", res.Body!["approver"]!.GetValue()); + } + var created = await SendAsync(client, "POST", "/api/auths/permit", new Dictionary + { + ["reference"] = "REF-NEW", ["approver"] = "Dr. New", ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["permit_secret"] = "forged", + }); + Assert.Equal(201, created.Status); + AssertNoCredential(created.Body, "POST permit"); + + await using var conn = new Npgsql.NpgsqlConnection(pg.ConnectionString); + await conn.OpenAsync(); + await using var q = conn.CreateCommand(); + q.CommandText = "SELECT \"id\", \"pinHash\", \"permitNote\" FROM \"auths\" ORDER BY \"id\""; + await using var r = await q.ExecuteReaderAsync(); + var rows = new List<(long Id, string? Pin, string? Note)>(); + while (await r.ReadAsync()) rows.Add((r.GetInt64(0), r.IsDBNull(1) ? null : r.GetString(1), r.IsDBNull(2) ? null : r.GetString(2))); + Assert.Equal("permit-secret", rows.Single(x => x.Id == 3).Pin); + Assert.Equal("PUT-note", rows.Single(x => x.Id == 3).Note); // a multi-word subtype field is applied under the policy + Assert.Null(rows.Single(x => x.Id > 3).Pin); + } +} diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs index 7818486b16..39cd3fd606 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs @@ -17,12 +17,12 @@ internal static class SecretFieldsFixture ); """; - public static async Task ProvisionSchemaAsync(string connString) + public static async Task ProvisionSchemaAsync(string connString, string? extraDdl = null) { await using var c = new NpgsqlConnection(connString); await c.OpenAsync(); await using var cmd = c.CreateCommand(); - cmd.CommandText = SchemaDdl; + cmd.CommandText = SchemaDdl + (extraDdl is null ? "" : "\n" + extraDdl); await cmd.ExecuteNonQueryAsync(); } diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs index c2426f9520..79a1d6f164 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs @@ -19,6 +19,17 @@ namespace MetaObjects.IntegrationTests.Api; +/// +/// A host variant for the secret-fields lane: how the generated property names are spelled +/// (), the host's JSON naming policy, and an optional change +/// to the corpus model (extra fields) with the DDL its table needs. +/// +internal sealed record SecretFieldsHost( + Func? PropertyNaming = null, + System.Text.Json.JsonNamingPolicy? JsonPolicy = null, + string? MetaJson = null, + string? ExtraDdl = null); + internal sealed class SecretFieldsGeneratedServerFactory : IAsyncDisposable { private const string GeneratedNamespace = "MetaObjects.ApiContract.SecretFieldsGenerated"; @@ -35,17 +46,19 @@ private SecretFieldsGeneratedServerFactory(PostgresContainer pg, WebApplication BaseUrl = baseUrl; } - public static async Task StartAsync(PostgresContainer pg) + public static async Task StartAsync(PostgresContainer pg, SecretFieldsHost? host = null) { - await SecretFieldsFixture.ProvisionSchemaAsync(pg.ConnectionString); + await SecretFieldsFixture.ProvisionSchemaAsync(pg.ConnectionString, host?.ExtraDdl); - var (assembly, entityNames) = CompileGeneratedServer(); + var (assembly, entityNames) = CompileGeneratedServer(host); var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); var builder = WebApplication.CreateBuilder(); LoopbackKestrel.BindAnyPort(builder); builder.Logging.ClearProviders(); + if (host?.JsonPolicy is { } policy) + builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.PropertyNamingPolicy = policy); RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); var app = builder.Build(); @@ -73,9 +86,11 @@ public async ValueTask DisposeAsync() try { await _app.DisposeAsync(); } catch { /* ignored */ } } - private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGeneratedServer() + private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGeneratedServer(SecretFieldsHost? host) { - var loadResult = new MetaDataLoader().Load([new FileSource(ApiContractCorpusPaths.SecretFieldsMetaJson)]); + var loadResult = new MetaDataLoader().Load([host?.MetaJson is { } json + ? new InMemoryStringSource(json, id: "secret-fields-variant.json") + : new FileSource(ApiContractCorpusPaths.SecretFieldsMetaJson)]); // ADR-0058 — the corpus's committed naming rule, not a hardcoded default. loadResult.Root.PhysicalNaming = ApiContractCorpusPaths.Naming; loadResult.Root.WireFormat = ApiContractCorpusPaths.Wire; @@ -106,6 +121,7 @@ private static (Assembly Assembly, IReadOnlyList EntityNames) CompileGen // is the only lane that proves an Names.NAME reference // actually RESOLVES against a real EF Core compile. IncludeNames = true, + PropertyNaming = host?.PropertyNaming, }, }; diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs index c49dbd5bfb..326a0815bd 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphFixture.cs @@ -48,12 +48,12 @@ internal static class TphFixture { "id", "type", "reference", "quantity", "couponAmount", "approver", "issuedCurrency", "autoCreatedAt", "autoUpdatedAt" }; /// Create the single `auths` table on a fresh container. - public static async Task ProvisionSchemaAsync(string connString) + public static async Task ProvisionSchemaAsync(string connString, string? extraDdl = null) { await using var c = new NpgsqlConnection(connString); await c.OpenAsync(); await using var cmd = c.CreateCommand(); - cmd.CommandText = SchemaDdl; + cmd.CommandText = SchemaDdl + (extraDdl is null ? "" : "\n" + extraDdl); await cmd.ExecuteNonQueryAsync(); } diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs index 8bdb9d964d..cad1709d84 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs @@ -32,6 +32,14 @@ namespace MetaObjects.IntegrationTests.Api; +/// A host variant for the TPH lane: property naming, the host JSON naming policy, a changed +/// corpus model and the DDL it needs (see ). +internal sealed record TphHost( + Func? PropertyNaming = null, + System.Text.Json.JsonNamingPolicy? JsonPolicy = null, + string? MetaJson = null, + string? ExtraDdl = null); + internal sealed class TphGeneratedServerFactory : IAsyncDisposable { private const string GeneratedNamespace = "MetaObjects.ApiContract.TphGenerated"; @@ -48,11 +56,11 @@ private TphGeneratedServerFactory(PostgresContainer pg, WebApplication app, stri BaseUrl = baseUrl; } - public static async Task StartAsync(PostgresContainer pg) + public static async Task StartAsync(PostgresContainer pg, TphHost? host = null) { - await TphFixture.ProvisionSchemaAsync(pg.ConnectionString); + await TphFixture.ProvisionSchemaAsync(pg.ConnectionString, host?.ExtraDdl); - var (assembly, baseRouteEntities) = CompileGeneratedServer(); + var (assembly, baseRouteEntities) = CompileGeneratedServer(host); var dbContextType = MetaObjects.IntegrationTests.GeneratedTypes.Find(assembly, $"{GeneratedNamespace}.AppDbContext") ?? throw new InvalidOperationException("generated AppDbContext type not found"); @@ -62,6 +70,8 @@ public static async Task StartAsync(PostgresContainer // TPH host concern: serialize the discriminator enum as its string symbol. builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter())); + if (host?.JsonPolicy is { } policy) + builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.PropertyNamingPolicy = policy); RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); var app = builder.Build(); @@ -90,9 +100,11 @@ public async ValueTask DisposeAsync() try { await _app.DisposeAsync(); } catch { /* ignored */ } } - private static (Assembly Assembly, IReadOnlyList RouteEntities) CompileGeneratedServer() + private static (Assembly Assembly, IReadOnlyList RouteEntities) CompileGeneratedServer(TphHost? host) { - var loadResult = new MetaDataLoader().Load([new FileSource(ApiContractCorpusPaths.TphMetaJson)]); + var loadResult = new MetaDataLoader().Load([host?.MetaJson is { } json + ? new InMemoryStringSource(json, id: "tph-variant.json") + : new FileSource(ApiContractCorpusPaths.TphMetaJson)]); // ADR-0058 — the corpus's committed naming rule, not a hardcoded default. loadResult.Root.PhysicalNaming = ApiContractCorpusPaths.Naming; loadResult.Root.WireFormat = ApiContractCorpusPaths.Wire; @@ -125,6 +137,7 @@ private static (Assembly Assembly, IReadOnlyList RouteEntities) CompileG // is the only lane that proves an Names.NAME reference // actually RESOLVES against a real EF Core compile. IncludeNames = true, + PropertyNaming = host?.PropertyNaming, }, }; From 28758a918e5fd93c41e911c1598b9fac9b8e72c9 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:05:01 -0500 Subject: [PATCH 242/267] docs(changelog): the credential leak exists in released 1.2.x under snake and kebab policies Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aba4c9bd67..f2417b59f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -675,19 +675,29 @@ vocabulary; upgrade every port together. ### Security -- **Fix, C#: a credential or write-denied field renamed by the property-naming resolver can no longer - escape its protection (rc.22).** The routes keyed credential stripping (`view.password` fields are - omitted from every body), the PATCH write-deny of `@formExclude` and credential fields, and the - PATCH value-object and map arms on the metadata field name. An entity property serializes under - the host's naming policy applied to the resolved property name, so with a rename beyond case - (`pinHash` spelled `Secret`) the stripping missed the key and sent the credential in every read, - list, create and update response, and `PATCH {"secret": "x"}` wrote it. Stripping and the PATCH - arms now match the field name and the resolved name, so create and PATCH agree. A rename that is - only a different case was never affected. Regenerate any project that sets - `GenConfig.PropertyNaming`. +- **Fix, C#: a credential could be returned in every response under a snake or kebab JSON naming + policy, and under a property-naming rename (rc.22).** The generated routes omitted a credential + (`view.password` field) from a body by comparing the serialized key to the field name, ignoring + case. An entity property's key is the host's naming policy applied to the property name, so under + `JsonNamingPolicy.SnakeCaseLower`, `SnakeCaseUpper`, `KebabCaseLower` or `KebabCaseUpper` a + multi-word credential (`pinHash` serialized as `pin_hash`) was sent in every read, list, create, + update (PATCH and PUT) and M:N response. **This leak exists in the released 1.2.x** with no + property-naming resolver at all; a resolver rename beyond case (`pinHash` spelled `Secret`) leaked + the same way under any policy. Only single-word credentials, or a host with the default + camelCase policy and no rename, were safe. 1.2.3 fixes it: the omit list and the PATCH and PUT + key lookup read the key from the serializer's own contract (`JsonSerializerOptions.GetTypeInfo`), + so a naming policy, a rename, an attribute or a type-info modifier cannot escape them. The write + side was never exploitable: a PATCH or PUT body key that missed the deny list also missed the + property and was dropped. Regenerate every project whose host sets a snake or kebab policy or + `GenConfig.PropertyNaming`; a project on the default policy with no rename is unaffected. ### Fixed +- **Fix, C#: PATCH and PUT apply a multi-word field under a snake or kebab JSON naming policy + (rc.22).** The merge matched a body key to a property by name, so `seat_count` never found + `SeatCount` and the update returned 200 with the field silently unchanged. The key is now resolved + through the serializer's own key map. + - **Fix, C#: the generators name a field's property through the one property-naming resolver (rc.22).** Since rc.20 `GenConfig.PropertyNaming` renamed a field's property in the entity, the context's model lines, the reverse finders and the composite key, but these emit sites still From 7bd6aebea78317338a61c69567ca3581a3c65f3a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:18:10 -0500 Subject: [PATCH 243/267] fix(csharp): credential stripping fails closed when the serializer contract cannot be read KeysOfType throws, naming the type and the credential property, when the contract is not an object, a property has no reflection member, or the credential is unmatched. The generated route mapping checks it at startup, and the strip also removes any key that spells the credential ignoring case and separators. Co-Authored-By: Claude Opus 5.5 --- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 3 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 3 +- .../PropertyNamingEmitSitesTests.cs | 4 +- .../PropertyNamingGoldenTests.cs | 12 ++- .../SerializerKeysTests.cs | 97 +++++++++++++++++++ .../Generators/RoutesGenerator.cs | 20 +++- .../Runtime/ReportExportHttp.cs | 2 +- .../Runtime/SerializerKeys.cs | 81 ++++++++++++++-- 8 files changed, 199 insertions(+), 23 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 5086b0bc8d..b27b745ef2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -38,6 +38,7 @@ public static class GizmoRoutes /// public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { + SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Gizmo) }, new string[] { "PinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -285,7 +286,7 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names)); + SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index d6cc9882f7..920c86d616 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -57,6 +57,7 @@ public static class VehicleRoutes /// public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { + SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Vehicle), typeof(Car), typeof(Van) }, new string[] { "VinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/vehicles", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -426,7 +427,7 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names)); + SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index 51a65f656a..8687f0fbb3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -261,8 +261,8 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ // The credential is named by its CLR property; the JSON key is the serializer's, read at run time // (SerializerKeys.KeysOf), never spelled here. - Assert.Contains("new string[] { \"XPinHash\" }", gizmo); - Assert.Contains("new string[] { \"XVinHash\" }", vehicle); + Assert.Contains("new string[] { \"XPinHash\", \"pinHash\" }", gizmo); + Assert.Contains("new string[] { \"XVinHash\", \"vinHash\" }", vehicle); Assert.Contains("SerializerKeys.KeysOf(_value, _envelope, opts, _names)", gizmo); Assert.DoesNotContain("OrdinalIgnoreCase))\n o.Remove", gizmo); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs index 52dfb7c92a..69e956b06f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -1,10 +1,12 @@ // The default output (no property-naming resolver) of the generators the rc.22 property-naming fix -// touched, compared byte for byte against files captured from the generators BEFORE the fix -// (de59161f5): the routes, the callable, the extractor, the report export, the filter allowlist and -// the DbContext (Postgres, so the @sequenceStart identity line is in it). The fix routes each -// field's property name through the resolver; with none set the output must not move. +// touched, compared byte for byte against files in Golden/pre-rc22-propname. They were captured from the +// generators BEFORE the fix (de59161f5) and then re-captured ONLY where the credential-stripping security +// fix legitimately changed the output: the four routes files (GizmoRoutes, VehicleRoutes, TagRoutes, +// LineRoutes: the credential omit list, the strip helper call, the startup contract check and the PATCH key +// lookup). Callable, Extractor, ReportExport, FilterAllowlist and DbContext are still byte-identical to +// de59161f5. So with no resolver the output is unchanged except for that security change. // -// Capture (only ever against a checkout that predates the fix): GOLDEN_WRITE=1 dotnet test +// Capture (re-capture only for a deliberate, reviewed output change): GOLDEN_WRITE=1 dotnet test // --filter PropertyNamingGoldenTests. Compare mode is the default. using System.Runtime.CompilerServices; diff --git a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs new file mode 100644 index 0000000000..124a8ecdfe --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs @@ -0,0 +1,97 @@ +// SerializerKeys fails closed: a credential that cannot be matched to the serializer's contract is a +// refusal, never a silently unstripped response. + +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using MetaObjects.Codegen.Runtime; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class SerializerKeysTests +{ + public sealed class Row + { + public long Id { get; set; } + public string? PinHash { get; set; } + } + + private static readonly string[] Names = ["PinHash", "pinHash"]; + + [Fact] + public void The_default_contract_gives_the_policys_key() + { + var opts = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + Assert.Equal(["pin_hash"], SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + } + + [Fact] + public void A_type_without_the_credential_contributes_nothing_and_never_throws() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; + Assert.Empty(SerializerKeys.KeysOfType(typeof(string), opts, Names)); + } + + // A resolver whose properties carry no reflection member (what a custom resolver, a rebuilding + // modifier or a source-generated context can do). + private sealed class NoProviderResolver : IJsonTypeInfoResolver + { + public JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options) + { + var info = JsonTypeInfo.CreateJsonTypeInfo(type, options); + if (type != typeof(Row)) return info; + var id = info.CreateJsonPropertyInfo(typeof(long), "id"); + id.Get = o => ((Row)o).Id; + id.Set = (o, v) => ((Row)o).Id = (long)v!; + var pin = info.CreateJsonPropertyInfo(typeof(string), "pinHash"); + pin.Get = o => ((Row)o).PinHash; + pin.Set = (o, v) => ((Row)o).PinHash = (string?)v; + info.Properties.Add(id); + info.Properties.Add(pin); + return info; + } + } + + [Fact] + public void A_contract_with_no_reflection_member_is_refused_naming_the_type_and_property_but_no_value() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; + var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + Assert.Contains("refused", ex.Message); + } + + private sealed class RowConverter : JsonConverter + { + public override Row? Read(ref Utf8JsonReader reader, Type t, JsonSerializerOptions o) => throw new NotSupportedException(); + public override void Write(Utf8JsonWriter writer, Row value, JsonSerializerOptions o) => writer.WriteStringValue("x"); + } + + [Fact] + public void A_custom_converter_for_the_row_type_is_refused() + { + var opts = new JsonSerializerOptions { Converters = { new RowConverter() }, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + } + + [Fact] + public void A_credential_the_contract_does_not_carry_is_refused() + { + // A modifier that drops the property from the contract while the type still declares it. + var resolver = new DefaultJsonTypeInfoResolver(); + resolver.Modifiers.Add(ti => { if (ti.Type == typeof(Row)) ti.Properties.Remove(ti.Properties.Single(p => p.Name == "PinHash")); }); + var opts = new JsonSerializerOptions { TypeInfoResolver = resolver }; + var ex = Assert.Throws(() => SerializerKeys.KeysOf(new[] { new Row() }, false, opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + } + + [Fact] + public void Strip_also_removes_a_key_that_spells_the_credential_ignoring_case_and_separators() + { + var node = System.Text.Json.Nodes.JsonNode.Parse("""{"id":1,"pin_hash":"v","PIN-HASH":"v","name":"n"}""")!; + SerializerKeys.Strip(node, [], Names); + Assert.Equal("""{"id":1,"name":"n"}""", node.ToJsonString()); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index acb75724f2..d843530d9e 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -319,6 +319,9 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); sb.AppendLine($" public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); + // Refuse to start when the host's serializer contract cannot be read to strip a credential. + if (credentials.Count > 0) + sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); AppendDecimalRangeGroup(sb); // List — honours ?limit / ?offset / ?sort / ?withCount per api-contract.md. @@ -655,6 +658,11 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t AppendUnauthenticatedRoutesDoc(sb, baseCls, readOnly: false); sb.AppendLine($" public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); + if (baseCredentials.Count > 0) + { + var credTypes = new[] { baseCls }.Concat(tph.Subtypes.Select(st => ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)))); + sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(baseCredentials)});"); + } AppendDecimalRangeGroup(sb); // --- Polymorphic list: GET / (union of all subtypes; each row carries its discriminator) --- @@ -848,7 +856,13 @@ private static List WireKeys(MetaField f, GenConfig config) => // The CLR property names of an entity's credentials. The JSON key each is written under is not // derived here: the generated result asks the host's serializer (SerializerKeys.KeysOf). private static List CredentialNames(MetaObject entity, GenConfig config) => - entity.Fields().Where(IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); + entity.Fields().Where(IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); + + // The CLR property first (what the serializer's contract is matched on), then the field name: the + // normalized-spelling backstop in SerializerKeys.Strip also removes a key that spells it. Equal + // ignoring case when no resolver renames, so the list is then the one CLR name. + private static IEnumerable CredentialSpellings(MetaField f, GenConfig config) => + new[] { CSharpNaming.PropertyName(f, config), f.Name }.Distinct(StringComparer.OrdinalIgnoreCase); // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. private static string KeyMatch(IEnumerable keys) => @@ -903,7 +917,7 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); sb.AppendLine(" // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names."); sb.AppendLine($" SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node,"); - sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names));"); + sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names);"); sb.AppendLine(" http.Response.StatusCode = _status;"); sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); @@ -1534,7 +1548,7 @@ private static void AppendTphSubtypeRoutes( // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); - var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); + var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); // Per-subtype list: GET // sb.AppendLine(); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs index 51b65a3fe2..954d5b6312 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs @@ -80,7 +80,7 @@ is Microsoft.Extensions.Options.IOptions on every runtime type found in (a row, a list of /// rows, or, with , the rows of a { rows, total } envelope). A /// polymorphic list contributes each element's own type, so a subtype-declared property is found. + /// Fails closed: see . /// public static HashSet KeysOf(object? body, bool envelope, JsonSerializerOptions options, IReadOnlyCollection clrNames) { var keys = new HashSet(StringComparer.Ordinal); foreach (var type in RowTypes(body, envelope)) + keys.UnionWith(KeysOfType(type, options, clrNames)); + return keys; + } + + /// + /// The JSON keys writes the credential properties of under, + /// read from the serializer's contract. A type that declares none of contributes + /// nothing. For a type that does, this THROWS rather than guess when the contract cannot be read: + /// its kind is not an object (a custom converter), any property has no reflection member behind it + /// (a custom type-info resolver, a modifier that rebuilds properties, a source-generated context that does + /// not carry it), or a credential has no matching property in the contract. A response that cannot be + /// stripped is refused, never sent. The message names the type and the credential property, never a value. + /// + public static HashSet KeysOfType(Type type, JsonSerializerOptions options, IReadOnlyCollection clrNames) + { + var keys = new HashSet(StringComparer.Ordinal); + var declared = clrNames + .Where(n => type.GetProperty(n, BindingFlags.Public | BindingFlags.Instance) is { } prop && !IsIgnored(prop)) + .Distinct(StringComparer.Ordinal).ToList(); + if (declared.Count == 0) return keys; + + JsonTypeInfo info; + try { info = options.GetTypeInfo(type); } + catch (NotSupportedException e) { throw Unreadable(type, declared, "the serializer has no contract for it (" + e.GetType().Name + ")"); } + if (info.Kind != JsonTypeInfoKind.Object) + throw Unreadable(type, declared, $"its JSON contract is a {info.Kind}, not an object (a custom converter?)"); + if (info.Properties.Any(p => p.AttributeProvider is not MemberInfo)) + throw Unreadable(type, declared, "a property has no reflection member behind it (a custom type-info resolver, a modifier that rebuilds properties, or a source-generated context?)"); + foreach (var name in declared) { - var info = options.GetTypeInfo(type); - if (info.Kind != JsonTypeInfoKind.Object) continue; - foreach (var p in info.Properties) - if (p.AttributeProvider is MemberInfo member && clrNames.Contains(member.Name)) - keys.Add(p.Name); + var matched = info.Properties.Where(p => ((MemberInfo)p.AttributeProvider!).Name == name).Select(p => p.Name).ToList(); + if (matched.Count == 0) throw Unreadable(type, [name], "the credential has no property in the serializer's contract"); + keys.UnionWith(matched); } return keys; } - /// Remove every key in from the object, or from each object of the array. - public static void Strip(JsonNode? node, HashSet keys) + /// + /// Check, at startup (the generated route mapping calls it), that the credential properties of + /// can be stripped under the host's configured JsonOptions. Throws as + /// does, so a host whose serializer contract cannot be read fails to start + /// instead of failing on the first response. + /// + public static void EnsureContract(IServiceProvider services, IReadOnlyCollection types, IReadOnlyCollection clrNames) { - if (keys.Count == 0) return; - if (node is JsonArray a) { foreach (var e in a) Strip(e, keys); return; } + var options = (services.GetService(typeof(Microsoft.Extensions.Options.IOptions)) + as Microsoft.Extensions.Options.IOptions)?.Value.SerializerOptions + ?? JsonSerializerOptions.Default; + foreach (var type in types) KeysOfType(type, options, clrNames); + } + + private static bool IsIgnored(PropertyInfo prop) => + prop.GetCustomAttribute() is { Condition: System.Text.Json.Serialization.JsonIgnoreCondition.Always }; + + private static InvalidOperationException Unreadable(Type type, IEnumerable credentials, string why) => + new($"cannot strip the credential {string.Join(", ", credentials.Select(c => type.Name + "." + c))} from a response: {why}. " + + "Credential stripping reads the serializer's reflection-visible contract; the response is refused rather than sent unstripped."); + + /// + /// Remove every key in from the object, or from each object of the array, and, as a + /// second line of defence, every key that spells one of ignoring case, _ and + /// -. + /// + public static void Strip(JsonNode? node, HashSet keys, IReadOnlyCollection? names = null) + { + if (keys.Count == 0 && (names is null || names.Count == 0)) return; + var normalized = names is null ? [] : names.Select(Normalize).ToHashSet(StringComparer.Ordinal); + StripCore(node, keys, normalized); + } + + private static void StripCore(JsonNode? node, HashSet keys, HashSet normalized) + { + if (node is JsonArray a) { foreach (var e in a) StripCore(e, keys, normalized); return; } if (node is not JsonObject o) return; - foreach (var key in o.Select(p => p.Key).Where(keys.Contains).ToList()) o.Remove(key); + foreach (var key in o.Select(p => p.Key).Where(k => keys.Contains(k) || normalized.Contains(Normalize(k))).ToList()) o.Remove(key); } + private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); + /// /// The map from a body's JSON key (compared ignoring case, as the PATCH merge always has) to the CLR /// property name gives that key on . From d6b4367d6d4c9babcd18b91b1b9fd7246f8bbd17 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:20:38 -0500 Subject: [PATCH 244/267] test(csharp): refuse-not-leak host variants, a multi-word credential rename, value-based leak checks Co-Authored-By: Claude Opus 5.5 --- .../ApiContractCredentialHostVariantsTest.cs | 57 +++++++++++++++++-- .../Api/SecretFieldsGeneratedServerFactory.cs | 11 +++- .../Api/TphGeneratedServerFactory.cs | 11 +++- 3 files changed, 69 insertions(+), 10 deletions(-) diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs index 268ea271fd..b6e40cc3dd 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs @@ -36,7 +36,7 @@ private static string AccountMeta() => File.ReadAllText(ApiContractCorpusPaths.S private static string AccountSpelling(MetaField f) => f.Name switch { - "pinHash" => "Secret", + "pinHash" => "PinSecret", "tokenHash" => "ApiToken", "displayName" => "ShownAs", _ => CSharpNaming.Pascal(f.Name), @@ -55,7 +55,10 @@ public static IEnumerable Hosts() => MetaJson: AccountMeta(), ExtraDdl: AccountDdl); // A key is a credential key iff it spells the credential (or its resolved name) ignoring case and `_`/`-`. - private static readonly string[] CredentialKeys = ["pinhash", "secret"]; + private static readonly string[] CredentialKeys = ["pinhash", "pinsecret", "permitsecret"]; + + // The credential VALUES seeded by the corpus and the TPH test: they may appear in no response body, under any key. + private static readonly string[] CredentialValues = ["pin-hash-1", "pin-hash-2", "permit-secret"]; private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); @@ -82,6 +85,8 @@ private static void AssertNoCredential(JsonNode? node, string where) if (body is not null) req.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); var res = await c.SendAsync(req); var text = await res.Content.ReadAsStringAsync(); + foreach (var v in CredentialValues) + Assert.DoesNotContain(v, text); // by value: no key spelling can hide it return ((int)res.StatusCode, string.IsNullOrEmpty(text) ? null : JsonNode.Parse(text)); } @@ -107,7 +112,7 @@ private static void AssertNoCredential(JsonNode? node, string where) { ["name"] = name, ["pinHash"] = "forged", ["tokenHash"] = "forged", ["role"] = "admin", - ["secret"] = "forged", ["Secret"] = "forged", ["apiToken"] = "forged", ["ApiToken"] = "forged", + ["pinSecret"] = "forged", ["PinSecret"] = "forged", ["pin_secret"] = "forged", ["apiToken"] = "forged", ["ApiToken"] = "forged", ["pin_hash"] = "forged", ["token_hash"] = "forged", ["api_token"] = "forged", }; @@ -213,7 +218,7 @@ public async Task A_subtype_credential_is_never_returned_or_written_on_the_polym } using var client = new HttpClient { BaseAddress = new Uri(server.BaseUrl) }; - foreach (var path in new[] { "/api/auths?sort=id:asc", "/api/auths/permit?sort=id:asc", "/api/auths/permit/3", "/api/auths/3" }) + foreach (var path in new[] { "/api/auths?sort=id:asc", "/api/auths?withCount=1&sort=id:asc", "/api/auths/permit?sort=id:asc", "/api/auths/permit?withCount=1&sort=id:asc", "/api/auths/permit/3", "/api/auths/3" }) { var res = await SendAsync(client, "GET", path); Assert.Equal(200, res.Status); @@ -255,4 +260,48 @@ public async Task A_subtype_credential_is_never_returned_or_written_on_the_polym Assert.Equal("PUT-note", rows.Single(x => x.Id == 3).Note); // a multi-word subtype field is applied under the policy Assert.Null(rows.Single(x => x.Id > 3).Pin); } + + // ---- a host whose serializer contract cannot be read must be refused, never leak ---- + + // Every property loses its reflection member: what a custom type-info resolver, a modifier that rebuilds + // properties, or a source-generated context that does not carry it can do. + private static void NoReflectionMembers(JsonSerializerOptions o) + { + var resolver = new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver(); + resolver.Modifiers.Add(ti => { foreach (var p in ti.Properties) p.AttributeProvider = null; }); + o.TypeInfoResolver = resolver; + } + + private static bool Refused(Exception e) + { + for (var x = e; x is not null; x = x.InnerException!) + if (x.Message.Contains("cannot strip the credential", StringComparison.Ordinal)) return true; + return false; + } + + [Fact] + public async Task A_host_whose_contract_cannot_be_read_refuses_to_start_instead_of_leaking_the_account_credential() + { + await using var pg = await PostgresContainer.StartAsync(); + var host = AccountHost("rename", "snake") with { ConfigureJson = NoReflectionMembers }; + var ex = await Assert.ThrowsAnyAsync(async () => + { + await using var server = await SecretFieldsGeneratedServerFactory.StartAsync(pg, host); + }); + Assert.True(Refused(ex), ex.ToString()); + Assert.DoesNotContain("pin-hash", ex.ToString()); + } + + [Fact] + public async Task A_host_whose_contract_cannot_be_read_refuses_to_start_instead_of_leaking_the_subtype_credential() + { + await using var pg = await PostgresContainer.StartAsync(); + var host = new TphHost(PropertyNaming: TphSpelling, JsonPolicy: JsonNamingPolicy.SnakeCaseLower, + MetaJson: TphMeta(), ExtraDdl: TphDdl, ConfigureJson: NoReflectionMembers); + var ex = await Assert.ThrowsAnyAsync(async () => + { + await using var server = await TphGeneratedServerFactory.StartAsync(pg, host); + }); + Assert.True(Refused(ex), ex.ToString()); + } } diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs index 79a1d6f164..7175108395 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsGeneratedServerFactory.cs @@ -28,7 +28,8 @@ internal sealed record SecretFieldsHost( Func? PropertyNaming = null, System.Text.Json.JsonNamingPolicy? JsonPolicy = null, string? MetaJson = null, - string? ExtraDdl = null); + string? ExtraDdl = null, + Action? ConfigureJson = null); internal sealed class SecretFieldsGeneratedServerFactory : IAsyncDisposable { @@ -57,8 +58,12 @@ public static async Task StartAsync(Postgres var builder = WebApplication.CreateBuilder(); LoopbackKestrel.BindAnyPort(builder); builder.Logging.ClearProviders(); - if (host?.JsonPolicy is { } policy) - builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.PropertyNamingPolicy = policy); + if (host is not null) + builder.Services.ConfigureHttpJsonOptions(o => + { + if (host.JsonPolicy is { } policy) o.SerializerOptions.PropertyNamingPolicy = policy; + host.ConfigureJson?.Invoke(o.SerializerOptions); + }); RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); var app = builder.Build(); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs index cad1709d84..f69ee641b9 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphGeneratedServerFactory.cs @@ -38,7 +38,8 @@ internal sealed record TphHost( Func? PropertyNaming = null, System.Text.Json.JsonNamingPolicy? JsonPolicy = null, string? MetaJson = null, - string? ExtraDdl = null); + string? ExtraDdl = null, + Action? ConfigureJson = null); internal sealed class TphGeneratedServerFactory : IAsyncDisposable { @@ -70,8 +71,12 @@ public static async Task StartAsync(PostgresContainer // TPH host concern: serialize the discriminator enum as its string symbol. builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.Converters.Add(new JsonStringEnumConverter())); - if (host?.JsonPolicy is { } policy) - builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.PropertyNamingPolicy = policy); + if (host is not null) + builder.Services.ConfigureHttpJsonOptions(o => + { + if (host.JsonPolicy is { } policy) o.SerializerOptions.PropertyNamingPolicy = policy; + host.ConfigureJson?.Invoke(o.SerializerOptions); + }); RegisterGeneratedDbContext(builder.Services, dbContextType, pg.ConnectionString); var app = builder.Build(); From f126e34abbd3279a2e00914a3483dd60943b8079 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:20:42 -0500 Subject: [PATCH 245/267] Revert fail-closed stripping (temporary, before-fix evidence for the refuse variants) Co-Authored-By: Claude Opus 5.5 --- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 3 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 3 +- .../PropertyNamingEmitSitesTests.cs | 4 +- .../PropertyNamingGoldenTests.cs | 12 +-- .../SerializerKeysTests.cs | 97 ------------------- .../Generators/RoutesGenerator.cs | 20 +--- .../Runtime/ReportExportHttp.cs | 2 +- .../Runtime/SerializerKeys.cs | 81 ++-------------- 8 files changed, 23 insertions(+), 199 deletions(-) delete mode 100644 server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index b27b745ef2..5086b0bc8d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -38,7 +38,6 @@ public static class GizmoRoutes /// public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { - SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Gizmo) }, new string[] { "PinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -286,7 +285,7 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); + SerializerKeys.KeysOf(_value, _envelope, opts, _names)); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 920c86d616..d6cc9882f7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -57,7 +57,6 @@ public static class VehicleRoutes /// public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { - SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Vehicle), typeof(Car), typeof(Van) }, new string[] { "VinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/vehicles", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -427,7 +426,7 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); + SerializerKeys.KeysOf(_value, _envelope, opts, _names)); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index 8687f0fbb3..51a65f656a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -261,8 +261,8 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ // The credential is named by its CLR property; the JSON key is the serializer's, read at run time // (SerializerKeys.KeysOf), never spelled here. - Assert.Contains("new string[] { \"XPinHash\", \"pinHash\" }", gizmo); - Assert.Contains("new string[] { \"XVinHash\", \"vinHash\" }", vehicle); + Assert.Contains("new string[] { \"XPinHash\" }", gizmo); + Assert.Contains("new string[] { \"XVinHash\" }", vehicle); Assert.Contains("SerializerKeys.KeysOf(_value, _envelope, opts, _names)", gizmo); Assert.DoesNotContain("OrdinalIgnoreCase))\n o.Remove", gizmo); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs index 69e956b06f..52dfb7c92a 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -1,12 +1,10 @@ // The default output (no property-naming resolver) of the generators the rc.22 property-naming fix -// touched, compared byte for byte against files in Golden/pre-rc22-propname. They were captured from the -// generators BEFORE the fix (de59161f5) and then re-captured ONLY where the credential-stripping security -// fix legitimately changed the output: the four routes files (GizmoRoutes, VehicleRoutes, TagRoutes, -// LineRoutes: the credential omit list, the strip helper call, the startup contract check and the PATCH key -// lookup). Callable, Extractor, ReportExport, FilterAllowlist and DbContext are still byte-identical to -// de59161f5. So with no resolver the output is unchanged except for that security change. +// touched, compared byte for byte against files captured from the generators BEFORE the fix +// (de59161f5): the routes, the callable, the extractor, the report export, the filter allowlist and +// the DbContext (Postgres, so the @sequenceStart identity line is in it). The fix routes each +// field's property name through the resolver; with none set the output must not move. // -// Capture (re-capture only for a deliberate, reviewed output change): GOLDEN_WRITE=1 dotnet test +// Capture (only ever against a checkout that predates the fix): GOLDEN_WRITE=1 dotnet test // --filter PropertyNamingGoldenTests. Compare mode is the default. using System.Runtime.CompilerServices; diff --git a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs deleted file mode 100644 index 124a8ecdfe..0000000000 --- a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs +++ /dev/null @@ -1,97 +0,0 @@ -// SerializerKeys fails closed: a credential that cannot be matched to the serializer's contract is a -// refusal, never a silently unstripped response. - -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.Json.Serialization.Metadata; -using MetaObjects.Codegen.Runtime; -using Xunit; - -namespace MetaObjects.Codegen.Tests; - -public class SerializerKeysTests -{ - public sealed class Row - { - public long Id { get; set; } - public string? PinHash { get; set; } - } - - private static readonly string[] Names = ["PinHash", "pinHash"]; - - [Fact] - public void The_default_contract_gives_the_policys_key() - { - var opts = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; - Assert.Equal(["pin_hash"], SerializerKeys.KeysOfType(typeof(Row), opts, Names)); - } - - [Fact] - public void A_type_without_the_credential_contributes_nothing_and_never_throws() - { - var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; - Assert.Empty(SerializerKeys.KeysOfType(typeof(string), opts, Names)); - } - - // A resolver whose properties carry no reflection member (what a custom resolver, a rebuilding - // modifier or a source-generated context can do). - private sealed class NoProviderResolver : IJsonTypeInfoResolver - { - public JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options) - { - var info = JsonTypeInfo.CreateJsonTypeInfo(type, options); - if (type != typeof(Row)) return info; - var id = info.CreateJsonPropertyInfo(typeof(long), "id"); - id.Get = o => ((Row)o).Id; - id.Set = (o, v) => ((Row)o).Id = (long)v!; - var pin = info.CreateJsonPropertyInfo(typeof(string), "pinHash"); - pin.Get = o => ((Row)o).PinHash; - pin.Set = (o, v) => ((Row)o).PinHash = (string?)v; - info.Properties.Add(id); - info.Properties.Add(pin); - return info; - } - } - - [Fact] - public void A_contract_with_no_reflection_member_is_refused_naming_the_type_and_property_but_no_value() - { - var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; - var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); - Assert.Contains("Row.PinHash", ex.Message); - Assert.Contains("refused", ex.Message); - } - - private sealed class RowConverter : JsonConverter - { - public override Row? Read(ref Utf8JsonReader reader, Type t, JsonSerializerOptions o) => throw new NotSupportedException(); - public override void Write(Utf8JsonWriter writer, Row value, JsonSerializerOptions o) => writer.WriteStringValue("x"); - } - - [Fact] - public void A_custom_converter_for_the_row_type_is_refused() - { - var opts = new JsonSerializerOptions { Converters = { new RowConverter() }, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; - var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); - Assert.Contains("Row.PinHash", ex.Message); - } - - [Fact] - public void A_credential_the_contract_does_not_carry_is_refused() - { - // A modifier that drops the property from the contract while the type still declares it. - var resolver = new DefaultJsonTypeInfoResolver(); - resolver.Modifiers.Add(ti => { if (ti.Type == typeof(Row)) ti.Properties.Remove(ti.Properties.Single(p => p.Name == "PinHash")); }); - var opts = new JsonSerializerOptions { TypeInfoResolver = resolver }; - var ex = Assert.Throws(() => SerializerKeys.KeysOf(new[] { new Row() }, false, opts, Names)); - Assert.Contains("Row.PinHash", ex.Message); - } - - [Fact] - public void Strip_also_removes_a_key_that_spells_the_credential_ignoring_case_and_separators() - { - var node = System.Text.Json.Nodes.JsonNode.Parse("""{"id":1,"pin_hash":"v","PIN-HASH":"v","name":"n"}""")!; - SerializerKeys.Strip(node, [], Names); - Assert.Equal("""{"id":1,"name":"n"}""", node.ToJsonString()); - } -} diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index d843530d9e..acb75724f2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -319,9 +319,6 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); sb.AppendLine($" public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); - // Refuse to start when the host's serializer contract cannot be read to strip a credential. - if (credentials.Count > 0) - sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); AppendDecimalRangeGroup(sb); // List — honours ?limit / ?offset / ?sort / ?withCount per api-contract.md. @@ -658,11 +655,6 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t AppendUnauthenticatedRoutesDoc(sb, baseCls, readOnly: false); sb.AppendLine($" public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); - if (baseCredentials.Count > 0) - { - var credTypes = new[] { baseCls }.Concat(tph.Subtypes.Select(st => ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)))); - sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(baseCredentials)});"); - } AppendDecimalRangeGroup(sb); // --- Polymorphic list: GET / (union of all subtypes; each row carries its discriminator) --- @@ -856,13 +848,7 @@ private static List WireKeys(MetaField f, GenConfig config) => // The CLR property names of an entity's credentials. The JSON key each is written under is not // derived here: the generated result asks the host's serializer (SerializerKeys.KeysOf). private static List CredentialNames(MetaObject entity, GenConfig config) => - entity.Fields().Where(IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); - - // The CLR property first (what the serializer's contract is matched on), then the field name: the - // normalized-spelling backstop in SerializerKeys.Strip also removes a key that spells it. Equal - // ignoring case when no resolver renames, so the list is then the one CLR name. - private static IEnumerable CredentialSpellings(MetaField f, GenConfig config) => - new[] { CSharpNaming.PropertyName(f, config), f.Name }.Distinct(StringComparer.OrdinalIgnoreCase); + entity.Fields().Where(IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. private static string KeyMatch(IEnumerable keys) => @@ -917,7 +903,7 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); sb.AppendLine(" // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names."); sb.AppendLine($" SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node,"); - sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names);"); + sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names));"); sb.AppendLine(" http.Response.StatusCode = _status;"); sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); @@ -1548,7 +1534,7 @@ private static void AppendTphSubtypeRoutes( // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); - var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); + var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); // Per-subtype list: GET // sb.AppendLine(); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs index 954d5b6312..51b65a3fe2 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs @@ -80,7 +80,7 @@ is Microsoft.Extensions.Options.IOptions on every runtime type found in (a row, a list of /// rows, or, with , the rows of a { rows, total } envelope). A /// polymorphic list contributes each element's own type, so a subtype-declared property is found. - /// Fails closed: see . /// public static HashSet KeysOf(object? body, bool envelope, JsonSerializerOptions options, IReadOnlyCollection clrNames) { var keys = new HashSet(StringComparer.Ordinal); foreach (var type in RowTypes(body, envelope)) - keys.UnionWith(KeysOfType(type, options, clrNames)); - return keys; - } - - /// - /// The JSON keys writes the credential properties of under, - /// read from the serializer's contract. A type that declares none of contributes - /// nothing. For a type that does, this THROWS rather than guess when the contract cannot be read: - /// its kind is not an object (a custom converter), any property has no reflection member behind it - /// (a custom type-info resolver, a modifier that rebuilds properties, a source-generated context that does - /// not carry it), or a credential has no matching property in the contract. A response that cannot be - /// stripped is refused, never sent. The message names the type and the credential property, never a value. - /// - public static HashSet KeysOfType(Type type, JsonSerializerOptions options, IReadOnlyCollection clrNames) - { - var keys = new HashSet(StringComparer.Ordinal); - var declared = clrNames - .Where(n => type.GetProperty(n, BindingFlags.Public | BindingFlags.Instance) is { } prop && !IsIgnored(prop)) - .Distinct(StringComparer.Ordinal).ToList(); - if (declared.Count == 0) return keys; - - JsonTypeInfo info; - try { info = options.GetTypeInfo(type); } - catch (NotSupportedException e) { throw Unreadable(type, declared, "the serializer has no contract for it (" + e.GetType().Name + ")"); } - if (info.Kind != JsonTypeInfoKind.Object) - throw Unreadable(type, declared, $"its JSON contract is a {info.Kind}, not an object (a custom converter?)"); - if (info.Properties.Any(p => p.AttributeProvider is not MemberInfo)) - throw Unreadable(type, declared, "a property has no reflection member behind it (a custom type-info resolver, a modifier that rebuilds properties, or a source-generated context?)"); - foreach (var name in declared) { - var matched = info.Properties.Where(p => ((MemberInfo)p.AttributeProvider!).Name == name).Select(p => p.Name).ToList(); - if (matched.Count == 0) throw Unreadable(type, [name], "the credential has no property in the serializer's contract"); - keys.UnionWith(matched); + var info = options.GetTypeInfo(type); + if (info.Kind != JsonTypeInfoKind.Object) continue; + foreach (var p in info.Properties) + if (p.AttributeProvider is MemberInfo member && clrNames.Contains(member.Name)) + keys.Add(p.Name); } return keys; } - /// - /// Check, at startup (the generated route mapping calls it), that the credential properties of - /// can be stripped under the host's configured JsonOptions. Throws as - /// does, so a host whose serializer contract cannot be read fails to start - /// instead of failing on the first response. - /// - public static void EnsureContract(IServiceProvider services, IReadOnlyCollection types, IReadOnlyCollection clrNames) + /// Remove every key in from the object, or from each object of the array. + public static void Strip(JsonNode? node, HashSet keys) { - var options = (services.GetService(typeof(Microsoft.Extensions.Options.IOptions)) - as Microsoft.Extensions.Options.IOptions)?.Value.SerializerOptions - ?? JsonSerializerOptions.Default; - foreach (var type in types) KeysOfType(type, options, clrNames); - } - - private static bool IsIgnored(PropertyInfo prop) => - prop.GetCustomAttribute() is { Condition: System.Text.Json.Serialization.JsonIgnoreCondition.Always }; - - private static InvalidOperationException Unreadable(Type type, IEnumerable credentials, string why) => - new($"cannot strip the credential {string.Join(", ", credentials.Select(c => type.Name + "." + c))} from a response: {why}. " + - "Credential stripping reads the serializer's reflection-visible contract; the response is refused rather than sent unstripped."); - - /// - /// Remove every key in from the object, or from each object of the array, and, as a - /// second line of defence, every key that spells one of ignoring case, _ and - /// -. - /// - public static void Strip(JsonNode? node, HashSet keys, IReadOnlyCollection? names = null) - { - if (keys.Count == 0 && (names is null || names.Count == 0)) return; - var normalized = names is null ? [] : names.Select(Normalize).ToHashSet(StringComparer.Ordinal); - StripCore(node, keys, normalized); - } - - private static void StripCore(JsonNode? node, HashSet keys, HashSet normalized) - { - if (node is JsonArray a) { foreach (var e in a) StripCore(e, keys, normalized); return; } + if (keys.Count == 0) return; + if (node is JsonArray a) { foreach (var e in a) Strip(e, keys); return; } if (node is not JsonObject o) return; - foreach (var key in o.Select(p => p.Key).Where(k => keys.Contains(k) || normalized.Contains(Normalize(k))).ToList()) o.Remove(key); + foreach (var key in o.Select(p => p.Key).Where(keys.Contains).ToList()) o.Remove(key); } - private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); - /// /// The map from a body's JSON key (compared ignoring case, as the PATCH merge always has) to the CLR /// property name gives that key on . From c9c1c9573775d23574e8dbe4fd113de1dc4088b7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:21:11 -0500 Subject: [PATCH 246/267] Reapply fail-closed credential stripping Co-Authored-By: Claude Opus 5.5 --- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 3 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 3 +- .../PropertyNamingEmitSitesTests.cs | 4 +- .../PropertyNamingGoldenTests.cs | 12 ++- .../SerializerKeysTests.cs | 97 +++++++++++++++++++ .../Generators/RoutesGenerator.cs | 20 +++- .../Runtime/ReportExportHttp.cs | 2 +- .../Runtime/SerializerKeys.cs | 81 ++++++++++++++-- 8 files changed, 199 insertions(+), 23 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index 5086b0bc8d..b27b745ef2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -38,6 +38,7 @@ public static class GizmoRoutes /// public static IEndpointRouteBuilder MapGizmoRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { + SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Gizmo) }, new string[] { "PinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/gizmos", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -285,7 +286,7 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names)); + SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index d6cc9882f7..920c86d616 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -57,6 +57,7 @@ public static class VehicleRoutes /// public static IEndpointRouteBuilder MapVehicleRoutes(this IEndpointRouteBuilder app, string prefix = "/api") { + SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] { typeof(Vehicle), typeof(Car), typeof(Van) }, new string[] { "VinHash" }); IEndpointRouteBuilder mount = app; app = app.MapGroup(string.Empty).AddEndpointFilter(new DecimalRangeEndpointFilter()); app.MapGet(prefix + "/vehicles", async (HttpContext http, global::Acme.Generated.AppDbContext db) => @@ -426,7 +427,7 @@ public CredentialOmittingResult(object value, string[] names, bool envelope = fa var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names)); + SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index 51a65f656a..8687f0fbb3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -261,8 +261,8 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ // The credential is named by its CLR property; the JSON key is the serializer's, read at run time // (SerializerKeys.KeysOf), never spelled here. - Assert.Contains("new string[] { \"XPinHash\" }", gizmo); - Assert.Contains("new string[] { \"XVinHash\" }", vehicle); + Assert.Contains("new string[] { \"XPinHash\", \"pinHash\" }", gizmo); + Assert.Contains("new string[] { \"XVinHash\", \"vinHash\" }", vehicle); Assert.Contains("SerializerKeys.KeysOf(_value, _envelope, opts, _names)", gizmo); Assert.DoesNotContain("OrdinalIgnoreCase))\n o.Remove", gizmo); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs index 52dfb7c92a..69e956b06f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -1,10 +1,12 @@ // The default output (no property-naming resolver) of the generators the rc.22 property-naming fix -// touched, compared byte for byte against files captured from the generators BEFORE the fix -// (de59161f5): the routes, the callable, the extractor, the report export, the filter allowlist and -// the DbContext (Postgres, so the @sequenceStart identity line is in it). The fix routes each -// field's property name through the resolver; with none set the output must not move. +// touched, compared byte for byte against files in Golden/pre-rc22-propname. They were captured from the +// generators BEFORE the fix (de59161f5) and then re-captured ONLY where the credential-stripping security +// fix legitimately changed the output: the four routes files (GizmoRoutes, VehicleRoutes, TagRoutes, +// LineRoutes: the credential omit list, the strip helper call, the startup contract check and the PATCH key +// lookup). Callable, Extractor, ReportExport, FilterAllowlist and DbContext are still byte-identical to +// de59161f5. So with no resolver the output is unchanged except for that security change. // -// Capture (only ever against a checkout that predates the fix): GOLDEN_WRITE=1 dotnet test +// Capture (re-capture only for a deliberate, reviewed output change): GOLDEN_WRITE=1 dotnet test // --filter PropertyNamingGoldenTests. Compare mode is the default. using System.Runtime.CompilerServices; diff --git a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs new file mode 100644 index 0000000000..124a8ecdfe --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs @@ -0,0 +1,97 @@ +// SerializerKeys fails closed: a credential that cannot be matched to the serializer's contract is a +// refusal, never a silently unstripped response. + +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; +using MetaObjects.Codegen.Runtime; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class SerializerKeysTests +{ + public sealed class Row + { + public long Id { get; set; } + public string? PinHash { get; set; } + } + + private static readonly string[] Names = ["PinHash", "pinHash"]; + + [Fact] + public void The_default_contract_gives_the_policys_key() + { + var opts = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + Assert.Equal(["pin_hash"], SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + } + + [Fact] + public void A_type_without_the_credential_contributes_nothing_and_never_throws() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; + Assert.Empty(SerializerKeys.KeysOfType(typeof(string), opts, Names)); + } + + // A resolver whose properties carry no reflection member (what a custom resolver, a rebuilding + // modifier or a source-generated context can do). + private sealed class NoProviderResolver : IJsonTypeInfoResolver + { + public JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options) + { + var info = JsonTypeInfo.CreateJsonTypeInfo(type, options); + if (type != typeof(Row)) return info; + var id = info.CreateJsonPropertyInfo(typeof(long), "id"); + id.Get = o => ((Row)o).Id; + id.Set = (o, v) => ((Row)o).Id = (long)v!; + var pin = info.CreateJsonPropertyInfo(typeof(string), "pinHash"); + pin.Get = o => ((Row)o).PinHash; + pin.Set = (o, v) => ((Row)o).PinHash = (string?)v; + info.Properties.Add(id); + info.Properties.Add(pin); + return info; + } + } + + [Fact] + public void A_contract_with_no_reflection_member_is_refused_naming_the_type_and_property_but_no_value() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new NoProviderResolver() }; + var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + Assert.Contains("refused", ex.Message); + } + + private sealed class RowConverter : JsonConverter + { + public override Row? Read(ref Utf8JsonReader reader, Type t, JsonSerializerOptions o) => throw new NotSupportedException(); + public override void Write(Utf8JsonWriter writer, Row value, JsonSerializerOptions o) => writer.WriteStringValue("x"); + } + + [Fact] + public void A_custom_converter_for_the_row_type_is_refused() + { + var opts = new JsonSerializerOptions { Converters = { new RowConverter() }, TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + var ex = Assert.Throws(() => SerializerKeys.KeysOfType(typeof(Row), opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + } + + [Fact] + public void A_credential_the_contract_does_not_carry_is_refused() + { + // A modifier that drops the property from the contract while the type still declares it. + var resolver = new DefaultJsonTypeInfoResolver(); + resolver.Modifiers.Add(ti => { if (ti.Type == typeof(Row)) ti.Properties.Remove(ti.Properties.Single(p => p.Name == "PinHash")); }); + var opts = new JsonSerializerOptions { TypeInfoResolver = resolver }; + var ex = Assert.Throws(() => SerializerKeys.KeysOf(new[] { new Row() }, false, opts, Names)); + Assert.Contains("Row.PinHash", ex.Message); + } + + [Fact] + public void Strip_also_removes_a_key_that_spells_the_credential_ignoring_case_and_separators() + { + var node = System.Text.Json.Nodes.JsonNode.Parse("""{"id":1,"pin_hash":"v","PIN-HASH":"v","name":"n"}""")!; + SerializerKeys.Strip(node, [], Names); + Assert.Equal("""{"id":1,"name":"n"}""", node.ToJsonString()); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index acb75724f2..d843530d9e 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -319,6 +319,9 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); sb.AppendLine($" public static IEndpointRouteBuilder Map{cls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); + // Refuse to start when the host's serializer contract cannot be read to strip a credential. + if (credentials.Count > 0) + sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] {{ typeof({readCls}) }}, {NamesLiteral(credentials)});"); AppendDecimalRangeGroup(sb); // List — honours ?limit / ?offset / ?sort / ?withCount per api-contract.md. @@ -655,6 +658,11 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t AppendUnauthenticatedRoutesDoc(sb, baseCls, readOnly: false); sb.AppendLine($" public static IEndpointRouteBuilder Map{baseCls}Routes(this IEndpointRouteBuilder app, string prefix = \"/api\")"); sb.AppendLine(" {"); + if (baseCredentials.Count > 0) + { + var credTypes = new[] { baseCls }.Concat(tph.Subtypes.Select(st => ValueObjectNames.TypeRef(st.Entity, ctx.Root, ctx.Config, ValueObjectNames.Namespace(baseEntity, ctx.Config)))); + sb.AppendLine($" SerializerKeys.EnsureContract(app.ServiceProvider, new global::System.Type[] {{ {string.Join(", ", credTypes.Select(t => $"typeof({t})"))} }}, {NamesLiteral(baseCredentials)});"); + } AppendDecimalRangeGroup(sb); // --- Polymorphic list: GET / (union of all subtypes; each row carries its discriminator) --- @@ -848,7 +856,13 @@ private static List WireKeys(MetaField f, GenConfig config) => // The CLR property names of an entity's credentials. The JSON key each is written under is not // derived here: the generated result asks the host's serializer (SerializerKeys.KeysOf). private static List CredentialNames(MetaObject entity, GenConfig config) => - entity.Fields().Where(IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); + entity.Fields().Where(IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); + + // The CLR property first (what the serializer's contract is matched on), then the field name: the + // normalized-spelling backstop in SerializerKeys.Strip also removes a key that spells it. Equal + // ignoring case when no resolver renames, so the list is then the one CLR name. + private static IEnumerable CredentialSpellings(MetaField f, GenConfig config) => + new[] { CSharpNaming.PropertyName(f, config), f.Name }.Distinct(StringComparer.OrdinalIgnoreCase); // `string.Equals(prop.Name, "a", ...) || string.Equals(prop.Name, "b", ...)` over the keys. private static string KeyMatch(IEnumerable keys) => @@ -903,7 +917,7 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" var node = global::System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); sb.AppendLine(" // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names."); sb.AppendLine($" SerializerKeys.Strip(_envelope && node is global::System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node,"); - sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names));"); + sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names);"); sb.AppendLine(" http.Response.StatusCode = _status;"); sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); @@ -1534,7 +1548,7 @@ private static void AppendTphSubtypeRoutes( // #484 — as on a plain entity: write-denied keys ignored, credentials omitted. One shared // column may be declared by several subtypes, so a mark on any declaration counts. var deniedFields = HierarchyMarkedFields(st.Entity, hierarchy, IsApiWriteDenied); - var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).Select(f => CSharpNaming.PropertyName(f, config)).ToList(); + var credentials = HierarchyMarkedFields(st.Entity, hierarchy, IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); // Per-subtype list: GET // sb.AppendLine(); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs index 51b65a3fe2..954d5b6312 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs @@ -80,7 +80,7 @@ is Microsoft.Extensions.Options.IOptions on every runtime type found in (a row, a list of /// rows, or, with , the rows of a { rows, total } envelope). A /// polymorphic list contributes each element's own type, so a subtype-declared property is found. + /// Fails closed: see . /// public static HashSet KeysOf(object? body, bool envelope, JsonSerializerOptions options, IReadOnlyCollection clrNames) { var keys = new HashSet(StringComparer.Ordinal); foreach (var type in RowTypes(body, envelope)) + keys.UnionWith(KeysOfType(type, options, clrNames)); + return keys; + } + + /// + /// The JSON keys writes the credential properties of under, + /// read from the serializer's contract. A type that declares none of contributes + /// nothing. For a type that does, this THROWS rather than guess when the contract cannot be read: + /// its kind is not an object (a custom converter), any property has no reflection member behind it + /// (a custom type-info resolver, a modifier that rebuilds properties, a source-generated context that does + /// not carry it), or a credential has no matching property in the contract. A response that cannot be + /// stripped is refused, never sent. The message names the type and the credential property, never a value. + /// + public static HashSet KeysOfType(Type type, JsonSerializerOptions options, IReadOnlyCollection clrNames) + { + var keys = new HashSet(StringComparer.Ordinal); + var declared = clrNames + .Where(n => type.GetProperty(n, BindingFlags.Public | BindingFlags.Instance) is { } prop && !IsIgnored(prop)) + .Distinct(StringComparer.Ordinal).ToList(); + if (declared.Count == 0) return keys; + + JsonTypeInfo info; + try { info = options.GetTypeInfo(type); } + catch (NotSupportedException e) { throw Unreadable(type, declared, "the serializer has no contract for it (" + e.GetType().Name + ")"); } + if (info.Kind != JsonTypeInfoKind.Object) + throw Unreadable(type, declared, $"its JSON contract is a {info.Kind}, not an object (a custom converter?)"); + if (info.Properties.Any(p => p.AttributeProvider is not MemberInfo)) + throw Unreadable(type, declared, "a property has no reflection member behind it (a custom type-info resolver, a modifier that rebuilds properties, or a source-generated context?)"); + foreach (var name in declared) { - var info = options.GetTypeInfo(type); - if (info.Kind != JsonTypeInfoKind.Object) continue; - foreach (var p in info.Properties) - if (p.AttributeProvider is MemberInfo member && clrNames.Contains(member.Name)) - keys.Add(p.Name); + var matched = info.Properties.Where(p => ((MemberInfo)p.AttributeProvider!).Name == name).Select(p => p.Name).ToList(); + if (matched.Count == 0) throw Unreadable(type, [name], "the credential has no property in the serializer's contract"); + keys.UnionWith(matched); } return keys; } - /// Remove every key in from the object, or from each object of the array. - public static void Strip(JsonNode? node, HashSet keys) + /// + /// Check, at startup (the generated route mapping calls it), that the credential properties of + /// can be stripped under the host's configured JsonOptions. Throws as + /// does, so a host whose serializer contract cannot be read fails to start + /// instead of failing on the first response. + /// + public static void EnsureContract(IServiceProvider services, IReadOnlyCollection types, IReadOnlyCollection clrNames) { - if (keys.Count == 0) return; - if (node is JsonArray a) { foreach (var e in a) Strip(e, keys); return; } + var options = (services.GetService(typeof(Microsoft.Extensions.Options.IOptions)) + as Microsoft.Extensions.Options.IOptions)?.Value.SerializerOptions + ?? JsonSerializerOptions.Default; + foreach (var type in types) KeysOfType(type, options, clrNames); + } + + private static bool IsIgnored(PropertyInfo prop) => + prop.GetCustomAttribute() is { Condition: System.Text.Json.Serialization.JsonIgnoreCondition.Always }; + + private static InvalidOperationException Unreadable(Type type, IEnumerable credentials, string why) => + new($"cannot strip the credential {string.Join(", ", credentials.Select(c => type.Name + "." + c))} from a response: {why}. " + + "Credential stripping reads the serializer's reflection-visible contract; the response is refused rather than sent unstripped."); + + /// + /// Remove every key in from the object, or from each object of the array, and, as a + /// second line of defence, every key that spells one of ignoring case, _ and + /// -. + /// + public static void Strip(JsonNode? node, HashSet keys, IReadOnlyCollection? names = null) + { + if (keys.Count == 0 && (names is null || names.Count == 0)) return; + var normalized = names is null ? [] : names.Select(Normalize).ToHashSet(StringComparer.Ordinal); + StripCore(node, keys, normalized); + } + + private static void StripCore(JsonNode? node, HashSet keys, HashSet normalized) + { + if (node is JsonArray a) { foreach (var e in a) StripCore(e, keys, normalized); return; } if (node is not JsonObject o) return; - foreach (var key in o.Select(p => p.Key).Where(keys.Contains).ToList()) o.Remove(key); + foreach (var key in o.Select(p => p.Key).Where(k => keys.Contains(k) || normalized.Contains(Normalize(k))).ToList()) o.Remove(key); } + private static string Normalize(string key) => key.Replace("_", "").Replace("-", "").ToLowerInvariant(); + /// /// The map from a body's JSON key (compared ignoring case, as the PATCH merge always has) to the CLR /// property name gives that key on . From 7eefd852d8dca25e0df95c5e472ebdec19a95e82 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:21:39 -0500 Subject: [PATCH 247/267] docs(changelog): the fail-closed contract, the rc.1 write-side hole, and what default output now changes Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f2417b59f2..7614569141 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -686,10 +686,22 @@ vocabulary; upgrade every port together. the same way under any policy. Only single-word credentials, or a host with the default camelCase policy and no rename, were safe. 1.2.3 fixes it: the omit list and the PATCH and PUT key lookup read the key from the serializer's own contract (`JsonSerializerOptions.GetTypeInfo`), - so a naming policy, a rename, an attribute or a type-info modifier cannot escape them. The write - side was never exploitable: a PATCH or PUT body key that missed the deny list also missed the - property and was dropped. Regenerate every project whose host sets a snake or kebab policy or - `GenConfig.PropertyNaming`; a project on the default policy with no rename is unaffected. + so a naming policy, a rename or an attribute cannot escape them. Stripping **fails closed**: when + the contract cannot be read (a custom converter for the row type, a custom type-info resolver or a + modifier that leaves a property without its reflection member, a contract that lacks the + credential), the generated route mapping throws at startup, and a response that reaches + `CredentialOmittingResult` anyway is refused with an exception naming the type and the credential + property (never a value), instead of being sent unstripped. A key that spells the credential + ignoring case, `_` and `-` is also removed. A host that sets a custom `TypeInfoResolver` or a + source-generated `JsonSerializerContext` must give the entity properties their reflection member + (the default reflection resolver does), or the app will not start. The write side of the released + 1.2.0 and 1.2.2 was not exploitable: a PATCH or PUT body key that missed the deny list also missed + the property and was dropped. **In 1.2.3-rc.1** (the first release with `GenConfig.PropertyNaming`), + a rename beyond case let `PATCH {"secret":"x"}` or `PUT` write a credential or a `@formExclude` + field, because the deny arm matched the field name only and the generic lookup found the renamed + property case-insensitively; 1.2.3 closes that too. Regenerate every project whose host sets a + snake or kebab policy or `GenConfig.PropertyNaming`; a project on the default policy with no + rename is unaffected. ### Fixed @@ -709,7 +721,9 @@ vocabulary; upgrade every port together. dispatch looked a property up by the field name, so `?filter[]` on a property renamed beyond case threw (500); the generated allowlist now carries a field-to-property map, emitted only when a rename goes beyond case, and `EfCoreFilterDispatch.ApplyFilter` and `Validate` take it as an - optional argument. With no resolver set the output is byte-identical (pinned by a golden test). + optional argument. With no resolver set the output is unchanged except for the security change + above: regenerating changes every routes file (the PATCH key lookup) and the credential-bearing + ones further; a golden test pins the rest byte for byte. - **Fix, TypeScript and C#: a passthrough may walk a reference backwards when at most one row references it (rc.21).** A reverse hop was always to-many, so a passthrough over it was refused From 1dbc28dba967f00da59b471700ba9d57e6903504 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sat, 14 Nov 2026 23:31:14 -0500 Subject: [PATCH 248/267] docs(changelog): the value-object credential known limit A view.password on a value-object member is not stripped; stripping covers top-level entity fields only. Recorded as a known limit until fixed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7614569141..4e508ed0cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -701,7 +701,10 @@ vocabulary; upgrade every port together. field, because the deny arm matched the field name only and the generic lookup found the renamed property case-insensitively; 1.2.3 closes that too. Regenerate every project whose host sets a snake or kebab policy or `GenConfig.PropertyNaming`; a project on the default policy with no - rename is unaffected. + rename is unaffected. **Known limit, not fixed here:** a credential (`view.password`) declared on a + value-object member is not listed, checked or stripped. Only an entity's top-level fields are + treated as credentials, and stripping does not recurse into nested objects. Declare credentials + as top-level entity fields until that is fixed. ### Fixed From 4113efecb98487903886b47309ee94aa187c4a3f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 09:33:24 -0500 Subject: [PATCH 249/267] fix(csharp): type a value-mapped enum's converter on the non-nullable enum A scalar @intValueMap or @stringValueMap enum's lambda pair went straight into HasConversion(...), so EF typed the converter on the property: an optional field got ValueConverter. EF Core 8 cannot build the JSON collection reader for a parameterised Contains over that converter, and the query failed at runtime on Npgsql. The pair is now wrapped in new ValueConverter(...), for required and optional fields alike, as the array element converter already was. Member chains, the unmapped-value throw and HasMaxLength are unchanged; the committed integration fixture is regenerated. Tests: codegen assertions for optional and required, int- and string-stored fields plus an EF 8 compile; a live Postgres Contains query over each shape. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 ++ .../ObjectFieldCodegenTests.cs | 5 +- .../ValueMappedEnumConverterTypeTests.cs | 124 +++++++++++++++ .../Generators/DbContextGenerator.cs | 32 +++- .../Generated/AppDbContext.g.cs | 6 +- .../ValueMappedEnumContainsPostgresTests.cs | 145 ++++++++++++++++++ 6 files changed, 312 insertions(+), 13 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs create mode 100644 server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e508ed0cb..d5946c2536 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -708,6 +708,19 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, C#: a query can test an optional value-mapped enum against a list (rc.22).** + `DbContextGenerator` handed a scalar `@intValueMap` or `@stringValueMap` enum's two conversion + lambdas straight to `HasConversion(...)`, so EF typed the converter on the property: an optional + field got `ValueConverter` (or ``). EF Core 8 cannot build the JSON collection + reader for a parameterised collection over that converter, and a query such as + `db.Widgets.Where(w => active.Contains(w.Status))` failed at runtime on Npgsql + (`InvalidOperationException` or `MissingMethodException` on + `JsonNullableStructCollectionReaderWriter`, by patch version). The pair is now wrapped in + `new ValueConverter(...)`, typed on the non-nullable enum for required and optional + fields alike, as an enum array's element converter already was. The stored values, the throw on an + unmapped value and `HasMaxLength` are unchanged. Regenerating changes every such line; an override + of `EnumConversionCall` that edits the returned text by pattern should be checked against it. + - **Fix, C#: PATCH and PUT apply a multi-word field under a snake or kebab JSON naming policy (rc.22).** The merge matched a body key to a property by name, so `seat_count` never found `SeatCount` and the update returned 200 with the field silently unchanged. The key is now resolved diff --git a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs index c4257f3ad2..04320a9858 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ObjectFieldCodegenTests.cs @@ -187,8 +187,9 @@ public void DbContext_configures_owned_types_flattened_and_json() // migration never created — measured against a real Postgres, not inferred. Assert.Contains("b.Property(p => p.Kind).HasColumnName(\"homeAddress_kind\").HasConversion();", dbContext); Assert.Contains( - "b.Property(p => p.Grade).HasColumnName(\"homeAddress_grade\").HasConversion(v => v == Address.AddressGrade.LO ? 1 : v == Address.AddressGrade.HI ? 2 : UnmappedEnumMember(v, \"grade\"), " + - "v => v == 1 ? Address.AddressGrade.LO : v == 2 ? Address.AddressGrade.HI : UnmappedEnumValue(v, \"grade\"));", + "b.Property(p => p.Grade).HasColumnName(\"homeAddress_grade\").HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(" + + "v => v == Address.AddressGrade.LO ? 1 : v == Address.AddressGrade.HI ? 2 : UnmappedEnumMember(v, \"grade\"), " + + "v => v == 1 ? Address.AddressGrade.LO : v == 2 ? Address.AddressGrade.HI : UnmappedEnumValue(v, \"grade\")));", dbContext); // ...and the fail-fast helper that converter names is declared, even though the ONLY // int-backed enum in this model lives on the value object, which is not an emitted diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs new file mode 100644 index 0000000000..dceba3f193 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs @@ -0,0 +1,124 @@ +// A scalar value-mapped field.enum (@intValueMap or @stringValueMap) is converted by an explicit +// ValueConverter typed on the NON-nullable enum, whether the field is required or optional. +// +// The lambda pair used to be passed straight to HasConversion(...), so EF typed it on the +// property's CLR type — ValueConverter for an optional field. Npgsql EF 8 cannot build +// the JSON collection reader for a parameterised `Contains` over such a property +// (MissingMethodException on JsonNullableStructCollectionReaderWriter`3[E?[], E?[], E]), so +// `active.Contains(w.Status)` failed at runtime. A converter on `E` is what EF's own built-in +// enum converters are, and what the array branch's element converter already was. The member +// chains themselves are unchanged. The live query is +// MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests. + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class ValueMappedEnumConverterTypeTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["DRAFT", "LIVE"], + "@intValueMap": { "DRAFT": 0, "LIVE": 5 } } }, + { "field.enum": { "name": "grade", "@required": true, "@values": ["LOW", "HIGH"], + "@intValueMap": { "LOW": 1, "HIGH": 9 } } }, + { "field.enum": { "name": "phase", "@maxLength": 12, "@values": ["OPEN", "SHUT"], + "@stringValueMap": { "OPEN": "open_v1", "SHUT": "shut_v1" } } }, + { "field.enum": { "name": "stage", "@required": true, "@maxLength": 10, "@values": ["NEW", "OLD"], + "@stringValueMap": { "NEW": "new", "OLD": "old" } } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + private const string Converter = "new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<"; + + private static GenContext Ctx() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(Model, id: "value-mapped-enum.json")]); + Assert.Empty(r.Errors); + return new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", IncludeNames = true }, + }; + } + + private static string DbContext(GenContext ctx) => + Assert.Single(new DbContextGenerator().Generate(ctx)).Content; + + private const string Owner = "global::Acme.Widget"; + + [Fact] + public void An_optional_int_mapped_enum_is_converted_on_the_non_nullable_enum() + { + var e = $"{Owner}.WidgetStatus"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Status).HasConversion({Converter}{e}, int>(" + + $"v => v == {e}.DRAFT ? 0 : v == {e}.LIVE ? 5 : UnmappedEnumMember(v, \"status\"), " + + $"v => v == 0 ? {e}.DRAFT : v == 5 ? {e}.LIVE : UnmappedEnumValue<{e}>(v, \"status\")));", + DbContext(Ctx())); + } + + [Fact] + public void A_required_int_mapped_enum_is_converted_on_the_enum() + { + var e = $"{Owner}.WidgetGrade"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Grade).HasConversion({Converter}{e}, int>(" + + $"v => v == {e}.LOW ? 1 : v == {e}.HIGH ? 9 : UnmappedEnumMember(v, \"grade\"), " + + $"v => v == 1 ? {e}.LOW : v == 9 ? {e}.HIGH : UnmappedEnumValue<{e}>(v, \"grade\")));", + DbContext(Ctx())); + } + + [Fact] + public void An_optional_string_mapped_enum_is_converted_on_the_non_nullable_enum_and_keeps_its_length() + { + var e = $"{Owner}.WidgetPhase"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Phase).HasConversion({Converter}{e}, string>(" + + $"v => v == {e}.OPEN ? \"open_v1\" : v == {e}.SHUT ? \"shut_v1\" : UnmappedEnumStoredMember(v, \"phase\"), " + + $"v => v == \"open_v1\" ? {e}.OPEN : v == \"shut_v1\" ? {e}.SHUT : UnmappedEnumStoredValue<{e}>(v, \"phase\"))).HasMaxLength(12);", + DbContext(Ctx())); + } + + [Fact] + public void A_required_string_mapped_enum_is_converted_on_the_enum_and_keeps_its_length() + { + var e = $"{Owner}.WidgetStage"; + Assert.Contains( + $"modelBuilder.Entity<{Owner}>().Property(x => x.Stage).HasConversion({Converter}{e}, string>(" + + $"v => v == {e}.NEW ? \"new\" : v == {e}.OLD ? \"old\" : UnmappedEnumStoredMember(v, \"stage\"), " + + $"v => v == \"new\" ? {e}.NEW : v == \"old\" ? {e}.OLD : UnmappedEnumStoredValue<{e}>(v, \"stage\"))).HasMaxLength(10);", + DbContext(Ctx())); + } + + // The typed converter compiles against EF Core 8 on a nullable property and a non-nullable + // one alike (PropertyBuilder.HasConversion(ValueConverter) takes a converter on E). + [Fact] + public void The_typed_converters_compile_against_EF_Core_8() + { + var ctx = Ctx(); + var sources = new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new NamesGenerator().Generate(ctx)) + .Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12))); + var comp = CSharpCompilation.Create( + "value_mapped_enum_" + Guid.NewGuid().ToString("N"), sources, DbContextCompileTests.BuildReferences(), + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var errors = comp.GetDiagnostics() + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()}") + .ToList(); + Assert.True(errors.Count == 0, "generated code should compile:\n" + string.Join("\n", errors)); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 31826361d7..73595626a0 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -2102,8 +2102,8 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met /// /// The complete HasConversion call for an enum property: the generic /// HasConversion<string>() for a string-backed enum, or - /// HasConversion(model→provider, provider→model) built from - /// @intValueMap for an int-backed one. + /// HasConversion(new ValueConverter<E, int|string>(model→provider, provider→model)) + /// built from @intValueMap / @stringValueMap for a value-mapped one. /// /// /// The mapping is emitted as a TERNARY CHAIN rather than a switch @@ -2165,7 +2165,7 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met foreach (var m in members) fromStored.Append($"v == \"{CSharpNaming.CSharpStringLiteral(EnumStorage.StoredValue(f, m))}\" ? {type}.{m} : "); fromStored.Append($"{UnmappedEnumStoredValueHelperName}<{type}>(v, \"{f.Name}\")"); - return $"HasConversion({toStored}, {fromStored}){maxLength}"; + return $"HasConversion({TypedEnumConverter(type, "string")}({toStored}, {fromStored})){maxLength}"; } // Read the ints THROUGH the map, keyed by member, so @values stays the SSOT and a @@ -2188,7 +2188,7 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met // as the LAST member's int, silently. for (var i = 0; i < members.Count; i++) toProvider.Append($"v == {type}.{members[i]} ? {ints[i]} : "); - // Typed object: the lambda's parameter is the property's type, nullable or not. + // Typed object: the helper takes the enum boxed, so it serves any converter's model type. toProvider.Append($"{UnmappedEnumMemberHelperName}(v, \"{f.Name}\")"); // Every member gets its own branch here (no last-member fallthrough) so the // final else can reject an int the model does not describe. @@ -2201,12 +2201,28 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met // lambdas against (CS1660), so the pair is wrapped in an explicit ValueConverter. // The element converter is the scalar pair unchanged, so each element is stored as // its declared int and an unmapped stored element throws exactly as a scalar does. - if (f.ResolvedIsArray()) - return "HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<" - + $"{type}, int>({toProvider}, {fromProvider}))"; - return $"HasConversion({toProvider}, {fromProvider})"; + // A scalar takes the same explicitly typed converter (see TypedEnumConverter). + return $"HasConversion({TypedEnumConverter(type, "int")}({toProvider}, {fromProvider}))"; } + /// + /// new ValueConverter<E, provider> — a value-mapped enum's converter, typed on the + /// NON-nullable enum whatever the property's nullability. + /// + /// + /// Handing the lambda pair straight to a scalar property's HasConversion(...) types it + /// on the property's CLR type, so an OPTIONAL field got a ValueConverter<E?, int>. + /// EF Core 8 cannot build the JSON collection reader/writer for a parameterised collection + /// over that converter, and a query such as active.Contains(w.Status) fails at runtime + /// (Npgsql: an InvalidOperationException or a MissingMethodException on + /// JsonNullableStructCollectionReaderWriter, by patch version). A converter on E is + /// what EF's own enum converters are and what an array's element converter already was; EF + /// passes null around it and never invokes the expressions on null, so the member chains + /// stay as they are. + /// + private static string TypedEnumConverter(string enumType, string provider) => + $"new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter<{enumType}, {provider}>"; + // #214 [0] — the per-field EF TYPE-converter emission, factored out so the SAME set of // converters configures BOTH the write entity (its derived-EXCLUDED field set) AND a // write-through entity's View read model (ALL fields, incl. the derived origin.* diff --git a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs index 37a2575de8..3352ed6589 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Generated/AppDbContext.g.cs @@ -60,7 +60,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity().HasNoKey().ToView("v_all_types_breakdown"); modelBuilder.Entity().Property(x => x.Level).HasConversion(); - modelBuilder.Entity().Property(x => x.LegacyStatus).HasConversion(v => v == global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED ? 9 : UnmappedEnumMember(v, "legacyStatus"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED : UnmappedEnumValue(v, "legacyStatus")); + modelBuilder.Entity().Property(x => x.LegacyStatus).HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED ? 9 : UnmappedEnumMember(v, "legacyStatus"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.AllTypesBreakdown.AllTypesBreakdownLegacyStatus.ARCHIVED : UnmappedEnumValue(v, "legacyStatus"))); modelBuilder.Entity().HasNoKey().ToView("v_asset_activity"); modelBuilder.Entity().HasNoKey().ToView("v_asset_days"); modelBuilder.Entity().HasNoKey().ToView("v_auths_by_kind"); @@ -94,7 +94,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().OwnsOne(x => x.Settings, b => b.ToJson(global::MetaObjects.IntegrationTests.Generated.AllTypesNames.SettingsColumn)); modelBuilder.Entity().OwnsMany(x => x.Labels, b => b.ToJson(global::MetaObjects.IntegrationTests.Generated.AllTypesNames.LabelsColumn)); modelBuilder.Entity().Property(x => x.EnumVal).HasConversion(); - modelBuilder.Entity().Property(x => x.IntEnumVal).HasConversion(v => v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED ? 9 : UnmappedEnumMember(v, "intEnumVal"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED : UnmappedEnumValue(v, "intEnumVal")); + modelBuilder.Entity().Property(x => x.IntEnumVal).HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED ? 9 : UnmappedEnumMember(v, "intEnumVal"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.AllTypes.AllTypesIntEnumVal.ARCHIVED : UnmappedEnumValue(v, "intEnumVal"))); modelBuilder.Entity().Property(x => x.DecVal).HasPrecision(18, 6); modelBuilder.Entity().Property(x => x.TsVal).HasColumnType("timestamp without time zone"); modelBuilder.Entity().Property(x => x.TsTzVal).HasColumnType("timestamp with time zone"); @@ -119,7 +119,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.PersonAId).OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.PersonBId).OnDelete(DeleteBehavior.NoAction); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.GadgetId).OnDelete(DeleteBehavior.NoAction); - modelBuilder.Entity().Property(x => x.State).HasConversion(v => v == global::MetaObjects.IntegrationTests.Generated.PublishState.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.PublishState.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.PublishState.ARCHIVED ? 9 : UnmappedEnumMember(v, "state"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.PublishState.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.PublishState.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.PublishState.ARCHIVED : UnmappedEnumValue(v, "state")); + modelBuilder.Entity().Property(x => x.State).HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == global::MetaObjects.IntegrationTests.Generated.PublishState.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.PublishState.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.PublishState.ARCHIVED ? 9 : UnmappedEnumMember(v, "state"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.PublishState.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.PublishState.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.PublishState.ARCHIVED : UnmappedEnumValue(v, "state"))); modelBuilder.Entity().PrimitiveCollection(x => x.History).ElementType().HasConversion(new global::Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter(v => v == global::MetaObjects.IntegrationTests.Generated.PublishState.DRAFT ? 0 : v == global::MetaObjects.IntegrationTests.Generated.PublishState.PUBLISHED ? 5 : v == global::MetaObjects.IntegrationTests.Generated.PublishState.ARCHIVED ? 9 : UnmappedEnumMember(v, "history"), v => v == 0 ? global::MetaObjects.IntegrationTests.Generated.PublishState.DRAFT : v == 5 ? global::MetaObjects.IntegrationTests.Generated.PublishState.PUBLISHED : v == 9 ? global::MetaObjects.IntegrationTests.Generated.PublishState.ARCHIVED : UnmappedEnumValue(v, "history"))); modelBuilder.Entity().Property(x => x.PreciseKg).HasPrecision(9, 4); modelBuilder.Entity().HasOne().WithMany().HasForeignKey(e => e.ParentId).OnDelete(DeleteBehavior.NoAction); diff --git a/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs b/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs new file mode 100644 index 0000000000..51dcd65e24 --- /dev/null +++ b/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs @@ -0,0 +1,145 @@ +// ValueMappedEnumContainsPostgresTests — a parameterised `Contains` over a scalar value-mapped +// field.enum (@intValueMap or @stringValueMap), through the GENERATED entity + AppDbContext, +// compiled in memory and run against a real Postgres. +// +// The generated converter used to be the bare lambda pair handed to HasConversion(...), which EF +// types on the property's CLR type: ValueConverter for an OPTIONAL field. Npgsql EF 8 +// cannot build the JSON collection reader for a parameterised collection over that converter, so +// +// E?[] active = { E.LIVE }; +// db.Widgets.Where(w => active.Contains(w.Status)).Count(); +// +// threw: InvalidOperationException ("When building an array mapping over 'Nullable`1', the +// JsonValueReaderWriter for element mapping ... is incorrect") on the EF 8.0.10 this project pins, +// MissingMethodException on JsonNullableStructCollectionReaderWriter`3[E?[], E?[], E] on later 8.0 +// patches. The converter is now typed on the non-nullable enum. Required fields and string-stored +// enums are covered alongside, so each shape the converter takes is queried. +// +// Postgres needs METAOBJECTS_TEST_PG_URL (a fresh database is created and dropped) or Docker: +// dotnet test server/csharp/MetaObjects.IntegrationTests/MetaObjects.IntegrationTests.csproj \ +// --filter "FullyQualifiedName~ValueMappedEnumContainsPostgresTests" + +using System.Linq.Expressions; +using System.Reflection; +using MetaObjects.IntegrationTests.Runner; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using Xunit; + +namespace MetaObjects.IntegrationTests; + +public sealed class ValueMappedEnumContainsPostgresTests +{ + private const string Model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Widget", "children": [ + { "source.rdb": { "@table": "widgets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["DRAFT", "LIVE", "GONE"], + "@intValueMap": { "DRAFT": 0, "LIVE": 5, "GONE": 9 } } }, + { "field.enum": { "name": "grade", "@required": true, "@values": ["LOW", "HIGH"], + "@intValueMap": { "LOW": 1, "HIGH": 7 } } }, + { "field.enum": { "name": "phase", "@maxLength": 12, "@values": ["OPEN", "SHUT"], + "@stringValueMap": { "OPEN": "open_v1", "SHUT": "shut_v1" } } }, + { "field.enum": { "name": "stage", "@required": true, "@maxLength": 10, "@values": ["NEW", "OLD"], + "@stringValueMap": { "NEW": "new", "OLD": "old" } } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}} + ]}} + """; + + private const string Ddl = """ + CREATE TABLE "widgets" ( + "id" BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + "status" INTEGER, + "grade" INTEGER NOT NULL, + "phase" VARCHAR(12), + "stage" VARCHAR(10) NOT NULL + ); + """; + + private static readonly Lazy Gen = new(() => GeneratedEfModel.Compile(Model, "Acme.EnumContains")); + + private static object Member(string enumType, string member) => Gen.Value.Enum("Widget+" + enumType, member); + + private static object Widget(string? status, string grade, string? phase, string stage) => + Gen.Value.New("Widget", + ("Status", status is null ? null : Member("WidgetStatus", status)), + ("Grade", Member("WidgetGrade", grade)), + ("Phase", phase is null ? null : Member("WidgetPhase", phase)), + ("Stage", Member("WidgetStage", stage))); + + [Fact] + public async Task Postgres_runs_a_parameterised_Contains_over_each_value_mapped_enum_shape() + { + await using var pg = await PostgresContainer.StartAsync(); + await using (var conn = new NpgsqlConnection(pg.ConnectionString)) + { + await conn.OpenAsync(); + await using var ddl = new NpgsqlCommand(Ddl, conn); + await ddl.ExecuteNonQueryAsync(); + } + + using (var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString))) + { + db.Add(Widget("DRAFT", "LOW", "OPEN", "NEW")); + db.Add(Widget("LIVE", "HIGH", "SHUT", "OLD")); + db.Add(Widget("GONE", "HIGH", "SHUT", "OLD")); + db.Add(Widget(null, "LOW", null, "NEW")); + db.SaveChanges(); + } + + // Every shape is queried and every outcome reported together, so one failure does not hide + // whether the others hold. + var failures = new List(); + void Expect(int expected, string property, bool nullable, params object[] members) + { + using var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString)); + try + { + var actual = CountIn(db, property, nullable, members); + if (actual != expected) failures.Add($"{property}: counted {actual}, expected {expected}"); + } + catch (Exception e) + { + var inner = GeneratedEfModel.Chain(e).Last(); + failures.Add($"{property}: {inner.GetType().Name}: {inner.Message}"); + } + } + + // Optional int-stored: the repro. Two of the three non-null rows match. + Expect(2, "Status", nullable: true, Member("WidgetStatus", "LIVE"), Member("WidgetStatus", "GONE")); + // Optional string-stored. + Expect(1, "Phase", nullable: true, Member("WidgetPhase", "OPEN")); + // Required int-stored and string-stored. + Expect(2, "Grade", nullable: false, Member("WidgetGrade", "HIGH")); + Expect(2, "Stage", nullable: false, Member("WidgetStage", "NEW")); + + Assert.True(failures.Count == 0, string.Join("\n", failures)); + } + + // `db.Set().Where(w => active.Contains(w.)).Count()`, with `active` a + // CAPTURED array — a query parameter, not constants inlined into the SQL — typed as the + // property is: E?[] for an optional field, E[] for a required one. + private static int CountIn(DbContext db, string property, bool nullable, params object[] members) + { + var enumType = members[0].GetType(); + var elementType = nullable ? typeof(Nullable<>).MakeGenericType(enumType) : enumType; + var active = Array.CreateInstance(elementType, members.Length); + for (var i = 0; i < members.Length; i++) active.SetValue(members[i], i); + return (int)typeof(ValueMappedEnumContainsPostgresTests) + .GetMethod(nameof(CountInOf), BindingFlags.NonPublic | BindingFlags.Static)! + .MakeGenericMethod(Gen.Value.Type("Widget"), elementType) + .Invoke(null, [db, property, active])!; + } + + private static int CountInOf(DbContext db, string property, TElement[] active) + where TEntity : class + { + var w = Expression.Parameter(typeof(TEntity), "w"); + Expression> captured = () => active; + var body = Expression.Call(typeof(Enumerable), nameof(Enumerable.Contains), [typeof(TElement)], + captured.Body, Expression.Property(w, property)); + return db.Set().Where(Expression.Lambda>(body, w)).Count(); + } +} From e093b16cf7dc81ed1b54cd2f2d7d9b9d113ebf5c Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 09:42:28 -0500 Subject: [PATCH 250/267] test(csharp): NULL reads and a null list element for value-mapped enums The live Postgres test now asserts that an optional int-stored and string-stored column reads NULL back as null, and runs a Contains whose list holds null, which matches the NULL row as well as the listed member. The codegen test header names the exception on each EF 8 patch. Co-Authored-By: Claude Opus 5.5 --- .../ValueMappedEnumConverterTypeTests.cs | 8 ++-- .../ValueMappedEnumContainsPostgresTests.cs | 41 ++++++++++++++----- 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs index dceba3f193..18c173a6a3 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ValueMappedEnumConverterTypeTests.cs @@ -3,9 +3,11 @@ // // The lambda pair used to be passed straight to HasConversion(...), so EF typed it on the // property's CLR type — ValueConverter for an optional field. Npgsql EF 8 cannot build -// the JSON collection reader for a parameterised `Contains` over such a property -// (MissingMethodException on JsonNullableStructCollectionReaderWriter`3[E?[], E?[], E]), so -// `active.Contains(w.Status)` failed at runtime. A converter on `E` is what EF's own built-in +// the JSON collection reader for a parameterised `Contains` over such a property, so +// `active.Contains(w.Status)` failed at runtime: an InvalidOperationException ("When building an +// array mapping over 'Nullable`1', the JsonValueReaderWriter for element mapping ... is incorrect") +// on the EF 8.0.10 this repository pins, and a MissingMethodException on +// JsonNullableStructCollectionReaderWriter`3[E?[], E?[], E] on 8.0.11 and later. A converter on `E` is what EF's own built-in // enum converters are, and what the array branch's element converter already was. The member // chains themselves are unchanged. The live query is // MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests. diff --git a/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs b/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs index 51dcd65e24..2234dffff8 100644 --- a/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/ValueMappedEnumContainsPostgresTests.cs @@ -62,6 +62,8 @@ public sealed class ValueMappedEnumContainsPostgresTests private static object Member(string enumType, string member) => Gen.Value.Enum("Widget+" + enumType, member); + private static Type EnumType(string enumType) => Gen.Value.Type("Widget+" + enumType); + private static object Widget(string? status, string grade, string? phase, string stage) => Gen.Value.New("Widget", ("Status", status is null ? null : Member("WidgetStatus", status)), @@ -89,41 +91,58 @@ public async Task Postgres_runs_a_parameterised_Contains_over_each_value_mapped_ db.SaveChanges(); } + // An optional value-mapped column reads NULL back as null, int-stored and string-stored alike: + // EF never hands null to the typed converter, so it is neither refused nor read as a member. + using (var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString))) + { + var rows = GeneratedEfModel.All(db, Gen.Value.Type("Widget")); + Assert.Equal(4, rows.Count); + var unset = Assert.Single(rows, r => GeneratedEfModel.Get(r, "Status") is null); + Assert.Null(GeneratedEfModel.Get(unset, "Phase")); + Assert.Equal(Member("WidgetGrade", "LOW"), GeneratedEfModel.Get(unset, "Grade")); + Assert.Equal(Member("WidgetStage", "NEW"), GeneratedEfModel.Get(unset, "Stage")); + Assert.Single(rows, r => GeneratedEfModel.Get(r, "Phase") is null); + } + // Every shape is queried and every outcome reported together, so one failure does not hide // whether the others hold. var failures = new List(); - void Expect(int expected, string property, bool nullable, params object[] members) + void Expect(int expected, string property, string enumType, bool nullable, params object?[] members) { using var db = Gen.Value.NewContext(o => o.UseNpgsql(pg.ConnectionString)); + var label = $"{property} in [{string.Join(", ", members.Select(m => m?.ToString() ?? "null"))}]"; try { - var actual = CountIn(db, property, nullable, members); - if (actual != expected) failures.Add($"{property}: counted {actual}, expected {expected}"); + var actual = CountIn(db, property, EnumType(enumType), nullable, members); + if (actual != expected) failures.Add($"{label}: counted {actual}, expected {expected}"); } catch (Exception e) { var inner = GeneratedEfModel.Chain(e).Last(); - failures.Add($"{property}: {inner.GetType().Name}: {inner.Message}"); + failures.Add($"{label}: {inner.GetType().Name}: {inner.Message}"); } } // Optional int-stored: the repro. Two of the three non-null rows match. - Expect(2, "Status", nullable: true, Member("WidgetStatus", "LIVE"), Member("WidgetStatus", "GONE")); + Expect(2, "Status", "WidgetStatus", nullable: true, Member("WidgetStatus", "LIVE"), Member("WidgetStatus", "GONE")); // Optional string-stored. - Expect(1, "Phase", nullable: true, Member("WidgetPhase", "OPEN")); + Expect(1, "Phase", "WidgetPhase", nullable: true, Member("WidgetPhase", "OPEN")); + // A list holding null matches the row whose column is NULL, as well as the members listed. + Expect(2, "Status", "WidgetStatus", nullable: true, null, Member("WidgetStatus", "LIVE")); + Expect(2, "Phase", "WidgetPhase", nullable: true, null, Member("WidgetPhase", "OPEN")); // Required int-stored and string-stored. - Expect(2, "Grade", nullable: false, Member("WidgetGrade", "HIGH")); - Expect(2, "Stage", nullable: false, Member("WidgetStage", "NEW")); + Expect(2, "Grade", "WidgetGrade", nullable: false, Member("WidgetGrade", "HIGH")); + Expect(2, "Stage", "WidgetStage", nullable: false, Member("WidgetStage", "NEW")); Assert.True(failures.Count == 0, string.Join("\n", failures)); } // `db.Set().Where(w => active.Contains(w.)).Count()`, with `active` a // CAPTURED array — a query parameter, not constants inlined into the SQL — typed as the - // property is: E?[] for an optional field, E[] for a required one. - private static int CountIn(DbContext db, string property, bool nullable, params object[] members) + // property is: E?[] for an optional field, E[] for a required one. A null member is a null + // element of the E?[] list. + private static int CountIn(DbContext db, string property, Type enumType, bool nullable, params object?[] members) { - var enumType = members[0].GetType(); var elementType = nullable ? typeof(Nullable<>).MakeGenericType(enumType) : enumType; var active = Array.CreateInstance(elementType, members.Length); for (var i = 0; i < members.Length; i++) active.SetValue(members[i], i); From 59d22a5226ec2d9f423b283109f44f41a09853d1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 15 Nov 2026 10:47:12 -0500 Subject: [PATCH 251/267] chore(release): @metaobjectsdev TypeScript packages 1.2.3 --- CHANGELOG.md | 23 ++++++++++ bun.lock | 44 +++++++++---------- client/web/packages/react/package.json | 2 +- client/web/packages/runtime-web/package.json | 2 +- client/web/packages/tanstack/package.json | 2 +- examples/showcase/site-payload.json | 2 +- .../packages/ai-runtime/package.json | 2 +- server/typescript/packages/cli/package.json | 2 +- .../packages/codegen-ts-react/package.json | 2 +- .../packages/codegen-ts-tanstack/package.json | 2 +- .../packages/codegen-ts/package.json | 2 +- .../packages/docs-site/package.json | 2 +- .../typescript/packages/metadata/package.json | 2 +- .../packages/migrate-ts/package.json | 2 +- .../typescript/packages/render/package.json | 2 +- .../packages/runtime-ts/package.json | 2 +- server/typescript/packages/sdk/package.json | 2 +- 17 files changed, 60 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bbc93cadb3..4ac52741f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,13 @@ here.** ## [Unreleased] +## [1.2.3] — 2026-11-15 + +_npm `1.2.3` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ + +_Also PyPI `1.2.3`, NuGet `1.2.3` and Maven Central `8.2.3`: every port changed. PyPI skips +`1.2.2`. No vocabulary or `metamodelVersion` change._ + ### Changed - **`gen` skips rendering when nothing it is built from changed, in every port (ADR-0062).** @@ -37,6 +44,22 @@ here.** deletes the merge's temporary files in every case, under `$DEV_SCRATCH` when set. An untouched file is overwritten directly. +### Upgrading + +- **Add `**/.metaobjects/.gen-state/*` and `!**/.metaobjects/.gen-state/.hashes.json` to your + `.gitignore`.** Otherwise the new `.fingerprint-.json` file shows as untracked (in each + Maven module, for Java and Kotlin). The exception matters: the fingerprint files stay + uncommitted, but `.hashes.json` stays committed, so do not ignore the whole `.metaobjects/` + directory. +- **Generated TypeScript docs change if you are coming from 1.2.0.** Since 1.2.2 an update schema + leaves out every primary-key field, so the documented `UpdateSchema` type, the update + function's patch type and the PATCH/PUT body no longer list the key (the `id` row is gone). + Regenerate the docs and commit them, or `meta verify --codegen` reports drift. +- **Committed generated code changes too, not only the docs.** Because primary-key fields leave + the update schemas, and because of 1.2.2's create-route fixes in Java, Kotlin and C#, regenerate + and commit your generated code when you upgrade from 1.2.0 or 1.2.1. Otherwise the drift gate + fails against the new generators. + ## [1.2.2] — 2026-11-13 _npm `1.2.2` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ diff --git a/bun.lock b/bun.lock index e17b5343bf..8b21b75950 100644 --- a/bun.lock +++ b/bun.lock @@ -43,7 +43,7 @@ }, "client/web/packages/react": { "name": "@metaobjectsdev/react", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/runtime-web": "workspace:*", "react-easy-crop": "^6.2.3", @@ -73,7 +73,7 @@ }, "client/web/packages/runtime-web": { "name": "@metaobjectsdev/runtime-web", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "qs": "^6.13.0", @@ -86,7 +86,7 @@ }, "client/web/packages/tanstack": { "name": "@metaobjectsdev/tanstack", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/runtime-web": "workspace:*", }, @@ -113,7 +113,7 @@ }, "server/typescript/packages/ai-runtime": { "name": "@metaobjectsdev/ai-runtime", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", @@ -134,7 +134,7 @@ }, "server/typescript/packages/cli": { "name": "@metaobjectsdev/cli", - "version": "1.2.2", + "version": "1.2.3", "bin": { "meta": "./dist/bin/meta.js", }, @@ -179,7 +179,7 @@ }, "server/typescript/packages/codegen-ts": { "name": "@metaobjectsdev/codegen-ts", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", @@ -224,7 +224,7 @@ }, "server/typescript/packages/codegen-ts-react": { "name": "@metaobjectsdev/codegen-ts-react", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", @@ -242,7 +242,7 @@ }, "server/typescript/packages/codegen-ts-tanstack": { "name": "@metaobjectsdev/codegen-ts-tanstack", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", @@ -274,7 +274,7 @@ }, "server/typescript/packages/docs-site": { "name": "@metaobjectsdev/docs-site", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", @@ -326,7 +326,7 @@ }, "server/typescript/packages/metadata": { "name": "@metaobjectsdev/metadata", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "yaml": "^2.9.0", }, @@ -339,7 +339,7 @@ }, "server/typescript/packages/migrate-ts": { "name": "@metaobjectsdev/migrate-ts", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@iarna/toml": "^2.2.5", "@metaobjectsdev/metadata": "workspace:*", @@ -366,7 +366,7 @@ }, "server/typescript/packages/render": { "name": "@metaobjectsdev/render", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "mustache": "^4.2.0", "nunjucks": "^3.2.4", @@ -380,7 +380,7 @@ }, "server/typescript/packages/runtime-ts": { "name": "@metaobjectsdev/runtime-ts", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", @@ -419,7 +419,7 @@ }, "server/typescript/packages/sdk": { "name": "@metaobjectsdev/sdk", - "version": "1.2.2", + "version": "1.2.3", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "yaml": "^2.9.0", @@ -604,7 +604,7 @@ "@fastify/merge-json-schemas": ["@fastify/merge-json-schemas@0.2.2", "", { "dependencies": { "dequal": "^2.0.3" } }, "sha512-d/gx9sRbUCVgGRGzma46wLcwiY8noTqO2Nmjg/vbTARxHRE5bdh5PIL8s97Lt1X7ScRWRW52eVYxwIoPwIdVUA=="], - "@fastify/proxy-addr": ["@fastify/proxy-addr@5.1.2", "", { "dependencies": { "@fastify/forwarded": "^3.0.0", "ipaddr.js": "^2.1.0" } }, "sha512-uqB4QsgVoro0XDC+DIftIMGXHdBPn+lK6Ek3xXAIxPMCJfqxnbtyEoMCm2KPUVOuIosd7Cyw9HawEqMFM/UA+g=="], + "@fastify/proxy-addr": ["@fastify/proxy-addr@5.1.3", "", { "dependencies": { "@fastify/forwarded": "^3.0.0", "ipaddr.js": "^2.1.0" } }, "sha512-ptgIgB+abBNTs5lsKNvFaKMCauPaTOE6ZIjxJr3FxCLehmYQQKYGg4srwwNICR9QQlFrYw59jWAo+i9GalVCaw=="], "@grpc/grpc-js": ["@grpc/grpc-js@1.14.7", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ=="], @@ -1150,7 +1150,7 @@ "effect": ["effect@3.20.0", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-qMLfDJscrNG8p/aw+IkT9W7fgj50Z4wG5bLBy0Txsxz8iUHjDIkOgO3SV0WZfnQbNG2VJYb0b+rDLMrhM4+Krw=="], - "electron-to-chromium": ["electron-to-chromium@1.5.485", "", {}, "sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw=="], + "electron-to-chromium": ["electron-to-chromium@1.5.486", "", {}, "sha512-rpybw4Ac4ak/An6G1Me2+61xzwobowDGyuJe71QHHOVpkZv4fPVobsLl7WH6zHSKusAMpaHxGKTpOvpy7+r3dQ=="], "elkjs": ["elkjs@0.11.1", "", {}, "sha512-zxxR9k+rx5ktMwT/FwyLdPCrq7xN6e4VGGHH8hA01vVYKjTFik7nHOxBnAYtrgYUB1RpAiLvA1/U2YraWxyKKg=="], @@ -1194,7 +1194,7 @@ "fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="], - "fast-json-stringify": ["fast-json-stringify@7.3.5", "", { "dependencies": { "@fastify/merge-json-schemas": "^0.2.0", "ajv": "^8.12.0", "ajv-formats": "^3.0.1", "fast-uri": "^4.0.0", "json-schema-ref-resolver": "^3.0.0", "rfdc": "^1.2.0" } }, "sha512-g7H3xqJmdH9aWLWh8S3CqrRZFZ321yaeNHZp3QUDl3wtXDWjPChDXCDDTwA4M/zsU42nOhE+z5KmpCzgBaaCgw=="], + "fast-json-stringify": ["fast-json-stringify@7.3.6", "", { "dependencies": { "@fastify/merge-json-schemas": "^0.2.0", "ajv": "^8.12.0", "ajv-formats": "^3.0.1", "fast-uri": "^4.0.0", "json-schema-ref-resolver": "^3.0.0", "rfdc": "^1.2.0" } }, "sha512-hXCpiZTZGiER/Xree1Tb4PY1DREPUnlWTP5Df9hgtoDnUppulV7Km8lh1/NEBuqz4JnNGSXghnABudfZ/iwIzg=="], "fast-querystring": ["fast-querystring@1.1.2", "", { "dependencies": { "fast-decode-uri-component": "^1.0.1" } }, "sha512-g6KuKWmFXc0fID8WWH0jit4g0AGBoJhCkJMb1RmbsSEUNvQ+ZC8D6CUZ+GtF8nMzSPXnhiePyyqqipzNNEnHjg=="], @@ -1214,7 +1214,7 @@ "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], - "find-my-way": ["find-my-way@9.10.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-eru+uCPQ2g+nLBkf84MHP/KyNNMar0BDy0j+i8Fb72GF9/YHBZ58q7FODUtfVV7XU9nfRUHXSmaM8NmZcIbZ4Q=="], + "find-my-way": ["find-my-way@9.10.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-querystring": "^1.0.0", "safe-regex2": "^5.0.0" } }, "sha512-UwbZdEdk59YXIGPW/rbDn/Ayr3mJ5fPH/HJeMPlK8Ez10aUin4iyRwgJvNTSkRfpZ2h8uLX0LbvZm/YUBUpymw=="], "foreground-child": ["foreground-child@3.3.1", "", { "dependencies": { "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" } }, "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw=="], @@ -1336,7 +1336,7 @@ "libsql": ["libsql@0.4.7", "", { "dependencies": { "@neon-rs/load": "^0.0.4", "detect-libc": "2.0.2" }, "optionalDependencies": { "@libsql/darwin-arm64": "0.4.7", "@libsql/darwin-x64": "0.4.7", "@libsql/linux-arm64-gnu": "0.4.7", "@libsql/linux-arm64-musl": "0.4.7", "@libsql/linux-x64-gnu": "0.4.7", "@libsql/linux-x64-musl": "0.4.7", "@libsql/win32-x64-msvc": "0.4.7" }, "os": [ "linux", "win32", "darwin", ], "cpu": [ "x64", "arm64", ] }, "sha512-T9eIRCs6b0J1SHKYIvD8+KCJMcWZ900iZyxdnSCdqxN12Z1ijzT+jY5nrk72Jw4B0HGzms2NgpryArlJqvc3Lw=="], - "light-my-request": ["light-my-request@6.8.0", "", { "dependencies": { "@fastify/deepmerge": "^3.1.0", "cookie": "^2.0.0", "process-warning": "^5.0.0", "set-cookie-parser": "^3.0.1" } }, "sha512-5Q8PjoSEdtGIB8fikZsTem5vgRo4F2mR6vUKTDW/H1g6MtAt8e3duQbg/QxL5yzg6BZhor2KOUm3hhWMWLTZwg=="], + "light-my-request": ["light-my-request@6.8.1", "", { "dependencies": { "@fastify/deepmerge": "^3.1.0", "cookie": "^2.0.0", "process-warning": "^5.0.0", "set-cookie-parser": "^3.0.1" } }, "sha512-20biUK0HAIPG9BZOK3/4s8uVAkAoi1+qW55lciHZCR0puTWipBgyMPEUjqXDWLjsZeqfO6DGsuwW5eyfsTGtyg=="], "lodash": ["lodash@4.18.1", "", {}, "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q=="], @@ -1598,7 +1598,7 @@ "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], - "sql-escaper": ["sql-escaper@1.5.2", "", {}, "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg=="], + "sql-escaper": ["sql-escaper@1.6.0", "", {}, "sha512-I+WA4xb3mprpxUbLFtraZRY8L4vI0+xEOPLxHSI4wOuZ8cSpjVBzeuQpnPjW6PfdjeSkD9n/IBoYzH0LGTVSoQ=="], "ssh-remote-port-forward": ["ssh-remote-port-forward@1.0.4", "", { "dependencies": { "@types/ssh2": "^0.5.48", "ssh2": "^1.4.0" } }, "sha512-x0LV1eVDwjf1gmG7TTnfqIzf+3VPRz7vrNIjX6oYLbeCrf/PeVY6hkT68Mg+q02qXxQhrLjB0jfgvhevoCRmLQ=="], @@ -1638,9 +1638,9 @@ "thread-stream": ["thread-stream@4.2.1", "", { "dependencies": { "real-require": "^1.0.0" } }, "sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ=="], - "tldts": ["tldts@7.5.2", "", { "dependencies": { "tldts-core": "^7.5.2" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-p+JwEdxIWQx033pMvW9ULBbyC1Eg6JtWo2Mo0jbC8TVSjp2QrHFE+WKs8JpMGc3ECMsmBpU2RH/25NgX3k1ulg=="], + "tldts": ["tldts@7.5.4", "", { "dependencies": { "tldts-core": "^7.5.4" }, "bin": { "tldts": "bin/cli.js" } }, "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q=="], - "tldts-core": ["tldts-core@7.5.2", "", {}, "sha512-8W1topazDwhMKbm2I83IPa57Ow5VUxFgLbXv42+vSILnv8FY5OHvdEY/tS6WoWeMbxkHZQhra5cmeFHriKptSQ=="], + "tldts-core": ["tldts-core@7.5.4", "", {}, "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA=="], "tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="], diff --git a/client/web/packages/react/package.json b/client/web/packages/react/package.json index 5ccfeff21f..9f98ac10f9 100644 --- a/client/web/packages/react/package.json +++ b/client/web/packages/react/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/react", - "version": "1.2.2", + "version": "1.2.3", "description": "React runtime for metaobjects: useEntityForm hook and CurrencyInput component.", "type": "module", "main": "./dist/index.js", diff --git a/client/web/packages/runtime-web/package.json b/client/web/packages/runtime-web/package.json index ae0c6e4348..0c11a40c76 100644 --- a/client/web/packages/runtime-web/package.json +++ b/client/web/packages/runtime-web/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/runtime-web", - "version": "1.2.2", + "version": "1.2.3", "description": "Pure framework-agnostic browser core for metaobjects: currency, filter URL serialization, fetcher contract types.", "type": "module", "main": "./dist/index.js", diff --git a/client/web/packages/tanstack/package.json b/client/web/packages/tanstack/package.json index b524804714..d50f7ab3a6 100644 --- a/client/web/packages/tanstack/package.json +++ b/client/web/packages/tanstack/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/tanstack", - "version": "1.2.2", + "version": "1.2.3", "description": "TanStack runtime for metaobjects: EntityFetcherProvider, EntityGrid, default cell renderers.", "type": "module", "main": "./dist/index.js", diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 69bf2716b9..815a35e70c 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -1,6 +1,6 @@ { "registries": { - "npm": "1.2.2", + "npm": "1.2.3", "pypi": "1.2.1", "nuget": "1.2.2", "maven": "8.2.2", diff --git a/server/typescript/packages/ai-runtime/package.json b/server/typescript/packages/ai-runtime/package.json index 69fc612d73..86718e53ce 100644 --- a/server/typescript/packages/ai-runtime/package.json +++ b/server/typescript/packages/ai-runtime/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/ai-runtime", - "version": "1.2.2", + "version": "1.2.3", "description": "LLM call loop + typed-trace recorder adapters for MetaObjects: provider-neutral LlmClient seam, callLlm bridge, Composite/Langfuse/OTel recorders.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/cli/package.json b/server/typescript/packages/cli/package.json index f1e3c07511..bfb9fbcc77 100644 --- a/server/typescript/packages/cli/package.json +++ b/server/typescript/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/cli", - "version": "1.2.2", + "version": "1.2.3", "description": "CLI for MetaObjects: scaffold, codegen, migrate, and drift-detection commands.", "type": "module", "main": "./dist/src/index.js", diff --git a/server/typescript/packages/codegen-ts-react/package.json b/server/typescript/packages/codegen-ts-react/package.json index 343bdd944d..feb93461a0 100644 --- a/server/typescript/packages/codegen-ts-react/package.json +++ b/server/typescript/packages/codegen-ts-react/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/codegen-ts-react", - "version": "1.2.2", + "version": "1.2.3", "description": "React codegen for metaobjects — emits .form.tsx files using react-hook-form and @metaobjectsdev/react helpers.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/codegen-ts-tanstack/package.json b/server/typescript/packages/codegen-ts-tanstack/package.json index 07dd6d0ca9..97e41af0d8 100644 --- a/server/typescript/packages/codegen-ts-tanstack/package.json +++ b/server/typescript/packages/codegen-ts-tanstack/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/codegen-ts-tanstack", - "version": "1.2.2", + "version": "1.2.3", "description": "TanStack codegen for metaobjects — TanStack Query hooks for every entity, plus TanStack Table column definitions and grid-state hooks for entities declaring a layout.dataGrid.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/codegen-ts/package.json b/server/typescript/packages/codegen-ts/package.json index 0785f3400e..bd6bbbc430 100644 --- a/server/typescript/packages/codegen-ts/package.json +++ b/server/typescript/packages/codegen-ts/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/codegen-ts", - "version": "1.2.2", + "version": "1.2.3", "description": "TypeScript codegen engine for MetaObjects — emits Drizzle, Zod, and Fastify artifacts.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/docs-site/package.json b/server/typescript/packages/docs-site/package.json index c99675193e..803e2da771 100644 --- a/server/typescript/packages/docs-site/package.json +++ b/server/typescript/packages/docs-site/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/docs-site", - "version": "1.2.2", + "version": "1.2.3", "description": "HTML documentation-site generator for metaobjects models — a browsable multi-page site (nav, search, per-object/package pages, kind-aware ER diagrams). Powers the `docs-site` generator (`docsSiteFile()`).", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/metadata/package.json b/server/typescript/packages/metadata/package.json index b2ecbeddb6..dac57e08df 100644 --- a/server/typescript/packages/metadata/package.json +++ b/server/typescript/packages/metadata/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/metadata", - "version": "1.2.2", + "version": "1.2.3", "description": "Metamodel loader, types, and constants for the MetaObjects standard.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/migrate-ts/package.json b/server/typescript/packages/migrate-ts/package.json index c9340bfc10..d8e2c93f3a 100644 --- a/server/typescript/packages/migrate-ts/package.json +++ b/server/typescript/packages/migrate-ts/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/migrate-ts", - "version": "1.2.2", + "version": "1.2.3", "description": "Schema migration tooling for MetaObjects: diff metadata vs DB and emit SQL for Postgres and SQLite.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/render/package.json b/server/typescript/packages/render/package.json index fdc0d33c59..faedcd6a53 100644 --- a/server/typescript/packages/render/package.json +++ b/server/typescript/packages/render/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/render", - "version": "1.2.2", + "version": "1.2.3", "description": "Deterministic text render engine for MetaObjects templates — Mustache (logic-less, the cross-port default) and Jinja (via nunjucks), provider-resolved partials, format-driven escaping, build-time payload drift check, zero core dependency.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/runtime-ts/package.json b/server/typescript/packages/runtime-ts/package.json index c82fa8d88d..a26723ba7f 100644 --- a/server/typescript/packages/runtime-ts/package.json +++ b/server/typescript/packages/runtime-ts/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/runtime-ts", - "version": "1.2.2", + "version": "1.2.3", "description": "Node-side runtime helpers for MetaObjects: Fastify route builders, Drizzle filter/sort integration, Kysely drivers.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/sdk/package.json b/server/typescript/packages/sdk/package.json index 154be0412a..28a7770a56 100644 --- a/server/typescript/packages/sdk/package.json +++ b/server/typescript/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/sdk", - "version": "1.2.2", + "version": "1.2.3", "description": "Workspace helpers and agent-context assembly for MetaObjects projects.", "type": "module", "main": "./dist/index.js", From 78320346ef14b9d26a0cc10261e76abb98fb2a87 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 15 Nov 2026 10:53:05 -0500 Subject: [PATCH 252/267] chore(release): PyPI, NuGet and Maven Central 1.2.3 (Maven 8.2.3) --- docs/llms/llms-full.txt | 18 +++++++++--------- docs/llms/llms.txt | 14 +++++++------- examples/showcase/jvm/pom.xml | 2 +- examples/showcase/site-payload.json | 6 +++--- server/csharp/Directory.Build.props | 2 +- server/java/codegen-base/pom.xml | 2 +- .../codegen-kotlin-exposed1x-check/pom.xml | 2 +- server/java/codegen-kotlin/pom.xml | 2 +- server/java/codegen-mustache/pom.xml | 2 +- server/java/codegen-plantuml/pom.xml | 2 +- server/java/codegen-spring/pom.xml | 2 +- server/java/core-spring/pom.xml | 2 +- server/java/integration-tests-kotlin/pom.xml | 2 +- server/java/integration-tests/pom.xml | 2 +- server/java/maven-plugin/pom.xml | 2 +- server/java/metadata-ktx/pom.xml | 2 +- server/java/metadata/pom.xml | 2 +- server/java/om/pom.xml | 2 +- server/java/omdb-ktx/pom.xml | 2 +- server/java/omdb/pom.xml | 2 +- server/java/pom.xml | 2 +- server/java/render/pom.xml | 2 +- server/java/spring-boot-starter/pom.xml | 2 +- server/python/pyproject.toml | 2 +- server/python/uv.lock | 2 +- 25 files changed, 41 insertions(+), 41 deletions(-) diff --git a/docs/llms/llms-full.txt b/docs/llms/llms-full.txt index 00b6b7f782..8a6b301586 100644 --- a/docs/llms/llms-full.txt +++ b/docs/llms/llms-full.txt @@ -1,6 +1,6 @@ # MetaObjects -- Full Reference Corpus -> Coding agents get context — rules files, memories, MCP servers — and context is advisory: nothing fails when the code stops matching it. MetaObjects gives your agent one typed model of your application — data, API, UI, prompt payloads, and what the software is supposed to do — generates each layer's code from it in TypeScript, Java, Kotlin, C# and Python with no proprietary runtime in the output, and fails your build when generated code, a prompt, or a claimed capability drifts from that model. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.2` on npm and `8.2.2` on Maven Central. +> Coding agents get context — rules files, memories, MCP servers — and context is advisory: nothing fails when the code stops matching it. MetaObjects gives your agent one typed model of your application — data, API, UI, prompt payloads, and what the software is supposed to do — generates each layer's code from it in TypeScript, Java, Kotlin, C# and Python with no proprietary runtime in the output, and fails your build when generated code, a prompt, or a claimed capability drifts from that model. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.3` on npm and `8.2.3` on Maven Central. **Note for AI assistants:** This file is the concatenated reference material for MetaObjects, intended to be loaded as LLM context. For the short index, see [llms.txt](https://metaobjects.dev/llms.txt). For the canonical spec and source, see the [GitHub repo](https://github.com/metaobjectsdev/metaobjects). When this file is out of date relative to the GitHub source, the GitHub source wins. @@ -39,7 +39,7 @@ If you are an AI assistant helping someone adopt MetaObjects, do this **first** 1. **Install the port's package:** - TypeScript / Node: `npm i -D @metaobjectsdev/cli @metaobjectsdev/codegen-ts @metaobjectsdev/metadata typescript @types/better-sqlite3`, then `npm i @metaobjectsdev/runtime-ts drizzle-orm zod fastify better-sqlite3` (SQLite; use `pg` and `@types/pg` for Postgres). The generated files import `drizzle-orm`, `zod`, `fastify` and a driver, and `npm` does not add them for you. - - Java / Kotlin: add `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.2`. + - Java / Kotlin: add `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.3`. - Python: `pip install metaobjects` - C#: install the MetaObjects .NET tool (invoked as `dotnet meta`). 2. **Run `meta init`** (the Node `meta` CLI). It works in any project that has Node — including a JVM or Python project with a TypeScript frontend. It scaffolds a slim always-on `.metaobjects/AGENTS.md` + `.metaobjects/CLAUDE.md` (auto-wired via an `@.metaobjects/AGENTS.md` import line into the project's root `CLAUDE.md`/`AGENTS.md`, so it loads automatically) plus six `metaobjects-*` Claude Code skills under `.claude/skills/`, carrying only the project's language reference fragments. Re-run `meta init --refresh-docs` to update the agent docs after a CLI upgrade. (The Node `meta` CLI is the single agent-context scaffolder for every backend, by design — ADR-0033; the JVM/Python/C# CLIs deliberately redirect to it. For a non-Node project, scaffold just the agent context with `npx meta agent-docs --server `.) @@ -127,11 +127,11 @@ Today the TypeScript toolchain publishes and TypeScript and Python projects cons | Language | Status | Notes | |---|---|---| -| TypeScript | Reference implementation, npm `1.2.2` | All six pillars, and the only port that prints the requirements authoring lint and publishes shared models. 2500+ tests passing. Owns the canonical schema-migration toolchain used by every port (ADR-0015). Bun-first dev. | -| Java | Maven Central `8.2.2` | Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx. Fully green across all conformance corpora. | -| Kotlin | Maven Central `8.2.2` | KotlinPoet codegen + Exposed runtime + `metadata-ktx` facade. Ships via the Java reactor. | -| C# | NuGet `1.2.2` (.NET tool) | Loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. `dotnet meta` tool. | -| Python | PyPI `1.2.1` | Loader + serializer + render + verify + codegen + `ObjectManager` runtime. Fully green across all corpora. | +| TypeScript | Reference implementation, npm `1.2.3` | All six pillars, and the only port that prints the requirements authoring lint and publishes shared models. 2500+ tests passing. Owns the canonical schema-migration toolchain used by every port (ADR-0015). Bun-first dev. | +| Java | Maven Central `8.2.3` | Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx. Fully green across all conformance corpora. | +| Kotlin | Maven Central `8.2.3` | KotlinPoet codegen + Exposed runtime + `metadata-ktx` facade. Ships via the Java reactor. | +| C# | NuGet `1.2.3` (.NET tool) | Loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. `dotnet meta` tool. | +| Python | PyPI `1.2.3` | Loader + serializer + render + verify + codegen + `ObjectManager` runtime. Fully green across all corpora. | Conformance fixtures live at [`fixtures/`](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures). Every port runs the shared corpus byte-identically: metamodel (`conformance/`, 314 fixtures), render, persistence (Testcontainers Postgres, with an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), api-contract (core REST contract + filter operators, plus TPH / M:N / jsonb / write-through and the other sub-corpora — two lanes: a reference server AND each port's generated API booted over HTTP), registry (byte-matched metamodel-vocabulary manifest, live + green in all five ports), `codegen-skip-conformance/` (when `gen` may skip a run, ADR-0062), and yaml/verify. @@ -184,7 +184,7 @@ Universal web client (`client/web/packages/`): `@metaobjectsdev/runtime-web`, `@ ## Java / Kotlin Maven coordinates -All published to Maven Central under `com.metaobjects:*` at `8.2.2`: +All published to Maven Central under `com.metaobjects:*` at `8.2.3`: - `metaobjects-metadata`, `metaobjects-metadata-ktx` - `metaobjects-codegen-base`, `metaobjects-codegen-mustache`, `metaobjects-codegen-spring`, `metaobjects-codegen-kotlin`, `metaobjects-codegen-plantuml` @@ -221,7 +221,7 @@ Project marker directory: `.metaobjects/`. ## Quickstart (Java / Kotlin) -Add the Maven coordinates above at `8.2.2`. Run codegen with `mvn metaobjects:generate` and codegen-drift checks with `mvn metaobjects:verify`. Configure generators (including Kotlin generators, which run through the same goal) on the `metaobjects-maven-plugin`. See [`server/java/`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java) and [`server/java/codegen-kotlin/README.md`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java/codegen-kotlin). +Add the Maven coordinates above at `8.2.3`. Run codegen with `mvn metaobjects:generate` and codegen-drift checks with `mvn metaobjects:verify`. Configure generators (including Kotlin generators, which run through the same goal) on the `metaobjects-maven-plugin`. See [`server/java/`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java) and [`server/java/codegen-kotlin/README.md`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java/codegen-kotlin). --- diff --git a/docs/llms/llms.txt b/docs/llms/llms.txt index cd6e4a15ec..c7710ef0bf 100644 --- a/docs/llms/llms.txt +++ b/docs/llms/llms.txt @@ -1,6 +1,6 @@ # MetaObjects -> MetaObjects gives your coding agent one typed model of your application: data, API, UI, prompt payloads, and what the software is supposed to do. It generates each layer's code from that model in TypeScript, Java, Kotlin, C# and Python, with no proprietary runtime in the output. Your build fails when generated code, a prompt or a claimed capability stops matching the model. Rules files and memories are only advice, because nothing fails when the code drifts from them. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.2` on npm and `8.2.2` on Maven Central. +> MetaObjects gives your coding agent one typed model of your application: data, API, UI, prompt payloads, and what the software is supposed to do. It generates each layer's code from that model in TypeScript, Java, Kotlin, C# and Python, with no proprietary runtime in the output. Your build fails when generated code, a prompt or a claimed capability stops matching the model. Rules files and memories are only advice, because nothing fails when the code drifts from them. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.3` on npm and `8.2.3` on Maven Central. **One typed model of your app** — data, API, UI, prompt payloads, and what it is supposed to do — that your agent reads and writes. Two things happen to it. @@ -26,7 +26,7 @@ If you are an AI assistant helping someone adopt MetaObjects in their project, d 1. **Install the port's package** for the project's stack: - **TypeScript / Node**: `npm i -D @metaobjectsdev/cli @metaobjectsdev/codegen-ts @metaobjectsdev/metadata typescript @types/better-sqlite3`, then `npm i @metaobjectsdev/runtime-ts drizzle-orm zod fastify better-sqlite3` (SQLite; use `pg` and `@types/pg` for Postgres). The generated files import `drizzle-orm`, `zod`, `fastify` and a driver, and `npm` does not add them for you. - - **Java / Kotlin**: add the Maven dependencies `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and the `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.2`. + - **Java / Kotlin**: add the Maven dependencies `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and the `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.3`. - **Python**: `pip install metaobjects` - **C#**: install the MetaObjects .NET tool (`dotnet tool install` the MetaObjects CLI tool; invoked as `dotnet meta`). @@ -65,10 +65,10 @@ MetaObjects pillars are capabilities of one metadata model, not separate product **Sharing a model across your own projects** — today the TypeScript toolchain publishes and TypeScript and Python projects consume, from an installed npm or Python package or over a `path` dependency (a sibling checkout or submodule); Java, Kotlin and C# arrive in Phase 2. One project publishes part of its model with the `sharedModelFile()` generator; another declares it under `dependencies` in `.metaobjects/config.json`, runs `meta deps sync` to commit a hash-locked snapshot, and builds on it with `extends` and references. When the publisher's model moves, `meta verify --deps` reports it instead of two copies drifting apart. -## Implementations (npm `1.2.2` / Maven Central `8.2.2`) +## Implementations (npm `1.2.3` / Maven Central `8.2.3`) -- [TypeScript](https://github.com/metaobjectsdev/metaobjects/tree/main/server/typescript): the reference implementation. Published to npm at `1.2.2` across 14 `@metaobjectsdev/*` packages on the `latest` tag. 2500+ tests passing across the workspace. Bun-first dev workflow. Owns the canonical schema-migration toolchain used by every port (ADR-0015). -- [Java](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java): 14 publishable Maven modules under `com.metaobjects:*` at `8.2.2` on Maven Central (15 artifacts with the parent POM). Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx, full FR-003 + FR-006 + FR-010/011 + FR-018 + FR5 family. Fully green across all conformance corpora. +- [TypeScript](https://github.com/metaobjectsdev/metaobjects/tree/main/server/typescript): the reference implementation. Published to npm at `1.2.3` across 14 `@metaobjectsdev/*` packages on the `latest` tag. 2500+ tests passing across the workspace. Bun-first dev workflow. Owns the canonical schema-migration toolchain used by every port (ADR-0015). +- [Java](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java): 14 publishable Maven modules under `com.metaobjects:*` at `8.2.3` on Maven Central (15 artifacts with the parent POM). Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx, full FR-003 + FR-006 + FR-010/011 + FR-018 + FR5 family. Fully green across all conformance corpora. - [Kotlin](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java/codegen-kotlin): a Kotlin codegen pipeline on KotlinPoet plus `metadata-ktx` — a Kotlin facade over the Java MetaObjects core. Ships via the Java reactor (`metaobjects-metadata-ktx`, `metaobjects-codegen-kotlin`). Persistence-conformance runs against Testcontainers Postgres through Exposed. - [C#](https://github.com/metaobjectsdev/metaobjects/tree/main/server/csharp): loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. The `dotnet meta` tool ships `gen` and the codegen-side `verify` subverbs (`--codegen`, `--templates`); schema migration is Node `meta` only (ADR-0015). - [Python](https://github.com/metaobjectsdev/metaobjects/tree/main/server/python): loader + canonical serializer + conformance + render + verify + codegen + an `ObjectManager` runtime layer. The `metaobjects` console-script ships `gen` and codegen-side `verify`. Fully green across all conformance corpora. @@ -82,7 +82,7 @@ MetaObjects deliberately does **not** ship one universal binary. Schema operatio - Codegen is **opt-in**: no port ships a default generator suite, `meta init` scaffolds `generators: []`, and `meta gen --list` is the catalog (`--probe` reports how many files each generator would emit for your model) - Project marker directory: `.metaobjects/` - Install (TypeScript reference): `npm install -D @metaobjectsdev/cli` (or `bun add @metaobjectsdev/cli`) -- Install (Java): `com.metaobjectsmetaobjects-metadata8.2.2` plus per-concern artifacts (`metaobjects-codegen-spring`, `metaobjects-omdb`, `metaobjects-maven-plugin`, etc.) +- Install (Java): `com.metaobjectsmetaobjects-metadata8.2.3` plus per-concern artifacts (`metaobjects-codegen-spring`, `metaobjects-omdb`, `metaobjects-maven-plugin`, etc.) - Install (Kotlin): same Maven coordinates — add `metaobjects-metadata-ktx` and `metaobjects-codegen-kotlin` to a JVM/Kotlin project. - Install (Python): `pip install metaobjects` - Install (C#): the MetaObjects .NET tool, invoked as `dotnet meta`. @@ -128,7 +128,7 @@ Universal web-client under `client/web/packages/`: ## Java / Kotlin Maven coordinates -All published to Maven Central under `com.metaobjects:*` at `8.2.2`: +All published to Maven Central under `com.metaobjects:*` at `8.2.3`: - `metaobjects-metadata`, `metaobjects-metadata-ktx` - `metaobjects-codegen-base`, `metaobjects-codegen-mustache`, `metaobjects-codegen-spring`, `metaobjects-codegen-kotlin`, `metaobjects-codegen-plantuml` diff --git a/examples/showcase/jvm/pom.xml b/examples/showcase/jvm/pom.xml index 6dcd77e740..feeee77444 100644 --- a/examples/showcase/jvm/pom.xml +++ b/examples/showcase/jvm/pom.xml @@ -23,7 +23,7 @@ - 8.2.2 + 8.2.3 UTF-8 diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 815a35e70c..7e5e79ed05 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -1,9 +1,9 @@ { "registries": { "npm": "1.2.3", - "pypi": "1.2.1", - "nuget": "1.2.2", - "maven": "8.2.2", + "pypi": "1.2.3", + "nuget": "1.2.3", + "maven": "8.2.3", "metamodel": "1.2" }, "counts": { diff --git a/server/csharp/Directory.Build.props b/server/csharp/Directory.Build.props index 9c9c41a6c0..c43af22128 100644 --- a/server/csharp/Directory.Build.props +++ b/server/csharp/Directory.Build.props @@ -8,7 +8,7 @@ --> - 1.2.2 + 1.2.3 Doug Mealing Doug Mealing LLC MetaObjects diff --git a/server/java/codegen-base/pom.xml b/server/java/codegen-base/pom.xml index 8eb2cdebab..4653a907c3 100644 --- a/server/java/codegen-base/pom.xml +++ b/server/java/codegen-base/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-codegen-base diff --git a/server/java/codegen-kotlin-exposed1x-check/pom.xml b/server/java/codegen-kotlin-exposed1x-check/pom.xml index 32c9755f0b..ef652ab428 100644 --- a/server/java/codegen-kotlin-exposed1x-check/pom.xml +++ b/server/java/codegen-kotlin-exposed1x-check/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-codegen-kotlin-exposed1x-check diff --git a/server/java/codegen-kotlin/pom.xml b/server/java/codegen-kotlin/pom.xml index b7f50c2b59..3912333309 100644 --- a/server/java/codegen-kotlin/pom.xml +++ b/server/java/codegen-kotlin/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-codegen-kotlin diff --git a/server/java/codegen-mustache/pom.xml b/server/java/codegen-mustache/pom.xml index 6def4a6c9a..9b69f69af1 100644 --- a/server/java/codegen-mustache/pom.xml +++ b/server/java/codegen-mustache/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-codegen-mustache diff --git a/server/java/codegen-plantuml/pom.xml b/server/java/codegen-plantuml/pom.xml index 2d71c32ee1..c03f2f0c92 100644 --- a/server/java/codegen-plantuml/pom.xml +++ b/server/java/codegen-plantuml/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-codegen-plantuml diff --git a/server/java/codegen-spring/pom.xml b/server/java/codegen-spring/pom.xml index 8a303818cc..6f482d7f12 100644 --- a/server/java/codegen-spring/pom.xml +++ b/server/java/codegen-spring/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-codegen-spring diff --git a/server/java/core-spring/pom.xml b/server/java/core-spring/pom.xml index 8799bf12f0..bc199f2862 100644 --- a/server/java/core-spring/pom.xml +++ b/server/java/core-spring/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-core-spring diff --git a/server/java/integration-tests-kotlin/pom.xml b/server/java/integration-tests-kotlin/pom.xml index cc386d3413..69d3b1b459 100644 --- a/server/java/integration-tests-kotlin/pom.xml +++ b/server/java/integration-tests-kotlin/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-integration-tests-kotlin diff --git a/server/java/integration-tests/pom.xml b/server/java/integration-tests/pom.xml index 314dc75ed1..a674c22378 100644 --- a/server/java/integration-tests/pom.xml +++ b/server/java/integration-tests/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-integration-tests diff --git a/server/java/maven-plugin/pom.xml b/server/java/maven-plugin/pom.xml index 56bdbcc152..9e30ba63e8 100644 --- a/server/java/maven-plugin/pom.xml +++ b/server/java/maven-plugin/pom.xml @@ -2,7 +2,7 @@ metaobjects com.metaobjects - 8.2.2 + 8.2.3 4.0.0 diff --git a/server/java/metadata-ktx/pom.xml b/server/java/metadata-ktx/pom.xml index 7c16b99371..037f734e70 100644 --- a/server/java/metadata-ktx/pom.xml +++ b/server/java/metadata-ktx/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-metadata-ktx diff --git a/server/java/metadata/pom.xml b/server/java/metadata/pom.xml index c2716046fd..da31aac851 100644 --- a/server/java/metadata/pom.xml +++ b/server/java/metadata/pom.xml @@ -4,7 +4,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-metadata diff --git a/server/java/om/pom.xml b/server/java/om/pom.xml index c33e76ccc6..bb8ed46afb 100644 --- a/server/java/om/pom.xml +++ b/server/java/om/pom.xml @@ -5,7 +5,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-om diff --git a/server/java/omdb-ktx/pom.xml b/server/java/omdb-ktx/pom.xml index 07d9832f74..ac9e51dab4 100644 --- a/server/java/omdb-ktx/pom.xml +++ b/server/java/omdb-ktx/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-omdb-ktx diff --git a/server/java/omdb/pom.xml b/server/java/omdb/pom.xml index 4744ad6944..8ab09b2aa4 100644 --- a/server/java/omdb/pom.xml +++ b/server/java/omdb/pom.xml @@ -4,7 +4,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-omdb diff --git a/server/java/pom.xml b/server/java/pom.xml index 29ddd9fd55..ecfd109bd1 100644 --- a/server/java/pom.xml +++ b/server/java/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.metaobjects metaobjects - 8.2.2 + 8.2.3 pom MetaObjects Core Universal metadata-driven development platform diff --git a/server/java/render/pom.xml b/server/java/render/pom.xml index a62d2e77cc..befaa35914 100644 --- a/server/java/render/pom.xml +++ b/server/java/render/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-render diff --git a/server/java/spring-boot-starter/pom.xml b/server/java/spring-boot-starter/pom.xml index 62abe5f9ee..65fd33a791 100644 --- a/server/java/spring-boot-starter/pom.xml +++ b/server/java/spring-boot-starter/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.2 + 8.2.3 metaobjects-spring-boot-starter diff --git a/server/python/pyproject.toml b/server/python/pyproject.toml index 2366d3f4bc..a71eb1984a 100644 --- a/server/python/pyproject.toml +++ b/server/python/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "metaobjects" -version = "1.2.1" +version = "1.2.3" description = "Cross-language metadata standard: declare typed entities once, generate idiomatic drift-checked code across languages — Python port." readme = "README.md" requires-python = ">=3.11" diff --git a/server/python/uv.lock b/server/python/uv.lock index a3b21881ca..ff78e8229d 100644 --- a/server/python/uv.lock +++ b/server/python/uv.lock @@ -399,7 +399,7 @@ wheels = [ [[package]] name = "metaobjects" -version = "1.2.1" +version = "1.2.3" source = { editable = "." } dependencies = [ { name = "pyyaml" }, From dc3a0819a9f5fb20a9a62bf4b8a49178f449997a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 16:14:07 -0500 Subject: [PATCH 253/267] fix(csharp): the gen-skip key covers the .csproj the context's assembly name is read from With no GenConfig.ContextAssemblyName, the DbContext generator names its design-time services reference after the one .csproj in --out or the nearest directory above it. That file can lie outside codegen/ and .metaobjects/, so a renamed assembly left the key unchanged and gen skipped over a stale reference. The identity now carries a `project` entry for that file (or "missing" when there is none), and the format version moves to 4. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- .../GenFingerprintProjectFileTests.cs | 48 +++++++++++++++++++ .../MetaObjects.Codegen/GenFingerprint.cs | 17 ++++++- 3 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c87a36663..0f027cc4c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -601,7 +601,8 @@ vocabulary; upgrade every port together. cannot show the line is unnecessary (it looks for `ModelSnapshot.cs` in the context's project, or a migrations project that already carries the line). Without the line a changed start still scaffolds as RESTART, which is the accepted residual risk. An adopter's own differ - is kept: the services wrap it. + is kept: the services wrap it. The `.csproj` the name is read from is an input of `dotnet meta + gen`'s skip key (ADR-0062), so renaming the assembly renders again. - **C#, upgrade note: a self-hosted codegen runner sets `GenConfig.Dialect`.** `@sequenceStart` and the design-time services are emitted only when the dialect is `postgres`. `CodegenCli` reads it from `.metaobjects/config.json` `migrate.dialect`; a runner that builds its own `GenConfig` must diff --git a/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs new file mode 100644 index 0000000000..c66da1f6bf --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs @@ -0,0 +1,48 @@ +// ADR-0062: with no GenConfig.ContextAssemblyName, the DbContext generator names its design-time +// services reference after the .csproj in --out or above it. That file is an input of the run, so +// the key moves when it does, even though it lies outside codegen/ and .metaobjects/. + +#nullable enable + +using MetaObjects.Codegen; +using Xunit; + +public sealed class GenFingerprintProjectFileTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "meta-projfile-" + Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } + + private string Key() => GenFingerprint.Key(GenFingerprint.IdentityEntries( + _root, _root, new GenFingerprint.Options { OutDir = Path.Combine("app", "Generated") }, [])); + + private static string Csproj(string assembly) => + $"{assembly}\n"; + + [Fact] + public void Renaming_the_assembly_of_the_output_project_changes_the_key() + { + Directory.CreateDirectory(Path.Combine(_root, "app", "Generated")); + File.WriteAllText(Path.Combine(_root, "app", "App.csproj"), Csproj("First")); + var first = Key(); + Assert.Equal(first, Key()); + + File.WriteAllText(Path.Combine(_root, "app", "App.csproj"), Csproj("Second")); + + Assert.NotEqual(first, Key()); + } + + [Fact] + public void A_project_created_after_a_run_without_one_changes_the_key() + { + Directory.CreateDirectory(Path.Combine(_root, "app", "Generated")); + var without = Key(); + + File.WriteAllText(Path.Combine(_root, "app", "App.csproj"), Csproj("App")); + + Assert.NotEqual(without, Key()); + } +} diff --git a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs index fc379cb9fd..09a1663978 100644 --- a/server/csharp/MetaObjects.Codegen/GenFingerprint.cs +++ b/server/csharp/MetaObjects.Codegen/GenFingerprint.cs @@ -18,6 +18,9 @@ // lock and snapshots), `.gen-state` aside // flag the output-changing flags: --out, --namespace, --generators, // --template-root, --template-spec, --emit-abstract-shapes, --strict, baseline +// project the one .csproj in --out or the nearest directory above it, which names +// the assembly of the generated context's design-time services reference +// when GenConfig.ContextAssemblyName is unset (or "missing" when there is none) // template every file under prompts/, templates/, --template-root, and the template spec // extra every path a generator declared in IGenerator.ExtraInputs // format this format's version @@ -37,7 +40,7 @@ namespace MetaObjects.Codegen; public static class GenFingerprint { /// Bumped when an entry kind is added or its meaning changes, so an old file never matches. - public const int FormatVersion = 3; + public const int FormatVersion = 4; /// The stored key's file name inside .metaobjects/.gen-state/. One per port. public const string FileName = ".fingerprint-csharp.json"; @@ -167,6 +170,18 @@ public static IReadOnlyList IdentityEntries( Flag("strict", o.Strict ? "true" : "false"); Flag("baseline", o.Baseline); + // The project the output is compiled into. With no GenConfig.ContextAssemblyName the DbContext + // generator reads its assembly name from this file (CSharpProjectAssembly), which may lie + // outside codegen/ and .metaobjects/: renaming the assembly must render again. + if (o.OutDir is not null) + { + var outFull = Path.GetFullPath(Path.Combine(cwd, o.OutDir)); + if (CSharpProjectAssembly.FindProject(outFull) is { } csproj) + entries.AddRange(FileEntries("project", projectRoot, [csproj])); + else + entries.Add(new Entry("project", Rel(projectRoot, outFull), "missing")); + } + // The project's own config: the nearest `.metaobjects/` at or above the project. for (var dir = new DirectoryInfo(Path.GetFullPath(projectRoot)); dir is not null; dir = dir.Parent) { From 8e9ac2311001b82b322970e9684df66b9404317e Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 16:14:10 -0500 Subject: [PATCH 254/267] docs(conformance): the metamodel corpus counts 475 fixtures in the table and the arithmetic Co-Authored-By: Claude Opus 5.5 --- docs/CONFORMANCE.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 6fd5a80401..833c13e04a 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 463 | ✓ | ✓ but the rc.19 fixtures — the two reverse-hop fixtures (`origin-reverse-reference-hop`, `error-origin-reverse-hop-ambiguous`; bug R-walk), `origin-passthrough-flattened-member` and `reference-flattened-member` (bug G6), `projection-filter-unprojected-base-field`, `projection-filter-joined-path` and `error-projection-filter-path-to-many` (bug G7), `projection-extends-abstract-projection`, `projection-extends-filtered-projection` and `error-projection-extends-filter-sql-body` (bug G13; the last two from the fix round's C1), `object-collection-name` (R57), `report-dimension-required-by-model` (R62; its `expected-report-required.json` holds the model-derived `required` every port's report shape must give — Java, Kotlin and Python still derive it from the INNER-join rule), and the Tier 2 view vocabulary (R58: `entity-derived-league-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `origin-filter-relative-now`, `projection-filter-relative-now`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`) — not run in this port; expected red until [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | inherits via `metadata-ktx` (the same) | ✓ | ✓ but the same, #544–#549 | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 475 | ✓ | ✓ but the rc.19 fixtures — the two reverse-hop fixtures (`origin-reverse-reference-hop`, `error-origin-reverse-hop-ambiguous`; bug R-walk), `origin-passthrough-flattened-member` and `reference-flattened-member` (bug G6), `projection-filter-unprojected-base-field`, `projection-filter-joined-path` and `error-projection-filter-path-to-many` (bug G7), `projection-extends-abstract-projection`, `projection-extends-filtered-projection` and `error-projection-extends-filter-sql-body` (bug G13; the last two from the fix round's C1), `object-collection-name` (R57), `report-dimension-required-by-model` (R62; its `expected-report-required.json` holds the model-derived `required` every port's report shape must give — Java, Kotlin and Python still derive it from the INNER-join rule), and the Tier 2 view vocabulary (R58: `entity-derived-league-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `origin-filter-relative-now`, `projection-filter-relative-now`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`) — not run in this port; expected red until [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | inherits via `metadata-ktx` (the same) | ✓ | ✓ but the same, #544–#549 | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | @@ -727,7 +727,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) -The fixtures in the nine corpora mapped above (metamodel 460 + yaml 16 + verify 45 +The fixtures in the nine corpora mapped above (metamodel 475 + yaml 16 + verify 45 + render 18 + persistence 59 + api-contract 122 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining From 3610a432e429949a84f5193ce53ede4ab4918321 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 16:43:45 -0500 Subject: [PATCH 255/267] fix(fixtures): the canonical Postgres schema carries the view hash of its renamed predicate The Coupon/Permit rename changed v_auths_by_kind's WHERE clause without regenerating the artifact, so its COMMENT ON VIEW still held the old body's hash and the schema-artifact drift test failed. Regenerated with `bun run gen:schema`; only that comment moves. Co-Authored-By: Claude Opus 5.5 --- fixtures/persistence-conformance/canonical/schema.postgres.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fixtures/persistence-conformance/canonical/schema.postgres.sql b/fixtures/persistence-conformance/canonical/schema.postgres.sql index 405005596a..5b5719575e 100644 --- a/fixtures/persistence-conformance/canonical/schema.postgres.sql +++ b/fixtures/persistence-conformance/canonical/schema.postgres.sql @@ -474,7 +474,7 @@ CREATE VIEW "v_auths_by_kind" AS FROM "public"."auths" a WHERE a."type" <> 'Permit' GROUP BY a."type"; -COMMENT ON VIEW "v_auths_by_kind" IS 'metaobjects:v1:sha256:1c8464289f36afaa7132f22c64ba8e5c5d529d4866cc27bc57b01b148dbbffbd'; +COMMENT ON VIEW "v_auths_by_kind" IS 'metaobjects:v1:sha256:30dd6efe1ae75fef8c329affdeab88614fcc1965a43c36b6e3a5d246b7df3980'; CREATE VIEW "v_gadget_events_by_label" AS SELECT From fe1da9b6d4acaa47da4f1abe5176cf3b990ee794 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 17:09:54 -0500 Subject: [PATCH 256/267] test(cli): the refused-orphan gen-skip case reads the crm module from its package directory The default TypeScript outputLayout is "package", so the case's Customer module is written to generated/crm/Customer.ts, not to the flat path the test was written against. Co-Authored-By: Claude Opus 5.5 --- .../typescript/packages/cli/test/gen-skip-conformance.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts index 37bc1edb10..fd59e79f2f 100644 --- a/server/typescript/packages/cli/test/gen-skip-conformance.test.ts +++ b/server/typescript/packages/cli/test/gen-skip-conformance.test.ts @@ -329,7 +329,8 @@ describe("an orphan the sweep refuses to delete (ADR-0062)", () => { const p = makeProject(); expect(await gen(p)).toBe(0); expect(existsSync(stateFile(p))).toBe(true); - const orphan = join(p.root, "generated", "Customer.ts"); + // The default outputLayout is "package": the crm package's module lives under its directory. + const orphan = join(p.root, "generated", "crm", "Customer.ts"); expect(existsSync(orphan)).toBe(true); append(orphan, "// mine\n"); unlinkSync(join(p.root, "metaobjects", "meta.crm.json")); From 1d8cce5f657d802722b414d974bee1ea55197878 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 17:28:49 -0500 Subject: [PATCH 257/267] fix(csharp): verify --codegen renders with the context assembly name gen read The drift render moves --out to a virtual root. With no GenConfig.ContextAssemblyName the name is read from the .csproj in or above --out, and the virtual root has none, so the render left out the DesignTimeServicesReference line gen wrote and reported DesignTimeServices.g.cs as drift on every rendering verify, which CI always does. The name is now resolved against the real --out before the directory moves. The new IdentityStartVerifyTests case (a .csproj above --out, Postgres, gen then verify --codegen --full) reports drift without the fix and passes with it. The existing case there also passes --full now, so it exercises the render rather than the stored key. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++++ .../IdentityStartVerifyTests.cs | 27 ++++++++++++++++++- .../MetaObjects.Codegen/CodegenDrift.cs | 9 ++++++- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f027cc4c4..dde6778288 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -710,6 +710,14 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, C#: `verify --codegen` renders the design-time services file `gen` wrote.** With no + `GenConfig.ContextAssemblyName`, `gen` reads the context's assembly name from the `.csproj` in or + above `--out` and writes `[assembly: DesignTimeServicesReference(...)]` into + `DesignTimeServices.g.cs`. The drift render ran under a temporary directory with no + project, left that line out, and reported the file as drift on every rendering `verify` (always + in CI) for a Postgres project laid out that way. The render now uses the name `gen` resolved. + Locally the stored-key answer (ADR-0062) hid it; `verify --codegen --full` showed it. + - **Fix, C#: a query can test an optional value-mapped enum against a list (rc.22).** `DbContextGenerator` handed a scalar `@intValueMap` or `@stringValueMap` enum's two conversion lambdas straight to `HasConversion(...)`, so EF typed the converter on the property: an optional diff --git a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs index 99205d8cad..b2154a917d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/IdentityStartVerifyTests.cs @@ -50,7 +50,32 @@ public void Verify_reads_the_dialect_gen_read() var (gen, genText) = Run("gen", Meta, "--out", Out, "--namespace", "Acme.Generated"); Assert.True(gen == 0, genText); Assert.True(File.Exists(Path.Combine(Out, "AppDbContextDesignTimeServices.g.cs")), genText); - var (verify, verifyText) = Run("verify", "--codegen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + var (verify, verifyText) = Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); + Assert.True(verify == 0, verifyText); + } + finally + { + Directory.SetCurrentDirectory(cwd); + } + } + + // The assembly name gen reads from the .csproj above --out is the one the drift render uses: a + // render under a temporary directory with no project would leave the reference line out and + // report the design-time services file as drift on every CI run. + [Fact] + public void Verify_renders_the_design_time_reference_gen_read_from_the_project() + { + File.WriteAllText(Path.Combine(_root, "Acme.App.csproj"), + "Acme.App\n"); + var cwd = Directory.GetCurrentDirectory(); + Directory.SetCurrentDirectory(_root); + try + { + var (gen, genText) = Run("gen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + Assert.True(gen == 0, genText); + var services = File.ReadAllText(Path.Combine(Out, "AppDbContextDesignTimeServices.g.cs")); + Assert.Contains("DesignTimeServicesReference(\"Acme.Generated.AppDbContextDesignTimeServices, Acme.App\"", services); + var (verify, verifyText) = Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); Assert.True(verify == 0, verifyText); } finally diff --git a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs index 0b86b0fcc4..28308224b1 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenDrift.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenDrift.cs @@ -88,7 +88,14 @@ public static Result Compute(GenConfig config, MetaRoot root, IReadOnlyList Path.Combine(virtualRoot, i.ToString())).ToList(); // No manifest and no sweep for the throwaway regen: it records nothing and deletes nothing. - var tempConfig = config with { OutDir = temps[0], GenStateDir = null, ProjectRoot = null, SweepOrphans = false }; + // The context's assembly name is pinned before --out moves: unset, it is read from the + // .csproj in or above --out, and the virtual root has none, so the render would leave the + // DesignTimeServicesReference line gen wrote out and report the file as drift. + var tempConfig = config with + { + OutDir = temps[0], ContextAssemblyName = config.ContextAssemblyName, + GenStateDir = null, ProjectRoot = null, SweepOrphans = false, + }; var rendered = new Dictionary(StringComparer.Ordinal); CodegenRunner.RunResult regen; try From 3dd27f856565cdd18784f63a1ad5921c6697a17d Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 17:39:32 -0500 Subject: [PATCH 258/267] test(csharp): every verify --codegen in the C# tests passes --full Since ADR-0062 a local verify after an unchanged gen may answer "no drift" from the stored key without rendering, so these tests stopped exercising the in-memory render they were written for; a render-path regression would surface only in CI. Each now passes --full. The gen-skip conformance tests keep the bare form: the stored-key answer is what they test. With --full the C# suites still pass, so the render path hides no further defect. Co-Authored-By: Claude Opus 5.5 --- .../CodegenNamespaceTests.cs | 8 ++-- .../ColumnNamingFlagTests.cs | 12 +++--- .../DependencyCliTests.cs | 2 +- .../EjectEndToEndTests.cs | 6 +-- .../OneGeneratorListTests.cs | 38 +++++++++---------- .../VerifyAppNamingStrategyTests.cs | 4 +- .../VerifyRequirementsTests.cs | 6 +-- .../WireSettingCliTests.cs | 2 +- .../EnumLengthCliTests.cs | 2 +- .../OrphanSweepTests.cs | 2 +- .../RecipeGeneratorTests.cs | 4 +- .../WrappedTemplateSpecTests.cs | 2 +- 12 files changed, 44 insertions(+), 44 deletions(-) diff --git a/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs b/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs index c593e7271c..cf3c9a3251 100644 --- a/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/CodegenNamespaceTests.cs @@ -71,7 +71,7 @@ public void A_config_namespace_is_used_by_gen_and_a_bare_verify_is_clean() Assert.True(gen.Exit == 0, gen.Output); Assert.Contains("namespace Acme.Blog;", PackageLessEntityFile()); - var verify = Run("verify", "--codegen"); + var verify = Run("verify", "--codegen", "--full"); Assert.True(verify.Exit == 0, verify.Output); } @@ -84,7 +84,7 @@ public void With_no_namespace_it_is_derived_from_the_metadata_package_and_a_bare Assert.True(gen.Exit == 0, gen.Output); Assert.Contains("namespace Acme.Shop;", EntityFile()); - var verify = Run("verify", "--codegen"); + var verify = Run("verify", "--codegen", "--full"); Assert.True(verify.Exit == 0, verify.Output); } @@ -97,7 +97,7 @@ public void With_no_namespace_a_project_with_nothing_to_emit_generates_cleanly() var gen = Run("gen"); Assert.True(gen.Exit == 0, gen.Output); - var verify = Run("verify", "--codegen"); + var verify = Run("verify", "--codegen", "--full"); Assert.True(verify.Exit == 0, verify.Output); } @@ -109,7 +109,7 @@ public void The_flag_wins_over_config_and_output_under_another_namespace_is_drif Assert.Equal(0, Run("gen", "--namespace", "Other.Ns").Exit); Assert.Contains("namespace Other.Ns;", PackageLessEntityFile()); - Assert.Equal(1, Run("verify", "--codegen").Exit); + Assert.Equal(1, Run("verify", "--codegen", "--full").Exit); } [Theory] diff --git a/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs b/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs index c43c791476..e6151b6d23 100644 --- a/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/ColumnNamingFlagTests.cs @@ -143,7 +143,7 @@ public void The_removed_flag_is_refused_on_verify_codegen() Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); var (exit, stdout, stderr) = OwnedRunner.Run( - _tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--column-naming", "literal", "--namespace", "Acme.Generated"); + _tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--column-naming", "literal", "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(2, exit); Assert.Contains("--column-naming was removed in 1.1.0", output); @@ -162,7 +162,7 @@ public void Verify_with_the_wrong_naming_says_the_naming_differs_instead_of_rege Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); WriteConfig("\"columns\": \"literal\""); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -188,7 +188,7 @@ public void Verify_with_another_table_rule_says_the_naming_differs_instead_of_re Assert.Contains("\"OrderItems\"", File.ReadAllText(Path.Combine(outDir, "acme", "OrderItemNames.g.cs"))); WriteConfig(null); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -212,7 +212,7 @@ public void Verify_finds_another_table_rule_when_only_the_entity_generator_runs( Assert.Contains("[Table(\"OrderItems\")]", File.ReadAllText(Path.Combine(outDir, "acme", "OrderItem.g.cs"))); WriteConfig(null); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -231,7 +231,7 @@ public void Verify_finds_a_column_and_table_rule_that_differ_together() Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); WriteConfig(null); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( @@ -248,7 +248,7 @@ public void Real_drift_still_says_regenerate() Assert.Equal(0, OwnedRunner.Run(_tmp, ["entity", "names"], "gen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated").ExitCode); File.AppendAllText(Path.Combine(outDir, "acme", "SubscriberNames.g.cs"), "// edited\n"); - var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + var (exit, stdout, stderr) = OwnedRunner.Run(_tmp, ["entity", "names"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains("Run 'dotnet meta gen' to regenerate", output); diff --git a/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs b/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs index cb98d46aff..c01575480e 100644 --- a/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/DependencyCliTests.cs @@ -62,7 +62,7 @@ public void Verify_codegen_regenerates_what_gen_wrote_with_a_dependency() Assert.False(Directory.EnumerateFiles(Path.Combine(_root, "generated"), "*Customer*", SearchOption.AllDirectories).Any(), "an imported entity must not be generated"); - var verify = OwnedRunner.Run(_root, ["entity"], "verify", "--codegen", "--out", "generated", "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_root, ["entity"], "verify", "--codegen", "--full", "--out", "generated", "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, verify.Stdout + verify.Stderr); } diff --git a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs index 610e612cfd..2e277d6a32 100644 --- a/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/EjectEndToEndTests.cs @@ -192,7 +192,7 @@ public void Edited_ejected_copy_changes_gen_output_and_verify_codegen_passes() // 5. `dotnet run --project codegen -- verify --codegen ...` — the committed output // (produced by the SAME edited copy) must read as in sync with a fresh regen. var (verifyExit, verifyOutput) = RunCodegenProject( - "verify", "--codegen", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", + "verify", "--codegen", "--full", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", "entity,names"); Assert.True(verifyExit == 0, $"verify --codegen failed (exit {verifyExit}):\n{verifyOutput}"); Assert.Contains("OK", verifyOutput); @@ -326,7 +326,7 @@ public void Ejected_routes_run_on_the_owned_helper_runtime_with_no_MetaObjects_r // verify --codegen: the owned runtime lives outside --out and is never drift. var (verifyExit, verifyOutput) = RunCodegenProject( - "verify", "--codegen", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); + "verify", "--codegen", "--full", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); Assert.True(verifyExit == 0, $"verify --codegen failed (exit {verifyExit}):\n{verifyOutput}"); // The adopter's fix, made in their own copy. @@ -337,7 +337,7 @@ public void Ejected_routes_run_on_the_owned_helper_runtime_with_no_MetaObjects_r // The same verify stays clean after the edit: the runtime copy is owned code. var (verify2Exit, verify2Output) = RunCodegenProject( - "verify", "--codegen", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); + "verify", "--codegen", "--full", MetadataDir, "--out", OutDir, "--namespace", "Acme.Generated", "--generators", selection); Assert.True(verify2Exit == 0, $"verify --codegen after a runtime edit failed (exit {verify2Exit}):\n{verify2Output}"); // A real web app: generated output + the owned runtime, EF Core + SQLite, and no diff --git a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs index f3fb41aaf5..1b4b57304d 100644 --- a/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/OneGeneratorListTests.cs @@ -135,7 +135,7 @@ public void A_selection_writes_its_entries_as_the_whole_list_does() Assert.True(narrowed.ExitCode == 0, $"exit={narrowed.ExitCode}\nstdout={narrowed.Stdout}\nstderr={narrowed.Stderr}"); Assert.Equal(whole, File.ReadAllText(entity)); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -229,7 +229,7 @@ public void Gen_in_a_project_with_no_generator_list_prints_the_amendment_line() [Fact] public void Verify_codegen_in_a_project_with_no_generator_list_prints_the_amendment_line() { - var (exit, _, stderr) = CliProcess.Run(_tmp, "verify", MetaDir, "--codegen", "--out", OutDir); + var (exit, _, stderr) = CliProcess.Run(_tmp, "verify", MetaDir, "--codegen", "--full", "--out", OutDir); Assert.Equal(2, exit); Assert.Contains(CodegenCli.NoGeneratorList("dotnet meta verify --codegen"), stderr); @@ -362,11 +362,11 @@ public void A_requirement_tests_entry_with_its_own_directory_is_written_and_chec Assert.Equal(["acme/Subscriber.g.cs"], FilesUnder(OutDir)); Assert.Equal(["Requirements_acme_Tests.g.cs", "Requirements_acme_Witnesses.g.cs"], FilesUnder(testsDir)); - var clean = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var clean = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(clean.ExitCode == 0, $"exit={clean.ExitCode}\nstdout={clean.Stdout}\nstderr={clean.Stderr}"); File.AppendAllText(Path.Combine(testsDir, "Requirements_acme_Tests.g.cs"), "// edited\n"); - var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.Equal(1, drift.ExitCode); Assert.Contains("Requirements_acme_Tests.g.cs", drift.Stderr); } @@ -385,11 +385,11 @@ public void A_configured_out_dir_is_where_gen_writes_and_verify_checks_and_out_o Assert.True(gen.ExitCode == 0, $"exit={gen.ExitCode}\nstdout={gen.Stdout}\nstderr={gen.Stderr}"); Assert.Equal(["acme/Subscriber.g.cs"], FilesUnder(OutDir)); - var clean = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--namespace", "Acme.Generated"); + var clean = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", "--namespace", "Acme.Generated"); Assert.True(clean.ExitCode == 0, $"exit={clean.ExitCode}\nstdout={clean.Stdout}\nstderr={clean.Stderr}"); File.AppendAllText(Path.Combine(OutDir, "acme", "Subscriber.g.cs"), "// edited\n"); - var drift = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--namespace", "Acme.Generated"); + var drift = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", "--namespace", "Acme.Generated"); Assert.Equal(1, drift.ExitCode); Assert.Contains("Subscriber.g.cs", drift.Stderr); @@ -398,7 +398,7 @@ public void A_configured_out_dir_is_where_gen_writes_and_verify_checks_and_out_o var genOther = OwnedRunner.Run(_tmp, declared, "gen", "--out", other, "--namespace", "Acme.Generated"); Assert.True(genOther.ExitCode == 0, $"exit={genOther.ExitCode}\n{genOther.Stdout}{genOther.Stderr}"); Assert.Equal(["acme/Subscriber.g.cs"], FilesUnder(other)); - var cleanOther = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--out", other, "--namespace", "Acme.Generated"); + var cleanOther = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", "--out", other, "--namespace", "Acme.Generated"); Assert.True(cleanOther.ExitCode == 0, $"exit={cleanOther.ExitCode}\n{cleanOther.Stdout}{cleanOther.Stderr}"); } @@ -419,15 +419,15 @@ public void Verify_narrowed_to_an_entry_with_its_own_directory_does_not_convict_ IReadOnlyList declared = [new EntityGenerator(), new ApiDocsGenerator { OutDir = DocsDir }]; Assert.Equal(0, OwnedRunner.Run(_tmp, declared, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); - var docsOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); + var docsOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); Assert.True(docsOnly.ExitCode == 0, $"exit={docsOnly.ExitCode}\nstdout={docsOnly.Stdout}\nstderr={docsOnly.Stderr}"); - var codeOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); + var codeOnly = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "entity", "--namespace", "Acme.Generated"); Assert.True(codeOnly.ExitCode == 0, $"exit={codeOnly.ExitCode}\nstdout={codeOnly.Stdout}\nstderr={codeOnly.Stderr}"); // What the narrowed run does produce is still checked. File.AppendAllText(Path.Combine(DocsDir, "api", "csharp", "README.md"), "edited\n"); - var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); + var drift = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", "api-docs", "--namespace", "Acme.Generated"); Assert.Equal(1, drift.ExitCode); Assert.Contains("api/csharp/README.md", drift.Stderr); } @@ -439,7 +439,7 @@ public void An_entry_directory_nested_in_out_is_compared_once_as_its_own() IReadOnlyList declared = [new EntityGenerator(), new ApiDocsGenerator { OutDir = nestedDocs }]; Assert.Equal(0, OwnedRunner.Run(_tmp, declared, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -471,7 +471,7 @@ public void A_conventional_template_spec_no_entry_declares_is_refused_and_nothin Assert.Equal(CodegenCli.LegacyTemplateSpec("dotnet meta gen", "template-spec.json"), stderr.Trim()); Assert.Equal(before, ProjectFiles()); - var (verifyExit, _, verifyErr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated"); + var (verifyExit, _, verifyErr) = OwnedRunner.Run(_tmp, ["entity"], "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated"); Assert.Equal(2, verifyExit); Assert.Equal(CodegenCli.LegacyTemplateSpec("dotnet meta verify --codegen", "template-spec.json"), verifyErr.Trim()); } @@ -501,7 +501,7 @@ public void A_declared_template_spec_entry_renders_its_templates_and_verifies_cl Assert.Equal(["Subscriber.summary.txt"], FilesUnder(OutDir)); Assert.Equal("name=Subscriber\n", File.ReadAllText(Path.Combine(OutDir, "Subscriber.summary.txt"))); - var (verifyExit, verifyOut, verifyErr) = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", "--full"); + var (verifyExit, verifyOut, verifyErr) = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated", "--full"); Assert.True(verifyExit == 0, $"exit={verifyExit}\nstdout={verifyOut}\nstderr={verifyErr}"); Assert.Contains("OK (generated output is in sync)", verifyOut); } @@ -533,9 +533,9 @@ public void The_runs_template_root_reaches_a_declared_spec_that_names_none() Assert.True(exit == 0, $"exit={exit}\nstdout={stdout}\nstderr={stderr}"); Assert.Equal("name=Subscriber\n", File.ReadAllText(Path.Combine(OutDir, "Subscriber.summary.txt"))); - var verify = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--template-root", "templates", "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--template-root", "templates", "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); - Assert.Equal(1, OwnedRunner.Run(_tmp, declared, "verify", "--codegen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); + Assert.Equal(1, OwnedRunner.Run(_tmp, declared, "verify", "--codegen", "--full", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); } // ---- a directory gen never had to create is an empty tree, not a missing one --------------- @@ -550,7 +550,7 @@ public void An_entry_directory_that_got_no_files_verifies_clean() Assert.Equal(0, OwnedRunner.Run(_tmp, declared, "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); Assert.False(Directory.Exists(testsDir)); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -568,7 +568,7 @@ public void A_list_of_entries_with_their_own_directories_verifies_clean_in_a_fre Directory.Delete(OutDir); Assert.False(Directory.Exists(testsDir)); - var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, declared, "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); } @@ -578,7 +578,7 @@ public void Verify_codegen_of_a_list_that_declares_nothing_is_clean() { Assert.Equal(0, OwnedRunner.Run(_tmp, Array.Empty(), "gen", MetaDir, "--out", OutDir, "--namespace", "Acme.Generated").ExitCode); - var verify = OwnedRunner.Run(_tmp, Array.Empty(), "verify", MetaDir, "--codegen", "--out", OutDir, "--namespace", "Acme.Generated"); + var verify = OwnedRunner.Run(_tmp, Array.Empty(), "verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--namespace", "Acme.Generated"); Assert.True(verify.ExitCode == 0, $"exit={verify.ExitCode}\nstdout={verify.Stdout}\nstderr={verify.Stderr}"); Assert.Contains("codegen/Generators.cs declares no generators; nothing to check", verify.Stdout); @@ -591,7 +591,7 @@ public void A_blank_generators_selection_is_refused(string command) { string[] args = command == "gen" ? ["gen", MetaDir, "--out", OutDir, "--generators", ""] - : ["verify", MetaDir, "--codegen", "--out", OutDir, "--generators", ""]; + : ["verify", MetaDir, "--codegen", "--full", "--out", OutDir, "--generators", ""]; var (exit, _, stderr) = OwnedRunner.Run(_tmp, ["entity"], args); diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs index 4371a2560c..53af252da9 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyAppNamingStrategyTests.cs @@ -65,7 +65,7 @@ public void Verify_codegen_hands_off_before_it_reads_an_app_naming_strategy() { WriteStandInRunner(); - var (exit, stdout, stderr) = CliProcess.Run(_tmp, "verify", "--codegen", "--out", "gen"); + var (exit, stdout, stderr) = CliProcess.Run(_tmp, "verify", "--codegen", "--full", "--out", "gen"); Assert.Contains("stand-in runner: verify --codegen --out", stdout); Assert.DoesNotContain("acme-app-columns", stderr); @@ -92,7 +92,7 @@ public void A_gate_this_process_runs_refuses_the_app_strategy_cleanly_after_the_ { WriteStandInRunner(); - var (exit, stdout, stderr) = CliProcess.Run(_tmp, ["verify", "--codegen", "--out", "gen", .. gate]); + var (exit, stdout, stderr) = CliProcess.Run(_tmp, ["verify", "--codegen", "--full", "--out", "gen", .. gate]); Assert.Contains("stand-in runner: verify --codegen --out", stdout); Assert.Equal(2, exit); diff --git a/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs b/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs index eba808db7e..97587a3f9a 100644 --- a/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/VerifyRequirementsTests.cs @@ -228,7 +228,7 @@ public void The_gate_runs_under_codegen_alone_and_its_errors_reach_the_exit_code // requirement gate still runs, as it does on every verify, and prints its findings. var args = Project(Requirement("Recorded", "live", "Refund")); var model = args[1]; - var codegenArgs = new[] { "verify", model, "--codegen", "--out", Path.Combine(_tmp, "out") }; + var codegenArgs = new[] { "verify", model, "--codegen", "--full", "--out", Path.Combine(_tmp, "out") }; var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, codegenArgs); @@ -354,7 +354,7 @@ public void Codegen_with_no_out_dir_never_loads_so_the_gate_reports_the_model_th { // In-process this time, through the built CLI: `--codegen` with no `--out` stops before it // loads anything, so here too the gate's load is the only one. - var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, "verify", UnloadableModel(), "--codegen"); + var (exitCode, stdout, stderr) = CliProcess.Run(_tmp, "verify", UnloadableModel(), "--codegen", "--full"); Assert.True(exitCode != 0, $"exit={exitCode}\nstdout={stdout}\nstderr={stderr}"); Assert.Contains(" load error: ERR_BAD_ATTR_VALUE: ", stderr); @@ -376,7 +376,7 @@ public void A_load_failure_a_gate_already_reported_is_not_reported_again() // So did the codegen gate, in its own form: since ADR-0034 Amendment 9 it runs in the // project's codegen project (CodegenCli.Run, see OwnedRunner). var (codegenExit, _, codegenErr) = OwnedRunner.Run( - _tmp, Array.Empty(), "verify", "--codegen", model, "--out", Path.Combine(_tmp, "out")); + _tmp, Array.Empty(), "verify", "--codegen", "--full", model, "--out", Path.Combine(_tmp, "out")); Assert.NotEqual(0, codegenExit); Assert.Contains("verify --codegen: FAILED (metadata did not load cleanly)", codegenErr); Assert.Equal(1, CountOf(codegenErr, "ERR_BAD_ATTR_VALUE")); diff --git a/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs b/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs index 321e0818b7..0b9437bc27 100644 --- a/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs +++ b/server/csharp/MetaObjects.Cli.Tests/WireSettingCliTests.cs @@ -104,7 +104,7 @@ public void Verify_with_the_wrong_wire_setting_says_the_setting_differs_instead_ WriteConfig(null); var (exit, stdout, stderr) = OwnedRunner.Run( - _tmp, ["entity"], "verify", "--codegen", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); + _tmp, ["entity"], "verify", "--codegen", "--full", MetaDir, "--out", outDir, "--namespace", "Acme.Generated"); var output = stdout + stderr; Assert.Equal(1, exit); Assert.Contains( diff --git a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs index 0c51bf6f7f..8ed7a12ce2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/EnumLengthCliTests.cs @@ -53,7 +53,7 @@ public void Gen_reports_the_member_by_name_and_fails() [Fact] public void Verify_codegen_reports_the_member_by_name_and_fails() { - var (code, text) = Run("verify", "--codegen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + var (code, text) = Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); Assert.NotEqual(0, code); Assert.Contains("field.enum \"Ticket.status\" has the member \"CLOSED\"", text); } diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs index 76a3f73685..fd0738135e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepTests.cs @@ -77,7 +77,7 @@ private void Model(string package, params string[] values) => } private (int Code, string Out, string Err) Gen(params string[] extra) => Run(["gen", Meta, "--out", Out, "--namespace", "Acme.Generated", .. extra]); - private (int Code, string Out, string Err) Verify() => Run("verify", "--codegen", Meta, "--out", Out, "--namespace", "Acme.Generated"); + private (int Code, string Out, string Err) Verify() => Run("verify", "--codegen", "--full", Meta, "--out", Out, "--namespace", "Acme.Generated"); private Dictionary Manifest() => JsonSerializer.Deserialize>(File.ReadAllText(ManifestPath))!; diff --git a/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs index 945bc07c86..abbdc187ed 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/RecipeGeneratorTests.cs @@ -66,12 +66,12 @@ public void The_recipe_generates_verifies_and_catches_drift() Assert.Equal("3.1.0", (string?)api["openapi"]); Assert.Equal(["/api/customers", "/api/customers/{id}"], api["paths"]!.AsObject().Select(p => p.Key)); - Assert.Equal(0, CodegenCli.Run(["verify", "--codegen", Meta, "--out", Out], Suite)); + Assert.Equal(0, CodegenCli.Run(["verify", "--codegen", "--full", Meta, "--out", Out], Suite)); File.WriteAllText(Path.Combine(Meta, "meta.shop.json"), Model.Replace("""{ "field.string": { "name": "email", "@required": true } },""", """{ "field.string": { "name": "email", "@required": true } }, { "field.string": { "name": "note" } },""")); - Assert.NotEqual(0, CodegenCli.Run(["verify", "--codegen", Meta, "--out", Out], Suite)); + Assert.NotEqual(0, CodegenCli.Run(["verify", "--codegen", "--full", Meta, "--out", Out], Suite)); } private sealed class Throws : IGenerator diff --git a/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs b/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs index 64f7d0bd22..7079b02dc7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/WrappedTemplateSpecTests.cs @@ -48,7 +48,7 @@ public void A_wrapped_declared_spec_is_not_legacy_and_an_invalid_one_is_validate public void A_wrapped_declared_spec_is_not_legacy_and_an_invalid_one_is_validated_by_verify() { File.WriteAllText(Spec, "{ not json"); - var verify = Run("verify", "--codegen", Meta, "--out", Out); + var verify = Run("verify", "--codegen", "--full", Meta, "--out", Out); Assert.DoesNotContain("1.0 template-spec configuration", verify.Err); Assert.Contains("template spec", verify.Err); } From 1c4242f546c8c536297deda8a47a81e95c9536e7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 17:39:34 -0500 Subject: [PATCH 259/267] test(csharp): gen re-renders when the output project's assembly is renamed, and refuses a format-3 key Two end-to-end cases through CodegenCli.Run on a Postgres project with a .csproj above --out: an unchanged second gen skips, renaming the assembly renders again and the DesignTimeServicesReference names the new assembly; and a stored key rewritten to format 3 is not read, so gen renders and stores a format-4 key. Co-Authored-By: Claude Opus 5.5 --- .../GenFingerprintProjectFileTests.cs | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs index c66da1f6bf..2c92e056e9 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GenFingerprintProjectFileTests.cs @@ -5,8 +5,10 @@ #nullable enable using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; using Xunit; +[Collection("Console")] public sealed class GenFingerprintProjectFileTests : IDisposable { private readonly string _root = Path.Combine(Path.GetTempPath(), "meta-projfile-" + Guid.NewGuid().ToString("N")); @@ -45,4 +47,79 @@ public void A_project_created_after_a_run_without_one_changes_the_key() Assert.NotEqual(without, Key()); } + + // ---- end to end: `dotnet meta gen` on a Postgres project whose .csproj sits above --out + + private string Meta => Path.Combine(_root, "metaobjects"); + private string Out => Path.Combine(_root, "gen"); + private string Services => Path.Combine(Out, "AppDbContextDesignTimeServices.g.cs"); + private string StateFile => Path.Combine(_root, ".metaobjects", ".gen-state", GenFingerprint.FileName); + + private void Project(string assembly) + { + Directory.CreateDirectory(Meta); + Directory.CreateDirectory(Path.Combine(_root, ".metaobjects")); + File.WriteAllText(Path.Combine(_root, ".metaobjects", "config.json"), """{ "schema_version": 1, "migrate": { "dialect": "postgres" } }"""); + File.WriteAllText(Path.Combine(Meta, "meta.acme.json"), """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Ticket", "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment", "@sequenceStart": 100 } } + ]}} + ]}} + """); + File.WriteAllText(Path.Combine(_root, "App.csproj"), Csproj(assembly)); + } + + private (int Code, string Text) Gen() + { + var (cwd, prevOut, prevErr) = (Directory.GetCurrentDirectory(), Console.Out, Console.Error); + var (o, e) = (new StringWriter(), new StringWriter()); + Directory.SetCurrentDirectory(_root); + Console.SetOut(o); + Console.SetError(e); + try { return (CodegenCli.Run(["gen", Meta, "--out", Out, "--namespace", "Acme.Generated"], [new DbContextGenerator()]), o + "\n" + e); } + finally { Console.SetOut(prevOut); Console.SetError(prevErr); Directory.SetCurrentDirectory(cwd); } + } + + private static string Reference(string assembly) => + $"DesignTimeServicesReference(\"Acme.Generated.AppDbContextDesignTimeServices, {assembly}\""; + + [Fact] + public void Renaming_the_assembly_renders_again_and_the_reference_names_the_new_one() + { + Project("First"); + var (first, firstText) = Gen(); + Assert.True(first == 0, firstText); + Assert.Contains(Reference("First"), File.ReadAllText(Services)); + var (again, againText) = Gen(); + Assert.True(again == 0, againText); + Assert.Contains("nothing changed since the last run; skipped", againText); + + File.WriteAllText(Path.Combine(_root, "App.csproj"), Csproj("Second")); + var (renamed, renamedText) = Gen(); + + Assert.True(renamed == 0, renamedText); + Assert.DoesNotContain("skipped", renamedText); + Assert.Contains(Reference("Second"), File.ReadAllText(Services)); + } + + [Fact] + public void A_state_file_of_the_previous_format_is_not_a_match_and_gen_renders() + { + Project("App"); + var (first, firstText) = Gen(); + Assert.True(first == 0, firstText); + Assert.True(File.Exists(StateFile), firstText); + var stored = File.ReadAllText(StateFile); + Assert.Contains($"\"format\": {GenFingerprint.FormatVersion}", stored); + File.WriteAllText(StateFile, stored.Replace($"\"format\": {GenFingerprint.FormatVersion}", "\"format\": 3")); + + Assert.Null(GenFingerprint.Read(_root)); + var (second, secondText) = Gen(); + Assert.True(second == 0, secondText); + Assert.DoesNotContain("skipped", secondText); + Assert.Contains($"\"format\": {GenFingerprint.FormatVersion}", File.ReadAllText(StateFile)); + } } From 8108a51c855b314c0be48a94397797ec9474f43b Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 17:39:37 -0500 Subject: [PATCH 260/267] fix(cli): a skipped meta gen still prints the widened-extender warning dotnet meta gen printed the rc.21 extender-subtype-scope warning before its skip check, meta gen after it, so the same unchanged project warned in one port and not the other. ADR-0062 says nothing about output on a skipped run; the finding is about the model, and a warning that stops appearing once nothing changes is one nobody fixes, so meta gen now says it before the skip too, and a structured skip document carries it under `warnings`. Co-Authored-By: Claude Opus 5.5 --- .../packages/cli/src/commands/gen.ts | 9 ++++++--- .../packages/cli/src/lib/gen-skip.ts | 4 +++- .../test/gen-extender-scope-warning.test.ts | 19 +++++++++++++++++-- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/server/typescript/packages/cli/src/commands/gen.ts b/server/typescript/packages/cli/src/commands/gen.ts index 6aee604740..1b6263f032 100644 --- a/server/typescript/packages/cli/src/commands/gen.ts +++ b/server/typescript/packages/cli/src/commands/gen.ts @@ -229,11 +229,16 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat // successful run and every file it recorded exists. Nothing renders and nothing is written, // the manifest and the stored key included. `--force` (and every mode that does not write) // never skips. + // + // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. Said before + // the skip, so a skipped run still says it (as `dotnet meta gen` does): the finding is about the + // model, and a warning that stops appearing once nothing changes is one the user never fixes. + warnings.push(...warnWidenedExtenders(metadata, (line) => log.warn(line))); const skipInputs = skipBase !== undefined ? withModel(skipBase, modelHashTree(metadata)) : undefined; if (skipInputs !== undefined && genMaySkip(flags)) { const verdict = decideGenSkip(skipInputs); if (verdict.skip) { - await reportGenSkip(fmt, verdict.recorded.length); + await reportGenSkip(fmt, verdict.recorded.length, warnings); return 0; } } @@ -247,8 +252,6 @@ export async function genCommand(args: string[], cwd: string, fmt: OutputFormat ? [...unknownAttrFindings, UNKNOWN_ATTR_GEN_ADVICE] : []; for (const w of unknownAttrs) { log.warn(`warning: ${w}`); warnings.push(w); } - // rc.21 part B (I2): an extender whose view now returns every row of a TPH base. - warnings.push(...warnWidenedExtenders(metadata, (line) => log.warn(line))); // The schema settings `meta migrate` builds with, for the Prisma schema, the schema page and // the migrate advice. A conventions preset that does not resolve is a config error here as in diff --git a/server/typescript/packages/cli/src/lib/gen-skip.ts b/server/typescript/packages/cli/src/lib/gen-skip.ts index edb0a054c9..811eae92d0 100644 --- a/server/typescript/packages/cli/src/lib/gen-skip.ts +++ b/server/typescript/packages/cli/src/lib/gen-skip.ts @@ -16,7 +16,7 @@ const SKIP_SUMMARY = "nothing changed since the last meta gen, so nothing was re const SKIP_HELP = "meta gen --force regenerates everything"; /** Print the skipped run in the requested format. */ -export async function reportGenSkip(fmt: Format, recorded: number): Promise { +export async function reportGenSkip(fmt: Format, recorded: number, warnings: readonly string[] = []): Promise { if (fmt === "text") { log.info(`meta gen — ${SKIP_SUMMARY} (${recorded} generated file(s) up to date). ${SKIP_HELP}.`); return; @@ -29,6 +29,8 @@ export async function reportGenSkip(fmt: Format, recorded: number): Promise 0 && { warnings: [...warnings] }), }; if (fmt === "json") log.info(JSON.stringify(doc, null, 2)); else { diff --git a/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts index 495accc4eb..2848372f9b 100644 --- a/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts +++ b/server/typescript/packages/cli/test/gen-extender-scope-warning.test.ts @@ -30,7 +30,7 @@ function model(scoped: boolean, abstract = false): string { }); } -function setupRepo(scoped: boolean, abstract = false): string { +function setupRepo(scoped: boolean, abstract = false, generators = "[]"): string { mkdirSync(WORKSPACE_TMP, { recursive: true }); const root = mkdtempSync(join(WORKSPACE_TMP, "gen-extender-scope-")); mkdirSync(join(root, "metaobjects"), { recursive: true }); @@ -44,7 +44,7 @@ export default defineConfig({ dialect: "postgres", dbImport: "~/db", extStyle: "none", - generators: [], + generators: ${generators}, }); `); return root; @@ -68,6 +68,21 @@ afterEach(() => { }); describe("meta gen — the widened-extender warning is printed", () => { + test("a skipped run still prints it, as dotnet meta gen does", async () => { + // A wired generator, so the first run stores the key the second one skips on. + const root = setupRepo(false, false, `["entity"]`); + try { + expect(await run(["gen", "--cwd", root])).toBe(0); + err.length = 0; + out.length = 0; + expect(await run(["gen", "--cwd", root])).toBe(0); + expect([...out, ...err].join("\n")).toContain("nothing changed since the last meta gen"); + expect(err.join("\n")).toContain("object.projection TruckRow"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + test("names the projection, the field and the remedy; exit code unchanged", async () => { const root = setupRepo(false); try { From 8ca82715ac4567bc191f08997154eb2930e30a42 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Sun, 15 Nov 2026 17:39:41 -0500 Subject: [PATCH 261/267] docs(changelog): the 1.2.2 Bridge-route entry names the Coupon subtype The test-model rename left one Copay mention in the [1.2.2] section. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dde6778288..dd30248c38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1351,7 +1351,7 @@ file changes. No vocabulary or `metamodelVersion` change._ route subtype's own settable columns. - **C# (`MetaObjects.Codegen`).** The create route bound the EF Core entity from the body, so a client `id` on a generated key was inserted, a TPH create stored the body's discriminator (a - POST to the Bridge route could create a Copay row), and a TPH subtype's `readOnly` field and + POST to the Bridge route could create a Coupon row), and a TPH subtype's `readOnly` field and an M:N navigation graph were written. The route now resets the generated key and the discriminator to their defaults and empties the M:N navigations before `Add`, and a `readOnly` property of every shape, a TPH subtype's included, has a private setter, which From aa17da4d288d40d1076bfbea6ebfbd2503b080ff Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 17 Nov 2026 23:21:50 -0500 Subject: [PATCH 262/267] no-mistakes(review): apply reviewer inline fixes --- .../codegen/generators/names_generator.py | 34 ----------------- .../src/metaobjects/config/neutral_config.py | 37 ------------------- 2 files changed, 71 deletions(-) diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index b92b7e9ddf..f814a083b0 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -272,40 +272,6 @@ def _flattened_members(field: MetaData, strategy: str) -> list[tuple[str, str]] return [(m.name, resolve_flattened_column_name(field, m, strategy)) for m in target.fields()] -def _flattened_member_consts( - field: MetaData, members: list[tuple[str, str]] -) -> list[tuple[str, _Const]]: - """A flattened value object's ``__COLUMN`` constants, one per member, - emitted beside the field's own ``_FIELD`` constant (a flattened field has no column - constant of its own).""" - member = _member(field.name) - return [ - ( - f"{field.name}.{name}", - _Const(f"{member}_{_member(name)}_COLUMN", _q(column), f"field {field.name + '.' + name!r}"), - ) - for name, column in sorted(members) - ] - - -def _flattened_members(field: MetaData, strategy: str) -> list[tuple[str, str]] | None: - """The ``(member name, column)`` pairs of a ``@storage: "flattened"`` value object, or - ``None`` for any other field. - - The flattened test is migrate's own: a ``field.object`` whose RESOLVED ``@storage`` is - ``flattened`` (ADR-0039 — it may be inherited). Each member's column is core naming's - :func:`metaobjects.naming.resolve_flattened_column_name`, the rule ``meta migrate`` names - it by. A flattened field whose ``@objectRef`` does not resolve has no members; the loader - refuses that model before codegen runs. - """ - if field.sub_type != FIELD_SUBTYPE_OBJECT or field.get_meta_attr(FIELD_ATTR_STORAGE) != STORAGE_FLATTENED: - return None - target = ref_target(field, FIELD_ATTR_OBJECT_REF) - if not isinstance(target, MetaObject): - return [] - return [(m.name, resolve_flattened_column_name(field, m, strategy)) for m in target.fields()] - - def _flattened_member_consts( field: MetaData, members: list[tuple[str, str]] ) -> list[tuple[str, _Const]]: diff --git a/server/python/src/metaobjects/config/neutral_config.py b/server/python/src/metaobjects/config/neutral_config.py index 3780e99320..43dba03913 100644 --- a/server/python/src/metaobjects/config/neutral_config.py +++ b/server/python/src/metaobjects/config/neutral_config.py @@ -205,7 +205,6 @@ def read_neutral_config(config_dir: Path) -> NeutralConfig | None: wire = _read_wire(raw, path) _check_enums(raw, path) api = _read_api(raw, path) - _check_enums(raw, path) requirements_inherit = _read_requirements_inherit(raw, path) # Unknown top-level keys are IGNORED by design — see the module docstring. @@ -370,42 +369,6 @@ def _read_naming(raw: dict[str, object], path: Path) -> NamingRules: return NamingRules(columns=columns, tables=tables, collections=collections) -#: Every key the `enums` block accepts, and the ONLY ones it accepts (refused, not ignored, like `naming`). -_ENUMS_KEYS = ("maxLength",) - - -def _check_enums(raw: dict[str, object], path: Path) -> None: - """The `enums` block: `maxLength`, a positive integer, is the column length a port that - sizes a string-stored enum's column gives one with no @maxLength. This port sizes no - column (it emits no DDL and no column type), so it reads nothing from the block, but a - project shared with a port that does has one: the block is accepted, and its shape is - checked so a typo is refused here as it is there (a non-object block, an unknown key, or - a value that is not a positive integer).""" - if "enums" not in raw: - return - enums = raw["enums"] - if not isinstance(enums, dict): - raise ParseError(f"{path}: 'enums' must be an object", code=ErrorCode.ERR_BAD_ATTR_VALUE) - unknown = sorted(set(enums) - set(_ENUMS_KEYS)) - if unknown: - raise ParseError( - f"{path}: 'enums' has unknown key(s) {unknown}; accepted: {list(_ENUMS_KEYS)}", - code=ErrorCode.ERR_BAD_ATTR_VALUE, - ) - if "maxLength" not in enums: - return - value = enums["maxLength"] - # A whole number however JSON spells it (32, 32.0, 1e2): a reader that parses numbers as - # doubles (TypeScript's) cannot tell those apart, so every port accepts all three. - if isinstance(value, float) and value.is_integer(): - value = int(value) - if isinstance(value, bool) or not isinstance(value, int) or value <= 0: - raise ParseError( - f"{path}: 'enums.maxLength' must be a positive integer, got {value!r}", - code=ErrorCode.ERR_BAD_ATTR_VALUE, - ) - - _PAGE_SIZE_MAX = 2147483647 From d77e4295668d6d6e74cd89fe4c2d080857ec2b68 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Tue, 17 Nov 2026 23:37:56 -0500 Subject: [PATCH 263/267] no-mistakes(review): apply reviewer inline fixes --- server/typescript/packages/metadata/src/naming.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/server/typescript/packages/metadata/src/naming.ts b/server/typescript/packages/metadata/src/naming.ts index 44e1d03d1a..c7362e4c96 100644 --- a/server/typescript/packages/metadata/src/naming.ts +++ b/server/typescript/packages/metadata/src/naming.ts @@ -444,7 +444,6 @@ export function pluralize(s: string): string { * (`naming.collections`, {@link physicalNamingOf}) over its name. Each artifact then applies its * own casing (REST: snake_case; a TS export: as is; a Drizzle variable: lowerFirst). Own, not * resolving: a name inherited from an abstract base would give every subtype one collection. - * Throws when an object declares both attrs — the caller reports it. */ export function collectionNameOf(obj: MetaData): string { const declared = declaredCollectionName(obj); @@ -487,7 +486,7 @@ export function snakeCollectionName(s: string): string { } /** - * The collection name an object declares itself, and through which attr; undefined when it + * The collection name an object declares itself (`@collectionName`); undefined when it * declares none. */ export function declaredCollectionName(obj: MetaData): { name: string } | undefined { From ac8f7a0d0f6aac0faef8651ea3d7053d70a9f3e6 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 00:05:37 -0500 Subject: [PATCH 264/267] no-mistakes(document): fix stale docs after 1.2.x/main merge --- AGENTS.md | 14 ++++++++------ docs/CONFORMANCE.md | 10 +++++++--- docs/features/adopting-existing-models.md | 4 ++-- docs/features/entities.md | 14 ++++++++------ .../codegen/collection_name_collision.py | 4 ++-- 5 files changed, 27 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 172f4eed5b..b9f825d63a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ The first four ship per-language today across the five ports (TS / C# / Java / P ## Status -_Last refreshed 2026-10-30._ +_Last refreshed 2026-11-17._ **1.0 gating — the quiet period is RETIRED (2026-09-06).** `docs/1.0-readiness.md` §G3 no longer asks for "one coordinated release with no metamodel-breaking change." It measured a @@ -39,14 +39,16 @@ because a conformance corpus gates the ports against each other and never agains in ADR-0035 **Amendment 3**. Do not reintroduce a waiting gate in any form. -**Where the versions are.** `latest` is **`1.2.0`** on npm, **`8.2.0`** on Maven Central, -**`1.2.0`** on PyPI and **`1.2.0`** on NuGet (the Maven major is always **npm major + 7**, so -1.2.0 is 8.2.0). **1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4 and 1.2.0 are released.** 1.0.13 is the last 1.0.x release; the four registries moved together on 1.0.13, 1.0.12, 1.0.11, 1.0.10 and 1.0.9 (Maven skipped 8.0.8), and earlier Maven alone took 1.0.6 (8.0.6) while the other three skipped that +**Where the versions are.** `latest` is **`1.2.3`** on npm, **`8.2.3`** on Maven Central, +**`1.2.3`** on PyPI and **`1.2.3`** on NuGet (the Maven major is always **npm major + 7**, so +1.2.3 is 8.2.3). **1.1.0 through 1.2.0, 1.2.1 (Python only), 1.2.2 and 1.2.3 are released.** +`CHANGELOG.md` carries a dated **[1.3.0]** section, but no registry has published it yet (the +npm publish prep is still open); and the 1.2.x line has `1.2.4-rc.N` candidates cut. 1.0.13 is the last 1.0.x release; the four registries moved together on 1.0.13, 1.0.12, 1.0.11, 1.0.10 and 1.0.9 (Maven skipped 8.0.8), and earlier Maven alone took 1.0.6 (8.0.6) while the other three skipped that number. Both patterns are the convergent-publishing rule working as intended. **1.0 is CUT** and **1.1 is released**: the 1.0.0-rc candidates through 1.0.13 are superseded, and npm's `next` tag is REPOINTED onto each release — not deleted, because `dist-tag rm` 403s for every token we hold (`docs/RELEASING.md` §4). `metamodelVersion` read **`1.0`** through 1.0.13 — C4 landed and G4 shipped it, and no 1.0.x patch moved it (1.0.4 relaxed `@sourceRefField` onto `@cardinality: one` with a prose-only -manifest footprint, and was ruled a hold). `metamodelVersion` read **`1.1`** from 1.1.0 through 1.1.3 for the FR-044 reporting vocabulary and the requirements slice 1 (the first slice of two, covering existence gates and per-entity coverage). **It reads `1.2` from 1.1.4** for calendar-aligned relative report windows (`startOf` on a relative date). Per-release detail lives in **`CHANGELOG.md`** — it is the log, and this file does +manifest footprint, and was ruled a hold). `metamodelVersion` read **`1.1`** from 1.1.0 through 1.1.3 for the FR-044 reporting vocabulary and the requirements slice 1 (the first slice of two, covering existence gates and per-entity coverage). **It reads `1.2` from 1.1.4** through every published release since, for calendar-aligned relative report windows (`startOf` on a relative date). The merged tree claims **`1.3`** (`METAMODEL_VERSION` in every port) — main's 1.3.0 and the line's 1.2.4 both carry it, and neither is published. Per-release detail lives in **`CHANGELOG.md`** — it is the log, and this file does not duplicate it. The npm surface is **14 `@metaobjectsdev/*` packages in full lockstep**; the two `angular` @@ -80,7 +82,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken. **Key cross-language features shipped:** FR5 family (a/b/c/d/e + WARN envelope-shape — actionable loader errors per ADR-0009); FR-003 (Java RDB runtime persistence + projections; schema migrations are TS-only — the Java migration engine was removed); FR-006 (template.output parser-on-receipt codegen per ADR-0010 in all 5 ports); FR-008 + FR-009 (cross-port REST API contract + the nine filter operators); FR-018 (M:N relationship codegen in all 5 ports — entity navigation + idiomatic ORM wiring [Drizzle m2m / EF Core `UsingEntity` / Spring repo+JPA / Exposed / Pydantic+route as the SQLAlchemy-secondary equivalent] + REST traversal `GET //{id}/` + Tier-2 docs, gated by the shared api-contract m2m corpus in both lanes + persistence-conformance; the TanStack M:N client hook is a deferred client-ergonomics follow-up); SP-H (field-subtype end-to-end hardening: every concrete `field.*` subtype write+read round-trips cross-port via the persistence `op: roundtrip` gate; cut `field.byte`/`field.short`/`field.class` non-functional stubs; cross-port filter-op reconciliation for uuid/currency); source v2 paradigm (ADR-0007); metadata-ktx Kotlin facade; per-target output directories (TS codegen); FR-044 (the reporting vocabulary — `dimension.attribute`/`dimension.time`, `measure.aggregate`/`measure.ratio`, `segment.filter`, `object.report`, `@spine` on a report to take rows from a to-one dimension entity, `@default` on a measure for empty aggregates, plus the relative-date filter value — registered and loader-validated in all five ports; a report that declares a read-only `source.rdb @kind: view` is lowered to a SQL view by `meta migrate` and read by every port, and served by a generated read-only list route in every port, gated by the api-contract `report/` sub-corpus; the TypeScript `cube-model` reference generator writes the vocabulary as Cube data-model files, gated by the `fixtures/cube-model/` corpus and a `cube` lane that loads the output into a real Cube; a served report gets the generated TanStack list hook (`use`, or `useList` when the plural is the name) but no grid or form, see [docs/features/reporting.md](docs/features/reporting.md) and [docs/features/cube-export.md](docs/features/cube-export.md)). -**Release 1.1.0** (released; npm `1.1.0`, PyPI `1.1.0`, NuGet `1.1.0` and Maven Central `8.1.0`; the latest is 1.2.0 / 8.2.0). The reporting release (FR-044): declare dimensions, measures, segments and an `object.report`, and get a SQL view, a served read-only list route in every port, a generated TanStack list hook, and a Cube data model, with `@spine` for rows that have no facts and `@default` for an empty measure. Also carries the first slice of requirements (the gate in every port's `verify`), the derived-key parity fix across the ports, and the list-hook and nested-average fixes found by the first adopter. See the `CHANGELOG.md` 1.1.0 section for the full scope, pre-release RC history, and the diffs to expect when you upgrade (ejected generators and keyless projections). It also makes documentation a set of generators in every port (ADR-0034 Amendment 9): the docs commands are removed, and `docs/features/migrations/docs-are-generators.md` is the upgrade path. The last 1.0.x release, 1.0.13 (2026-10-03), was a PATCH on 1.0.x. +**Release 1.1.0** (released; npm `1.1.0`, PyPI `1.1.0`, NuGet `1.1.0` and Maven Central `8.1.0`; the latest is 1.2.3 / 8.2.3). The reporting release (FR-044): declare dimensions, measures, segments and an `object.report`, and get a SQL view, a served read-only list route in every port, a generated TanStack list hook, and a Cube data model, with `@spine` for rows that have no facts and `@default` for an empty measure. Also carries the first slice of requirements (the gate in every port's `verify`), the derived-key parity fix across the ports, and the list-hook and nested-average fixes found by the first adopter. See the `CHANGELOG.md` 1.1.0 section for the full scope, pre-release RC history, and the diffs to expect when you upgrade (ejected generators and keyless projections). It also makes documentation a set of generators in every port (ADR-0034 Amendment 9): the docs commands are removed, and `docs/features/migrations/docs-are-generators.md` is the upgrade path. The last 1.0.x release, 1.0.13 (2026-10-03), was a PATCH on 1.0.x. Active and planned work lives in GitHub: issues labelled `FR`, milestones for releases, and the MetaObjects Roadmap project board. `spec/roadmap.md` keeps the release direction and the FR → issue → spec index. Process: `docs/ROADMAP-PROCESS.md`. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index ba0986bdae..ed885a4265 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -179,9 +179,13 @@ collide on an output path. State per port: - *Done, TypeScript:* `outputLayout` defaults to `"flat"`; `"package"` is opt-in (ruling R63). Tests: `barrel-layout.test.ts` (the barrel exports the same names in both layouts), `naming/name-claims.test.ts`. -- *TODO, Python:* only the flat layout exists. A package layout is new work. -- *TODO, Java and Kotlin:* files land in the mapped Java package directories, so two metadata - packages mapped to one Java package would collide. +- *Done, Python:* `outputLayout` mirrors TypeScript — `"flat"` the default, `"package"` opt-in, + and `metaobjects init` writes `outputLayout: package` into a new project. Tests: + `tests/codegen/test_package_layout.py`. +- *Done, Java and Kotlin:* every per-object file lands in the directory of its metadata package + (`a::b` → `a/b`), and a run where two metadata packages would land in one directory is + refused (`OutputPackageCollisions`), not silently overwritten. Tests: `PackageKeyedOutputTest` + (spring, kotlin). - Tracked in [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549. **Native index vocabulary and `@description` in the ORM models.** `meta migrate` creates diff --git a/docs/features/adopting-existing-models.md b/docs/features/adopting-existing-models.md index 1c36fe6fe4..c4412e9e75 100644 --- a/docs/features/adopting-existing-models.md +++ b/docs/features/adopting-existing-models.md @@ -76,7 +76,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -169,7 +169,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/docs/features/entities.md b/docs/features/entities.md index e796a71d23..f31c4b276f 100644 --- a/docs/features/entities.md +++ b/docs/features/entities.md @@ -146,12 +146,14 @@ Absent, the project's **pluralizer** derives it from the object's name. One sett `naming.collections` in `.metaobjects/config.json`, selects it by name, exactly as `naming.columns` selects a column rule. Built in: `standard` (the default — the rule every port shares: an already-plural name stays, else `-s`/`-es`/`-ies`) and `none` (the name as it is). An application -registers its own (`namingStrategies.collections` in `metaobjects.config.ts` or -`registerPluralizer` in TypeScript; `NamingStrategies.RegisterPluralizer` in C#), and a name -nothing answers is refused when the config is read. An object's own `@collectionName` always wins. - -`@collectionName` is implemented in C# and TypeScript (ruling R40 kind 1); Java, Kotlin and -Python load it and do nothing with it yet. In C#, a project that configures no pluralizer keeps its historical DbSet names (which +registers its own (`namingStrategies.collections` in `metaobjects.config.ts`; `registerPluralizer` +in TypeScript and Java, `NamingStrategies.RegisterPluralizer` in C#, `register_pluralizer` in +Python), and a name nothing answers is refused when the config is read. An object's own +`@collectionName` always wins. + +`@collectionName` and `naming.collections` are implemented in every port (ruling R40 kind 1): +each port's route/controller path (and the C# `DbSet` name) reads the declared name or the +configured pluralizer. In C#, a project that configures no pluralizer keeps its historical DbSet names (which add C#'s `-sis` → `-ses` rule). ## What each port generates diff --git a/server/python/src/metaobjects/codegen/collection_name_collision.py b/server/python/src/metaobjects/codegen/collection_name_collision.py index 3f2304f17c..c503553191 100644 --- a/server/python/src/metaobjects/codegen/collection_name_collision.py +++ b/server/python/src/metaobjects/codegen/collection_name_collision.py @@ -32,8 +32,8 @@ def assert_no_collection_name_collisions(entities: list[MetaObject]) -> None: """Refuse a generation run in which two DISTINCT entities/projections pluralize to the same API-surface collection name. - Scope: this port writes every module into one flat package (``output_layout`` is flat - only) served by one app, so its scope is the whole run. Counted over the objects that + Scope: this port serves one app regardless of ``output_layout`` (``package`` splits + generated module directories, not route surfaces), so its scope is the whole run. Counted over the objects that emit a collection (:func:`_emits_collection`). A value object, an abstract object and a sourceless one never get a route, router module, or finder name, so they cannot collide on any of those — a layered model's abstract From f2afe7ca2d2a34038d94f9da55e3ed1d1142a248 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 00:53:23 -0500 Subject: [PATCH 265/267] fix: sync the adoption recipe mirrors with the flat-default wording; make a C# golden mismatch readable in CI - docs/features/adopting-existing-models.md (edited by the gate's document step) and the same outputLayout comment in four recipes, the agent-context mirror and the agent-context conformance corpus now say `"package"` is the opt-in layout, matching the flat default. Fixes the sdk recipe-mirror test that failed in CI. - PropertyNamingGoldenTests names the file, the first differing line and both spellings on a mismatch, and compares file names ordinally. It failed in CI only, with no message. - ci-local's C# lane adds the minimal console logger, so a failing test's message reaches the log. --- .../references/adopting-existing-models.md | 4 +-- docs/recipes/cloudflare-workers.md | 2 +- docs/recipes/drizzle-kit-migrations.md | 2 +- docs/recipes/nextjs-vercel.md | 2 +- docs/recipes/wiring-generated-queries.md | 2 +- .../references/adopting-existing-models.md | 4 +-- .../references/adopting-existing-models.md | 4 +-- .../references/adopting-existing-models.md | 4 +-- .../references/adopting-existing-models.md | 4 +-- .../references/adopting-existing-models.md | 4 +-- scripts/ci-local.sh | 9 ++++--- .../PropertyNamingGoldenTests.cs | 25 ++++++++++++++++--- 12 files changed, 43 insertions(+), 23 deletions(-) diff --git a/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md b/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md index 2fb95c0853..6854ed810c 100644 --- a/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/agent-context/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,7 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -160,7 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/docs/recipes/cloudflare-workers.md b/docs/recipes/cloudflare-workers.md index f1601ee979..cf659a8143 100644 --- a/docs/recipes/cloudflare-workers.md +++ b/docs/recipes/cloudflare-workers.md @@ -143,7 +143,7 @@ import { entityFile, queriesFile, routesFileHono, barrel } from "@metaobjectsdev export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "sqlite", // D1 is SQLite extStyle: "js", apiPrefix: "/api", diff --git a/docs/recipes/drizzle-kit-migrations.md b/docs/recipes/drizzle-kit-migrations.md index b630a6e0db..88d4af2803 100644 --- a/docs/recipes/drizzle-kit-migrations.md +++ b/docs/recipes/drizzle-kit-migrations.md @@ -17,7 +17,7 @@ schema file that exports them. `meta migrate` never has to run. export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", // must match the database drizzle-kit migrates generators: [entityFile(), queriesFile(), barrel()], }); diff --git a/docs/recipes/nextjs-vercel.md b/docs/recipes/nextjs-vercel.md index 2721112ca1..9857b5b047 100644 --- a/docs/recipes/nextjs-vercel.md +++ b/docs/recipes/nextjs-vercel.md @@ -36,7 +36,7 @@ import { entityFile, queriesFile, routesFileHono, barrel } from "@metaobjectsdev export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", apiPrefix: "/api", diff --git a/docs/recipes/wiring-generated-queries.md b/docs/recipes/wiring-generated-queries.md index 6d2513f194..b8ac7ed983 100644 --- a/docs/recipes/wiring-generated-queries.md +++ b/docs/recipes/wiring-generated-queries.md @@ -274,7 +274,7 @@ import { honoRoutesFile } from "./metaobjects-routes-hono"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "sqlite", apiPrefix: "/api", generators: [entityFile(), queriesFile(), honoRoutesFile(), barrel()], diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index 2fb95c0853..6854ed810c 100644 --- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,7 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -160,7 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index 2fb95c0853..6854ed810c 100644 --- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,7 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -160,7 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index 2fb95c0853..6854ed810c 100644 --- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,7 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -160,7 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index 2fb95c0853..6854ed810c 100644 --- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,7 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -160,7 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md index 2fb95c0853..6854ed810c 100644 --- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md +++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/adopting-existing-models.md @@ -67,7 +67,7 @@ import { defineConfig } from "@metaobjectsdev/cli"; export default defineConfig({ outDir: "src/generated", // beside the existing code; nothing imports it yet - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", timestampMode: "date", // when the existing timestamp columns read as Date generators: ["entity"], @@ -160,7 +160,7 @@ import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; export default defineConfig({ outDir: "src/generated", - outputLayout: "flat", // the paths below; the default puts each metadata package in a directory of its own + outputLayout: "flat", // the paths below; "package" puts each metadata package in a directory of its own dialect: "postgres", targets: { contract: { outDir: "src/generated", runtime: false }, // Zod schemas and types, no ORM diff --git a/scripts/ci-local.sh b/scripts/ci-local.sh index c78b0c4e39..b2872f92e2 100755 --- a/scripts/ci-local.sh +++ b/scripts/ci-local.sh @@ -756,11 +756,12 @@ gate_ts_unit() { done } gate_conf_csharp() { + # The minimal console logger prints a failing test's message; plain `--verbosity quiet` names the test and nothing else. ( cd server/csharp \ - && dotnet test MetaObjects.Conformance.Tests/MetaObjects.Conformance.Tests.csproj --nologo --verbosity quiet \ - && dotnet test MetaObjects.Render.Tests/MetaObjects.Render.Tests.csproj --nologo --verbosity quiet \ - && dotnet test MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj --nologo --verbosity quiet \ - && dotnet test MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj --nologo --verbosity quiet ) + && dotnet test MetaObjects.Conformance.Tests/MetaObjects.Conformance.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" \ + && dotnet test MetaObjects.Render.Tests/MetaObjects.Render.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" \ + && dotnet test MetaObjects.Codegen.Tests/MetaObjects.Codegen.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" \ + && dotnet test MetaObjects.Cli.Tests/MetaObjects.Cli.Tests.csproj --nologo --verbosity quiet --logger "console;verbosity=minimal" ) } # NOTE: these -Dtest= lists are a CHERRY-PICK, so a new test class that is not named here # runs in NO per-push lane and reports green. Adding a test to this module means adding its diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs index 53410d069a..fbaf175549 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -132,9 +132,28 @@ public void Default_output_matches_the_output_captured_before_the_property_namin foreach (var f in files) File.WriteAllText(Path.Combine(dir, System.IO.Path.GetFileName(f.Path)), f.Content); return; } - var expected = Directory.GetFiles(dir).Select(p => Path.GetFileName(p)).Order().ToList(); - Assert.Equal(expected, files.Select(f => System.IO.Path.GetFileName(f.Path)).Order().ToList()); + var expected = Directory.GetFiles(dir).Select(p => Path.GetFileName(p)).Order(StringComparer.Ordinal).ToList(); + var actualNames = files.Select(f => System.IO.Path.GetFileName(f.Path)).Order(StringComparer.Ordinal).ToList(); + Assert.True(expected.SequenceEqual(actualNames), + $"golden file set differs. missing from output: [{string.Join(", ", expected.Except(actualNames))}]; not in golden: [{string.Join(", ", actualNames.Except(expected))}]"); foreach (var f in files) - Assert.Equal(File.ReadAllText(Path.Combine(dir, System.IO.Path.GetFileName(f.Path))), f.Content); + { + var name = System.IO.Path.GetFileName(f.Path); + var golden = File.ReadAllText(Path.Combine(dir, name)); + if (golden != f.Content) Assert.Fail(FirstDifference(name, golden, f.Content)); + } + } + + // A golden mismatch names the file, the first differing line and both spellings, so a failure that + // shows only on another machine can be read from its log instead of reproduced. + private static string FirstDifference(string name, string golden, string actual) + { + var g = golden.Split('\n'); + var a = actual.Split('\n'); + var i = 0; + while (i < g.Length && i < a.Length && g[i] == a[i]) i++; + string At(string[] lines, int n) => n < lines.Length ? lines[n].Replace("\r", "\\r") : ""; + return $"{name}: output differs from its golden at line {i + 1} (golden {g.Length} lines, output {a.Length} lines)\n" + + $" golden: {At(g, i)}\n output: {At(a, i)}\n culture: {System.Globalization.CultureInfo.CurrentCulture.Name}; cwd: {Directory.GetCurrentDirectory()}"; } } From d4165390c59487276f6d056ba86c9955724f4947 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 01:55:55 -0500 Subject: [PATCH 266/267] no-mistakes(document): fix stale 1.2.1 release target in contract docs --- docs/features/contract-emitters.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/features/contract-emitters.md b/docs/features/contract-emitters.md index 75818dcf6e..fa016e75d7 100644 --- a/docs/features/contract-emitters.md +++ b/docs/features/contract-emitters.md @@ -4,8 +4,9 @@ _`jsonSchemaFile()` and `openApiFile()`: write the model's wire contract as plai and OpenAPI 3.1, so a consumer in any language can work from a standard document instead of a fourth hand-kept source of truth._ -**Status:** TypeScript reference helpers, unreleased, targeting 1.2.1 (FR-022; -[ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md) Amendment 10). They are listed +**Status:** TypeScript reference helpers, unreleased (FR-022; +[ADR-0034](../../spec/decisions/ADR-0034-codegen-scaffold-and-own.md) Amendment 10; the changelog's +unpublished `[1.3.0]` / `[1.2.4]` sections carry them). They are listed by `meta gen --list`, imported from `@metaobjectsdev/codegen-ts/generators` to run as shipped, copied with `meta eject contract-schema openapi` to change them, and checked by `meta verify --codegen`. They are not core: what MetaObjects guarantees is the model, and a generator that writes files into your From e7305b0b98e02bb46dd016d0da4e3c187f5bc640 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 02:02:20 -0500 Subject: [PATCH 267/267] test(csharp): the property-naming golden finds its files from the repo root A CI build (CI=true turns on ContinuousIntegrationBuild) maps source paths to /_/, so the [CallerFilePath]-derived Golden directory did not exist and the test threw DirectoryNotFoundException on hosted runners. The neighbouring golden test already finds its files from the repo root; this one now does too. --- .../MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs index fbaf175549..0b86aace4d 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingGoldenTests.cs @@ -9,7 +9,6 @@ // Capture (re-capture only for a deliberate, reviewed output change): GOLDEN_WRITE=1 dotnet test // --filter PropertyNamingGoldenTests. Compare mode is the default. -using System.Runtime.CompilerServices; using MetaObjects.Codegen; using MetaObjects.Codegen.Generators; using MetaObjects.Loader; @@ -100,8 +99,10 @@ public class PropertyNamingGoldenTests ]}} """; - private static string GoldenDir([CallerFilePath] string here = "") => - Path.Combine(Path.GetDirectoryName(here)!, "Golden", "pre-rc22-propname"); + // Found from the repo root, not [CallerFilePath]: a CI build (CI=true turns on + // ContinuousIntegrationBuild) maps source paths to /_/, where no golden file exists. + private static string GoldenDir() => + Path.Combine(CorpusPaths.RepoRoot(), "server", "csharp", "MetaObjects.Codegen.Tests", "Golden", "pre-rc22-propname"); [Fact] public void Default_output_matches_the_output_captured_before_the_property_naming_fix()
    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @equals string yes The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + @@ -509,6 +563,15 @@

    validator.requiredWhen

    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max int no The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived _chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. + + + + + + + + + diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index e1d1cb0327..47ab036326 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -63,14 +63,16 @@ "type": "field", "subType": "enum", "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    @dbCheckbooleannometaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @equals string yes
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { "type": "validator", "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ - { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { From d7f7834a91ccf1baee5681e2a481a49480b54cc7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Wed, 11 Nov 2026 18:51:54 -0500 Subject: [PATCH 164/267] feat(schema): @dbCheck: false on a cross-field validator is refused A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK: no port evaluates it app-side. @dbCheck: false on one would leave the rule enforced nowhere, so the loader refuses it in every port (ERR_CROSS_FIELD_WITHOUT_CHECK: "this validator is enforced only by its CHECK ... Remove the validator, or remove @dbCheck: false"). It is the one error such a node gets, even with @constraintName. The attr stays registered on all seven CHECK validators, so the canonical registry changes only in its description text; @dbCheck: true remains legal everywhere. meta migrate and the C# CHECK builder no longer consult @dbCheck for cross-field validators: they always keep their CHECK. Fixture conformance/error-db-check-cross-field (all four subtypes, one with @constraintName); validator-db-check now sets @dbCheck: true on them; the CHECK corpus drops its opted-out comparison (its expected files are unchanged). Description, docs and CHANGELOG corrected; registry, metamodel-docs, site-reference and site-payload regenerated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 +++++---- docs/CONFORMANCE.md | 2 +- docs/features/migrations-and-drift.md | 21 ++++----- examples/showcase/site-payload.json | 2 +- .../check-constraint-conformance/README.md | 7 +-- .../input/meta.checks.json | 3 +- fixtures/conformance/ERROR-CODES.json | 1 + .../expected-errors.json | 45 +++++++++++++++++++ .../input/meta.checks.json | 26 +++++++++++ .../validator-db-check/expected.json | 8 ++-- .../validator-db-check/input/meta.checks.json | 8 ++-- .../expected/types/validator.md | 14 +++--- .../expected-registry.json | 14 +++--- .../Generators/CheckConstraints.cs | 3 +- .../Core/Validator/ValidatorConstants.cs | 6 +++ server/csharp/MetaObjects/Errors.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 22 ++++++--- .../MetaObjects/Persistence/Db/DbSchema.cs | 2 +- .../csharp/MetaObjects/SpecMetamodel/db.json | 2 +- .../main/java/com/metaobjects/ErrorCode.java | 2 + .../metaobjects/loader/ValidationPhase.java | 26 ++++++++--- .../util/ErrorMessageConstants.java | 7 +++ server/python/src/metaobjects/errors.py | 2 + .../metaobjects/loader/validation_passes.py | 22 +++++++-- .../meta/persistence/db/db_provider.py | 2 +- .../src/metaobjects/spec_metamodel/db.json | 2 +- .../packages/metadata/src/errors.ts | 2 + .../metadata/src/loader/validation-passes.ts | 13 +++++- .../persistence/db/db-definition.embedded.ts | 2 +- .../migrate-ts/src/expected-schema.ts | 3 +- site-reference/types/validator.html | 14 +++--- spec/metamodel/db.json | 2 +- 32 files changed, 226 insertions(+), 81 deletions(-) create mode 100644 fixtures/conformance/error-db-check-cross-field/expected-errors.json create mode 100644 fixtures/conformance/error-db-check-cross-field/input/meta.checks.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cba9c8b2d..3b81ae7667 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,15 +26,17 @@ vocabulary; upgrade every port together. - **`@dbCheck: false`: a validator or enum with no database CHECK (rc.20).** A CHECK-generating validator (`numeric`, `length`, `regex`, `comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) or a `field.enum` takes an optional db-provider boolean `@dbCheck`, default `true`. - With `false`, `meta migrate`, `meta verify --db`, the Prisma schema's CHECKs and the C# EF - context's declared CHECKs leave that one node's CHECK out; every other CHECK on the table, and - `migrate.checks.skipRedundant`, are unchanged. It is for a column whose legacy rows break a rule: - a CHECK added `NOT VALID` still refuses an UPDATE of such a row. The generated app-level - validation is unchanged, so `numeric`, `length`, `regex` and an enum's members still hold every - write; a cross-field validator has no app-level enforcement, so with `false` it is enforced - nowhere. `@dbCheck: false` with `@constraintName` is refused at load in every port - (`ERR_CONSTRAINT_NAME_WITHOUT_CHECK`). Fixtures `fixtures/conformance/validator-db-check` and - `error-db-check-constraint-name`; the shared CHECK corpus (`fixtures/check-constraint-conformance`) + With `false` on a `numeric`, `length` or `regex` validator or a `field.enum`, `meta migrate`, + `meta verify --db`, the Prisma schema's CHECKs and the C# EF context's declared CHECKs leave that + one node's CHECK out; every other CHECK on the table, and `migrate.checks.skipRedundant`, are + unchanged. It is for a column whose legacy rows break a rule: a CHECK added `NOT VALID` still + refuses an UPDATE of such a row. The generated app-level validation is unchanged, so the + validator and an enum's members still hold every write. A cross-field validator is enforced only + by its CHECK, so `@dbCheck: false` on one is refused at load in every port + (`ERR_CROSS_FIELD_WITHOUT_CHECK`; remove the validator instead), and so is `@dbCheck: false` with + `@constraintName` (`ERR_CONSTRAINT_NAME_WITHOUT_CHECK`). Fixtures + `fixtures/conformance/validator-db-check`, `error-db-check-constraint-name` and + `error-db-check-cross-field`; the shared CHECK corpus (`fixtures/check-constraint-conformance`) pins the omissions for TypeScript and C#. **Upgrade note:** a live CHECK whose node now says `@dbCheck: false` is proposed for dropping by the next `meta migrate` (`--allow drop-check` on Postgres), and by the next EF migration a C# model scaffolds. diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 4faf5831c5..4bd5a72251 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | Corpus | Fixtures | TS | Java | Kotlin | C# | Python | |---|---|---|---|---|---|---| -| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 462 | ✓ | ✓ but the rc.19 fixtures — the two reverse-hop fixtures (`origin-reverse-reference-hop`, `error-origin-reverse-hop-ambiguous`; bug R-walk), `origin-passthrough-flattened-member` and `reference-flattened-member` (bug G6), `projection-filter-unprojected-base-field`, `projection-filter-joined-path` and `error-projection-filter-path-to-many` (bug G7), `projection-extends-abstract-projection`, `projection-extends-filtered-projection` and `error-projection-extends-filter-sql-body` (bug G13; the last two from the fix round's C1), `object-collection-name` (R57), `report-dimension-required-by-model` (R62; its `expected-report-required.json` holds the model-derived `required` every port's report shape must give — Java, Kotlin and Python still derive it from the INNER-join rule), and the Tier 2 view vocabulary (R58: `entity-derived-hipaa-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `origin-filter-relative-now`, `projection-filter-relative-now`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`) — not run in this port; expected red until [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | inherits via `metadata-ktx` (the same) | ✓ | ✓ but the same, #544–#549 | +| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 463 | ✓ | ✓ but the rc.19 fixtures — the two reverse-hop fixtures (`origin-reverse-reference-hop`, `error-origin-reverse-hop-ambiguous`; bug R-walk), `origin-passthrough-flattened-member` and `reference-flattened-member` (bug G6), `projection-filter-unprojected-base-field`, `projection-filter-joined-path` and `error-projection-filter-path-to-many` (bug G7), `projection-extends-abstract-projection`, `projection-extends-filtered-projection` and `error-projection-extends-filter-sql-body` (bug G13; the last two from the fix round's C1), `object-collection-name` (R57), `report-dimension-required-by-model` (R62; its `expected-report-required.json` holds the model-derived `required` every port's report shape must give — Java, Kotlin and Python still derive it from the INNER-join rule), and the Tier 2 view vocabulary (R58: `entity-derived-hipaa-gate`, `origin-computed-case-over-joined`, `origin-correlated-filter-and-segment`, `origin-filter-relative-now`, `projection-filter-relative-now`, `error-origin-computed-case-mixed-types`, `error-origin-segment-unresolved`, `error-origin-correlated-operand-unknown`) — not run in this port; expected red until [#544](https://github.com/metaobjectsdev/metaobjects/issues/544)–#549 | inherits via `metadata-ktx` (the same) | ✓ | ✓ but the same, #544–#549 | | [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 | | [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ | | [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ | diff --git a/docs/features/migrations-and-drift.md b/docs/features/migrations-and-drift.md index 962d6b6be1..e31095fcc7 100644 --- a/docs/features/migrations-and-drift.md +++ b/docs/features/migrations-and-drift.md @@ -424,16 +424,17 @@ attributes shape it, all database-only (no generated code reads them): declared name is always emitted, even where `migrate.checks.skipRedundant` (below) would leave it out. - **`@dbCheck: false`** leaves the CHECK out: `meta migrate`, `meta verify --db` and a generated - EF model declare none for that validator or enum (absent, `true`). It is per node, on the same - validators and on `field.enum`. Use it for a column whose legacy rows break the rule: a CHECK - added `NOT VALID` still refuses an `UPDATE` of such a row, whatever the update changes. The - generated app-level validation is unchanged, so `numeric`, `length` and `regex` still hold every - write and an enum's members still bound the property; a cross-field validator (`comparison`, - `requiredWhen`, `presentIff`, `atLeastOne`) is enforced only by its CHECK, so with `false` it is - enforced nowhere. A live CHECK the model no longer declares is proposed for dropping (under - `--allow drop-check` on Postgres). Declaring `@constraintName` too is refused - (`ERR_CONSTRAINT_NAME_WITHOUT_CHECK`): there is no CHECK for the name to name. - `migrate.checks.skipRedundant` (below) is independent: it only ever leaves more out. + EF model declare none for that validator or enum (absent, `true`). It is per node, on a + `numeric`, `length` or `regex` validator and on `field.enum`. Use it for a column whose legacy + rows break the rule: a CHECK added `NOT VALID` still refuses an `UPDATE` of such a row, whatever + the update changes. The generated app-level validation is unchanged, so the validator still holds + every write and an enum's members still bound the property. A cross-field validator + (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) is enforced only by its CHECK, so + `false` on one is refused (`ERR_CROSS_FIELD_WITHOUT_CHECK`): remove the validator instead. + A live CHECK the model no longer declares is proposed for dropping (under `--allow drop-check` + on Postgres). Declaring `@constraintName` too is refused (`ERR_CONSTRAINT_NAME_WITHOUT_CHECK`): + there is no CHECK for the name to name. `migrate.checks.skipRedundant` (below) is independent: + it only ever leaves more out. - **`@condition`** on a cross-field validator (`comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) is an expression, in the grammar `origin.computed` uses, over the entity's fields. The rule holds only where the condition does: the CHECK is `(NOT condition) OR (rule)`, with diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 1b37f8f45c..6a3c53abc1 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 463, + "fixtures": 464, "corpora": 38, "baseTypes": 17 }, diff --git a/fixtures/check-constraint-conformance/README.md b/fixtures/check-constraint-conformance/README.md index e7453728b2..544973da5b 100644 --- a/fixtures/check-constraint-conformance/README.md +++ b/fixtures/check-constraint-conformance/README.md @@ -20,9 +20,10 @@ The rules the corpus pins (ruling R55, which follows `meta migrate`): - names `
    __chk` (enum), `_numeric_chk`, `_length_chk`, `_regex_chk`, `_cmp_chk`, `_reqwhen_chk`, `_presentiff_chk`, `_atleastone_chk`; a declared `@constraintName` replaces the name and is kept even where `skipRedundant` would leave the CHECK out; -- `@dbCheck: false` leaves a validator's or an enum's CHECK out, under `skipRedundant` too - (`npi`, `legacyState`, `rank`'s minimum, `legacyWindow`); a sibling validator on the same field - keeps its own (`rank`'s maximum), and `@dbCheck: true` is the default (`floor`); +- `@dbCheck: false` leaves a numeric, length or regex validator's or an enum's CHECK out, under + `skipRedundant` too (`npi`, `legacyState`, `rank`'s minimum); a sibling validator on the same + field keeps its own (`rank`'s maximum), and `@dbCheck: true` is the default (`floor`). A + cross-field validator always keeps its CHECK: `false` on one is a load error; - comparisons, not `BETWEEN`; columns double-quoted; an int-backed enum lists its integers; a duration literal is the interval text on Postgres and microseconds on SQLite; - no CHECK on an array column, and none on a derived (origin-bearing) field — it has no column — diff --git a/fixtures/check-constraint-conformance/input/meta.checks.json b/fixtures/check-constraint-conformance/input/meta.checks.json index e48f73e581..5c077f3b5c 100644 --- a/fixtures/check-constraint-conformance/input/meta.checks.json +++ b/fixtures/check-constraint-conformance/input/meta.checks.json @@ -52,8 +52,7 @@ { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@max": 1 } }, { "validator.atLeastOne": { "name": "anyContact", "@fields": ["phone", "fax"], "@condition": { "op": "eq", "left": { "field": "level" }, "right": { "value": "HIGH" } } } }, - { "validator.requiredWhen": { "name": "bandFax", "@field": "fax", "@when": "band", "@equals": "HIGH" } }, - { "validator.comparison": { "name": "legacyWindow", "@left": "startsAt", "@op": "lt", "@right": "endsAt", "@dbCheck": false } } + { "validator.requiredWhen": { "name": "bandFax", "@field": "fax", "@when": "band", "@equals": "HIGH" } } ] } }, diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index de13830e7b..44f601d17b 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -55,6 +55,7 @@ "ERR_STORAGE_FLATTENED_ARRAY": "@storage \"flattened\" cannot be combined with isArray=true.", "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", + "ERR_CROSS_FIELD_WITHOUT_CHECK": "A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) sets @dbCheck: false. Nothing but its database CHECK enforces a cross-field validator, so false would leave the rule enforced nowhere: the validator is refused. Remove the validator instead.", "ERR_CONSTRAINT_NAME_WITHOUT_CHECK": "A CHECK-generating validator (numeric, length, regex, comparison, requiredWhen, presentIff, atLeastOne) or a field.enum sets @dbCheck: false, which generates no database CHECK, and @constraintName, which names that CHECK. With no CHECK there is nothing to name, so the node is refused rather than one of the two silently ignored.", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", diff --git a/fixtures/conformance/error-db-check-cross-field/expected-errors.json b/fixtures/conformance/error-db-check-cross-field/expected-errors.json new file mode 100644 index 0000000000..e33dfc4598 --- /dev/null +++ b/fixtures/conformance/error-db-check-cross-field/expected-errors.json @@ -0,0 +1,45 @@ +{ + "errors": [ + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[8]['validator.comparison']" + } + }, + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[9]['validator.requiredWhen']" + } + }, + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[10]['validator.presentIff']" + } + }, + { + "code": "ERR_CROSS_FIELD_WITHOUT_CHECK", + "source": { + "format": "json", + "files": [ + "meta.checks.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[11]['validator.atLeastOne']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json b/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json new file mode 100644 index 0000000000..1c2125b14a --- /dev/null +++ b/fixtures/conformance/error-db-check-cross-field/input/meta.checks.json @@ -0,0 +1,26 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Visit", + "children": [ + { "source.rdb": { "@table": "visits" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "kind" } }, + { "field.string": { "name": "email" } }, + { "field.string": { "name": "phone" } }, + { "field.timestamp": { "name": "startsAt" } }, + { "field.timestamp": { "name": "endsAt" } }, + { "identity.primary": { "name": "pk", "@fields": "id" } }, + { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": false } }, + { "validator.requiredWhen": { "name": "clinicEmail", "@field": "email", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, + { "validator.presentIff": { "name": "clinicStart", "@field": "startsAt", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, + { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": false, "@constraintName": "visits_contact_ok" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/validator-db-check/expected.json b/fixtures/conformance/validator-db-check/expected.json index b4fb1458fc..c7dcd836f2 100644 --- a/fixtures/conformance/validator-db-check/expected.json +++ b/fixtures/conformance/validator-db-check/expected.json @@ -99,7 +99,7 @@ { "validator.comparison": { "name": "window", - "@dbCheck": false, + "@dbCheck": true, "@left": "startsAt", "@op": "lte", "@right": "endsAt" @@ -108,7 +108,7 @@ { "validator.requiredWhen": { "name": "clinicEmail", - "@dbCheck": false, + "@dbCheck": true, "@equals": "clinic", "@field": "email", "@when": "kind" @@ -117,7 +117,7 @@ { "validator.presentIff": { "name": "clinicStart", - "@dbCheck": false, + "@dbCheck": true, "@equals": "clinic", "@field": "startsAt", "@when": "kind" @@ -126,7 +126,7 @@ { "validator.atLeastOne": { "name": "contact", - "@dbCheck": false, + "@dbCheck": true, "@fields": [ "email", "phone" diff --git a/fixtures/conformance/validator-db-check/input/meta.checks.json b/fixtures/conformance/validator-db-check/input/meta.checks.json index 6736ec95f0..87707ea740 100644 --- a/fixtures/conformance/validator-db-check/input/meta.checks.json +++ b/fixtures/conformance/validator-db-check/input/meta.checks.json @@ -20,10 +20,10 @@ { "field.timestamp": { "name": "startsAt" } }, { "field.timestamp": { "name": "endsAt" } }, { "identity.primary": { "name": "pk", "@fields": "id" } }, - { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": false } }, - { "validator.requiredWhen": { "name": "clinicEmail", "@field": "email", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, - { "validator.presentIff": { "name": "clinicStart", "@field": "startsAt", "@when": "kind", "@equals": "clinic", "@dbCheck": false } }, - { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": false } } + { "validator.comparison": { "name": "window", "@left": "startsAt", "@op": "lte", "@right": "endsAt", "@dbCheck": true } }, + { "validator.requiredWhen": { "name": "clinicEmail", "@field": "email", "@when": "kind", "@equals": "clinic", "@dbCheck": true } }, + { "validator.presentIff": { "name": "clinicStart", "@field": "startsAt", "@when": "kind", "@equals": "clinic", "@dbCheck": true } }, + { "validator.atLeastOne": { "name": "contact", "@fields": ["email", "phone"], "@dbCheck": true } } ] } } diff --git a/fixtures/metamodel-docs/expected/types/validator.md b/fixtures/metamodel-docs/expected/types/validator.md index 9e147b28af..dd5014751e 100644 --- a/fixtures/metamodel-docs/expected/types/validator.md +++ b/fixtures/metamodel-docs/expected/types/validator.md @@ -45,7 +45,7 @@ Cardinality of presence: at least one of the named fields (@fields) must be pres | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@fields` | string[] | yes | | | metaobjects-core-types | Names of the candidate fields; at least one must be present. | | `@max` | int | no | | | metaobjects-core-types | The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE). | @@ -86,7 +86,7 @@ Cross-field ordering: requires two sibling fields of the owning entity stand in | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@left` | string | yes | | | metaobjects-core-types | Name of the left-hand field of the owning entity. | | `@op` | string | yes | | `gt`, `gte`, `lt`, `lte`, `ne`, `eq` | metaobjects-core-types | Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=). | | `@right` | string | yes | | | metaobjects-core-types | Name of the right-hand field of the owning entity. | @@ -108,7 +108,7 @@ Bounds string length / collection size via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -129,7 +129,7 @@ Bounds a numeric value's magnitude via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -153,7 +153,7 @@ Biconditional presence: the target field (@field) is present (NOT NULL) if and o | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; @field is present exactly when @when equals this. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field whose presence is governed by the condition. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field. | @@ -175,7 +175,7 @@ Requires the value match a regular expression (@pattern). | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@pattern` | string | no | | | metaobjects-core-types | Regular expression the value must match. | @@ -216,7 +216,7 @@ One-directional conditional presence: when the gating field (@when) equals @equa | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; when @when equals this, @field must be present. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field that becomes required when the condition holds. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field whose value triggers the requirement. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 8890375c42..2540fb9dae 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -5036,7 +5036,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "fields", @@ -5103,7 +5103,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "left", @@ -5155,7 +5155,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "max", @@ -5192,7 +5192,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "max", @@ -5237,7 +5237,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "equals", @@ -5281,7 +5281,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "max", @@ -5341,7 +5341,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "equals", diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index 7c27152db5..4db2c691bb 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -80,9 +80,10 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co if (check is not null) checks.Add(Named(check, v)); } } + // A cross-field validator always keeps its CHECK: it is enforced nowhere else, and the loader + // refuses @dbCheck: false on one (ERR_CROSS_FIELD_WITHOUT_CHECK). foreach (var v in entity.Validators()) { - if (OptedOut(v)) continue; if (CrossFieldCheck(v, entity, table, strategy, dialect) is { } check) checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); } diff --git a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs index 5e5763dc81..3127cf22aa 100644 --- a/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs +++ b/server/csharp/MetaObjects/Core/Validator/ValidatorConstants.cs @@ -56,6 +56,12 @@ public static class ValidatorConstants /// A CHECK-generating validator or field.enum (db provider): false generates no database CHECK. Absent: true. public const string VALIDATOR_ATTR_DB_CHECK = "dbCheck"; + /// The cross-field validators: enforced only by their CHECK, so @dbCheck: false is refused on them. + public static readonly IReadOnlyList CROSS_FIELD_VALIDATOR_SUBTYPES_FOR_DB_CHECK = + [ + VALIDATOR_SUBTYPE_COMPARISON, VALIDATOR_SUBTYPE_REQUIRED_WHEN, VALIDATOR_SUBTYPE_PRESENT_IFF, VALIDATOR_SUBTYPE_AT_LEAST_ONE, + ]; + /// The validators meta migrate renders as a CHECK (and so may carry @constraintName): /// numeric, length, regex and the cross-field ones. required is NOT NULL; array and base have none. public static readonly IReadOnlyList CHECK_VALIDATOR_SUBTYPES = diff --git a/server/csharp/MetaObjects/Errors.cs b/server/csharp/MetaObjects/Errors.cs index 2eb5871eb4..7da6d23113 100644 --- a/server/csharp/MetaObjects/Errors.cs +++ b/server/csharp/MetaObjects/Errors.cs @@ -310,6 +310,8 @@ public enum ErrorCode ERR_SEQUENCE_START_OUT_OF_RANGE, // A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + // A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. + ERR_CROSS_FIELD_WITHOUT_CHECK, } /// diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index af76acfceb..ac63829943 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2542,8 +2542,10 @@ public static IReadOnlyList ValidateIdentitySequence(MetaData root) // --------------------------------------------------------------------------- // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the - // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). Read RESOLVING (ADR-0039), reported on - // each node that declares either of the two itself. Mirrors TS validateDbCheck. + // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). A cross-field validator is enforced only + // by its CHECK, so @dbCheck: false on one is refused (ERR_CROSS_FIELD_WITHOUT_CHECK), the one + // error such a node gets. Read RESOLVING (ADR-0039), reported on each node that declares either + // of the two itself. Mirrors TS validateDbCheck. // --------------------------------------------------------------------------- public static IReadOnlyList ValidateDbCheck(MetaData root) { @@ -2554,10 +2556,20 @@ void Visit(MetaData node, string? owner) { var checkedNode = (node.Type == TYPE_VALIDATOR && MetaObjects.Core.Validator.ValidatorConstants.CHECK_VALIDATOR_SUBTYPES.Contains(node.SubType)) || (node.Type == TYPE_FIELD && node.SubType == FIELD_SUBTYPE_ENUM); - if (checkedNode && (node.OwnAttr(dbCheck) is not null || node.OwnAttr(constraintName) is not null) - && node.Attr(dbCheck) is false && node.Attr(constraintName) is string { Length: > 0 } name) + var label = $"{node.Type}.{node.SubType} \"{(owner is null ? "" : owner + ".")}{node.Name}\""; + var declares = checkedNode && (node.OwnAttr(dbCheck) is not null || node.OwnAttr(constraintName) is not null); + if (declares && node.Attr(dbCheck) is false && node.Type == TYPE_VALIDATOR + && MetaObjects.Core.Validator.ValidatorConstants.CROSS_FIELD_VALIDATOR_SUBTYPES_FOR_DB_CHECK.Contains(node.SubType)) + { + // A cross-field validator has no app-level enforcement: its CHECK is the rule. + errors.Add(new MetaError( + $"{label} sets @dbCheck: false, but this validator is enforced only by its CHECK, so the rule would be " + + "enforced nowhere. Remove the validator, or remove @dbCheck: false.", + ErrorCode.ERR_CROSS_FIELD_WITHOUT_CHECK, + Envelope: node.Source)); + } + else if (declares && node.Attr(dbCheck) is false && node.Attr(constraintName) is string { Length: > 0 } name) { - var label = $"{node.Type}.{node.SubType} \"{(owner is null ? "" : owner + ".")}{node.Name}\""; errors.Add(new MetaError( $"{label} sets @dbCheck: false and @constraintName \"{name}\"; with no CHECK there is nothing for the name to name. " + "Remove @constraintName, or remove @dbCheck: false.", diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index 8a4cb9df0f..90fb061224 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -116,7 +116,7 @@ public static class DbSchema Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false, - Description: "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider."); + Description: "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider."); /// @dbCheck on a field.enum — false generates no membership CHECK. public static readonly AttrSchema EnumDbCheckSchema = new AttrSchema( diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index 47ab036326..fef802cf23 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -72,7 +72,7 @@ "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, - { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { diff --git a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java index 0c97e6542c..1259b8cf4f 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java +++ b/server/java/metadata/src/main/java/com/metaobjects/ErrorCode.java @@ -301,6 +301,8 @@ public enum ErrorCode { ERR_SEQUENCE_START_OUT_OF_RANGE, /** A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. */ ERR_CONSTRAINT_NAME_WITHOUT_CHECK, + /** A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. */ + ERR_CROSS_FIELD_WITHOUT_CHECK, /** @storage was set on a field that has no @objectRef. */ ERR_STORAGE_WITHOUT_OBJECT_REF, diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index b0f2f6ed2b..9c5fd64d6c 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -2570,10 +2570,15 @@ static void validateIdentitySequence(MetaRoot root, List out) // ========================================================================= // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the - // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). Read RESOLVING (ADR-0039), reported on - // each node that declares either of the two itself. Mirrors TS validateDbCheck. + // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). A cross-field validator is enforced only + // by its CHECK, so @dbCheck: false on one is refused (ERR_CROSS_FIELD_WITHOUT_CHECK), the one + // error such a node gets. Read RESOLVING (ADR-0039), reported on each node that declares either + // of the two itself. Mirrors TS validateDbCheck. // ========================================================================= + private static final java.util.Set CROSS_FIELD_DB_CHECK_SUBTYPES = java.util.Set.of( + "comparison", "requiredWhen", "presentIff", "atLeastOne"); + private static final java.util.Set DB_CHECK_VALIDATOR_SUBTYPES = java.util.Set.of( "numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"); @@ -2588,12 +2593,19 @@ private static void visitDbCheck(MetaData node, String owner, List None # @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no # database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the -# node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). Read RESOLVING (ADR-0039), reported on -# each node that declares either of the two itself. Mirrors TS validateDbCheck. +# node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). A cross-field validator is enforced only by +# its CHECK, so @dbCheck: false on one is refused (ERR_CROSS_FIELD_WITHOUT_CHECK), the one error +# such a node gets. Read RESOLVING (ADR-0039), reported on each node that declares either of the +# two itself. Mirrors TS validateDbCheck. def _validate_db_check(root: MetaData, errors: list[MetaError]) -> None: from ..meta.core.field import field_constants as fc from ..meta.core.validator import validator_constants as vc @@ -3786,8 +3788,20 @@ def visit(node: MetaData, owner: str | None) -> None: declares = node.attr(vc.VALIDATOR_ATTR_DB_CHECK) is not None or node.attr(vc.VALIDATOR_ATTR_CONSTRAINT_NAME) is not None if checked and declares: name = node.get_meta_attr(vc.VALIDATOR_ATTR_CONSTRAINT_NAME) - if node.get_meta_attr(vc.VALIDATOR_ATTR_DB_CHECK) is False and isinstance(name, str) and name: - prefix = f"{owner}." if owner is not None else "" + off = node.get_meta_attr(vc.VALIDATOR_ATTR_DB_CHECK) is False + prefix = f"{owner}." if owner is not None else "" + if off and node.type == TYPE_VALIDATOR and node.sub_type in vc.CROSS_FIELD_VALIDATOR_SUBTYPES: + # A cross-field validator has no app-level enforcement: its CHECK is the rule. + errors.append(MetaError( + code=ErrorCode.ERR_CROSS_FIELD_WITHOUT_CHECK, + message=( + f'{node.type}.{node.sub_type} "{prefix}{node.name}" sets @dbCheck: false, but this validator ' + "is enforced only by its CHECK, so the rule would be enforced nowhere. Remove the validator, " + "or remove @dbCheck: false." + ), + envelope=node.source, + )) + elif off and isinstance(name, str) and name: errors.append(MetaError( code=ErrorCode.ERR_CONSTRAINT_NAME_WITHOUT_CHECK, message=( diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index 761b1f24ce..e855a49959 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -218,7 +218,7 @@ name=vc.VALIDATOR_ATTR_DB_CHECK, value_type=ATTR_SUBTYPE_BOOLEAN, required=False, - description="false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", + description="false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", ) # The validators meta migrate renders as a CHECK: required is NOT NULL; array and base have none. _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME = ( diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index 47ab036326..fef802cf23 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -72,7 +72,7 @@ "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, - { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { diff --git a/server/typescript/packages/metadata/src/errors.ts b/server/typescript/packages/metadata/src/errors.ts index 13f358a147..355d6d19cc 100644 --- a/server/typescript/packages/metadata/src/errors.ts +++ b/server/typescript/packages/metadata/src/errors.ts @@ -160,6 +160,8 @@ export const ERROR_CODES = [ "ERR_SEQUENCE_START_OUT_OF_RANGE", // A CHECK-generating validator or field.enum sets @dbCheck: false and @constraintName. "ERR_CONSTRAINT_NAME_WITHOUT_CHECK", + // A cross-field validator (enforced only by its CHECK) sets @dbCheck: false. + "ERR_CROSS_FIELD_WITHOUT_CHECK", "ERR_STORAGE_WITHOUT_OBJECT_REF", // ADR-0013 — a field.object REQUIRES @objectRef (open/untyped JSON uses // the physical @dbColumnType: jsonb escape hatch on field.string instead). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index c7c408ddd7..32bb8f6a34 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -2062,6 +2062,8 @@ export function validateIdentitySequence(root: MetaData): ParseError[] { // @dbCheck: false (db provider) asks a CHECK-generating validator or a field.enum for no // database CHECK; @constraintName names that CHECK. Together there is nothing to name, so the // node is refused (ERR_CONSTRAINT_NAME_WITHOUT_CHECK) rather than one of them silently ignored. +// A cross-field validator is enforced only by its CHECK, so @dbCheck: false on one is refused +// (ERR_CROSS_FIELD_WITHOUT_CHECK), and that is the one error such a node gets. // Read RESOLVING (ADR-0039), reported on each node that declares either of the two itself. // --------------------------------------------------------------------------- @@ -2076,8 +2078,15 @@ export function validateDbCheck(root: MetaData): ParseError[] { || (node.type === TYPE_FIELD && node.subType === FIELD_SUBTYPE_ENUM); if (checked && (node.ownAttr(VALIDATOR_ATTR_DB_CHECK) !== undefined || node.ownAttr(VALIDATOR_ATTR_CONSTRAINT_NAME) !== undefined)) { const name = node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); - if (node.attr(VALIDATOR_ATTR_DB_CHECK) === false && typeof name === "string" && name.length > 0) { - const label = `${node.type}.${node.subType} "${owner !== undefined ? `${owner}.` : ""}${node.name}"`; + const label = `${node.type}.${node.subType} "${owner !== undefined ? `${owner}.` : ""}${node.name}"`; + if (node.attr(VALIDATOR_ATTR_DB_CHECK) === false && CROSS_FIELD_VALIDATOR_SUBTYPES.includes(node.subType)) { + // A cross-field validator has no app-level enforcement: its CHECK is the rule. + errors.push(new ParseError( + `${label} sets @dbCheck: false, but this validator is enforced only by its CHECK, so the rule would be ` + + `enforced nowhere. Remove the validator, or remove @dbCheck: false.`, + { code: "ERR_CROSS_FIELD_WITHOUT_CHECK", source: node.source }, + )); + } else if (node.attr(VALIDATOR_ATTR_DB_CHECK) === false && typeof name === "string" && name.length > 0) { errors.push(new ParseError( `${label} sets @dbCheck: false and @constraintName "${name}"; with no CHECK there is nothing for the name to name. ` + `Remove @constraintName, or remove @dbCheck: false.`, diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index e56d546178..798fbe975c 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -302,7 +302,7 @@ export const DB_DEFINITION: ProviderDefinition = { "name": "dbCheck", "min": 0, "max": 1, - "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 87a5ea2588..cd822da951 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -960,8 +960,9 @@ function buildChecks( } } // Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne). + // A cross-field validator always keeps its CHECK: it is enforced nowhere else, and the loader + // refuses @dbCheck: false on one (ERR_CROSS_FIELD_WITHOUT_CHECK). for (const v of entity.validators()) { - if (checkOptedOut(v)) continue; const check = crossFieldCheck(v, entity, tableName, strategy, dialect); if (check) checks.push(withDeclaredName(withCondition(check, v, entity, strategy, dialect), v)); } diff --git a/site-reference/types/validator.html b/site-reference/types/validator.html index db6bff86ea..dc0ff80c07 100644 --- a/site-reference/types/validator.html +++ b/site-reference/types/validator.html @@ -131,7 +131,7 @@

    validator.atLeastOne

    - + @@ -234,7 +234,7 @@

    validator.comparison

    - + @@ -299,7 +299,7 @@

    validator.length

    - + @@ -355,7 +355,7 @@

    validator.numeric

    - + @@ -421,7 +421,7 @@

    validator.presentIff

    - + @@ -486,7 +486,7 @@

    validator.regex

    - + @@ -569,7 +569,7 @@

    validator.requiredWhen

    - + diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index 47ab036326..fef802cf23 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -72,7 +72,7 @@ "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @fields metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @left metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @equals metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max metaobjects-dbfalse: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @equals
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, - { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this validator generates no database CHECK (meta migrate and a generated EF model leave it out). A numeric, length or regex validator is still enforced on every write by the generated app-level validators; a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so on one of those false leaves the rule enforced nowhere. Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { From 50386c4c62bd4cef83095a9fe5926f401393abdc Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Wed, 11 Nov 2026 19:32:09 -0500 Subject: [PATCH 165/267] fix(codegen-ts): the Drizzle enum CHECK honours @dbCheck and @constraintName (I1) The column mapper built a field.enum's membership CHECK on its own and never read @dbCheck, so an enum with @dbCheck: false still got
    __chk in the Drizzle table: a CHECK meta migrate no longer creates, which drizzle-kit push would re-add. It now skips the CHECK on @dbCheck: false (resolving), as migrate-ts's buildChecks does. The same table's check() also took the derived name over a declared @constraintName; it now takes the declared one. No other emitter builds CHECKs on its own: Prisma reads migrate-ts's expected schema, C# has CheckConstraints, and the Java, Kotlin and Python ports emit none. Test: drizzle-enum-db-check (postgres and sqlite; the Drizzle CHECK names equal meta migrate's), watched red without the guard. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 39 +++++--- .../OrphanSweepMarkedTests.cs | 93 ------------------- .../packages/codegen-ts/src/column-mapper.ts | 7 +- .../src/templates/drizzle-schema.ts | 13 ++- .../test/drizzle-enum-db-check.test.ts | 57 ++++++++++++ 5 files changed, 100 insertions(+), 109 deletions(-) delete mode 100644 server/csharp/MetaObjects.Codegen.Tests/OrphanSweepMarkedTests.cs create mode 100644 server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b81ae7667..26b8051eb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,8 +27,8 @@ vocabulary; upgrade every port together. validator (`numeric`, `length`, `regex`, `comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) or a `field.enum` takes an optional db-provider boolean `@dbCheck`, default `true`. With `false` on a `numeric`, `length` or `regex` validator or a `field.enum`, `meta migrate`, - `meta verify --db`, the Prisma schema's CHECKs and the C# EF context's declared CHECKs leave that - one node's CHECK out; every other CHECK on the table, and `migrate.checks.skipRedundant`, are + `meta verify --db`, the Prisma schema's CHECKs, the Drizzle schema's enum CHECK and the C# EF + context's declared CHECKs leave that one node's CHECK out; every other CHECK on the table, and `migrate.checks.skipRedundant`, are unchanged. It is for a column whose legacy rows break a rule: a CHECK added `NOT VALID` still refuses an UPDATE of such a row. The generated app-level validation is unchanged, so the validator and an enum's members still hold every write. A cross-field validator is enforced only @@ -41,12 +41,17 @@ vocabulary; upgrade every port together. `@dbCheck: false` is proposed for dropping by the next `meta migrate` (`--allow drop-check` on Postgres), and by the next EF migration a C# model scaffolds. -- **C#: an orphan sweep for a self-hosted runner with no hash manifest (G5).** A runner that - calls `CodegenRunner.Run` without `GenStateDir` swept nothing, so a layout change (R39) left the - old files behind. `OrphanSweep.SweepMarked(dirs, emitted)`, called after a run of the whole list - with `RunResult.EmittedPaths` (new), deletes each file under `dirs` that carries the - `` marker in its first lines and that no generator emitted, and returns them. - Opt-in: `Run` never calls it, and nothing else changes. +- **C#: an orphan sweep for a self-hosted runner that makes several runs (G5).** A runner that + calls `CodegenRunner.Run` once per target could not sweep: `SweepOrphans` sweeps one run's + directories, where another run's files look orphaned, and a runner with no `GenStateDir` had no + manifest at all, so a layout change (R39) left the old files behind. `RunResult.EmittedPaths` (new) + holds every path a run emitted; the runner gives each run the same `GenStateDir`, then calls + `OrphanSweep.Sweep` once with the runs' directories and the union of their paths. Only files the + manifest records with a matching hash are deleted, and edited ones are refused by name. New + `Sweep` options: `dryRun`, and `reportUnrecorded`, which lists (never deletes) files carrying + MetaObjects' `Generated by MetaObjects` header that a manifest-less run wrote. The sweep now + compares paths case-insensitively, `meta gen`'s own sweep included, so a case-only rename on + macOS or Windows keeps its file. The default behaviour is otherwise unchanged. - **Kind-1 vocabulary: cross-port, implemented in some ports so far (ruling R40).** A registry type or attr may name the ports that implement it so far (`"implementedIn": ["typescript"]` on @@ -563,11 +568,19 @@ vocabulary; upgrade every port together. `GetProperty("").SetComment(...)` on its column; any other mapping gets no comment line and a warning naming the field (`meta migrate` still writes the comment). -- **Fix, C#: a narrowed `EntityGenerator` declares only the shared enums it uses (G2).** With - `Include`, the materialized shared enums were still collected from every in-scope object, so two - entries splitting the model both declared each one. A narrowed entry now declares the enums of - the objects it accepts and of every value object it emits beyond them; an un-narrowed run emits - the same set as before. +- **Fix, TypeScript: the Drizzle schema's enum CHECK takes the field's `@constraintName`.** The + table's `check()` was always named `
    __chk`, so an enum whose CHECK `meta migrate` + names by `@constraintName` reported drift and `drizzle-kit push` proposed a second CHECK. + +- **Fix, C#: narrowed `EntityGenerator` entries declare each shared enum once (G2).** With + `Include`, the materialized shared enums were still collected from every in-scope object, so every + entry splitting the model declared all of them (`CS0101` where two outputs build together). A + narrowed entry now declares only the enums used by the objects it accepts and the value objects it + emits beyond them, and an enum several entries use is declared by one: the entry that emits its + first consumer by resolution key. Each entry reaches that answer from the model alone, in its own + run. An enum whose first consumer no entry emits is declared by none; give that object an entry, + or use an un-narrowed entry, which declares every enum as before. Placing an enum in a project of + its own choosing is G3, not built. - **Fix, TypeScript docs: an identity reference's target links to its page (G4).** The Identity section printed ``**Reference:** `x` → `Target` `` unlinked, bare or package-qualified. The target diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepMarkedTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepMarkedTests.cs deleted file mode 100644 index e678bb7559..0000000000 --- a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepMarkedTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -// G5, rc.20: a self-hosted runner that keeps no hash manifest (no GenConfig.GenStateDir) has -// nothing the manifest sweep can read, so a layout change (R39) left the old files behind. -// OrphanSweep.SweepMarked is its opt-in: after a run of the whole list, a file under the run's -// directories that carries the generated marker and that no generator emitted is deleted. A run -// that does not call it deletes nothing, as before. - -using MetaObjects.Loader; -using MetaObjects.Meta; -using Xunit; - -namespace MetaObjects.Codegen.Tests; - -public sealed class OrphanSweepMarkedTests : IDisposable -{ - private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-marked-" + Guid.NewGuid().ToString("N")); - private string Out => Path.Combine(_root, "gen"); - - public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } - - /// One file per value object, under its package directory when . - private sealed class PerValue(bool byPackage) : IGenerator - { - public string Name => "values"; - public IEnumerable Generate(GenContext ctx) => - ctx.Root.Objects().Select(o => new EmittedFile( - (byPackage ? "acme/" : "") + $"{o.Name}.g.cs", $"// \npublic sealed class {o.Name} {{ }}\n")); - } - - private static MetaRoot Root(params string[] values) - { - var children = string.Join(",", values.Select(v => $$"""{ "object.value": { "name": "{{v}}", "children": [ { "field.string": { "name": "x" } } ] } }""")); - var r = new MetaDataLoader().Load([new InMemoryStringSource($$"""{ "metadata.root": { "package": "acme", "children": [ {{children}} ] } }""", id: "m.json")]); - Assert.Empty(r.Errors); - return r.Root; - } - - private CodegenRunner.RunResult Run(MetaRoot root, bool byPackage, string? outDir = null) => - CodegenRunner.Run(new GenConfig { OutDir = outDir ?? Out, Namespace = "Acme" }, root, [new PerValue(byPackage)]); - - private string At(string rel) => Path.Combine(Out, rel); - - [Fact] - public void A_layout_change_leaves_the_old_files_unless_the_runner_sweeps() - { - Run(Root("Alpha", "Beta"), byPackage: false); - Assert.True(File.Exists(At("Alpha.g.cs"))); - - // The layout moves every file; without the sweep the flat ones stay, as before. - var moved = Run(Root("Alpha", "Beta"), byPackage: true); - Assert.True(File.Exists(At("acme/Alpha.g.cs"))); - Assert.True(File.Exists(At("Alpha.g.cs"))); - - var removed = OrphanSweep.SweepMarked([Out], moved.EmittedPaths); - Assert.Equal([Path.GetFullPath(At("Alpha.g.cs")), Path.GetFullPath(At("Beta.g.cs"))], removed); - Assert.False(File.Exists(At("Alpha.g.cs"))); - Assert.True(File.Exists(At("acme/Alpha.g.cs"))); - Assert.True(File.Exists(At("acme/Beta.g.cs"))); - } - - [Fact] - public void A_file_without_the_marker_and_the_metaobjects_directory_are_never_touched() - { - Directory.CreateDirectory(At(".metaobjects")); - File.WriteAllText(At(".metaobjects/state.g.cs"), "// \n"); - Directory.CreateDirectory(Out); - File.WriteAllText(At("Handwritten.cs"), "public partial class Alpha { }\n"); - // The marker past the first lines is a mention, not a header. - File.WriteAllText(At("Notes.cs"), "// one\n// two\n// three\n// four\n// five\n// six \n"); - var result = Run(Root("Alpha"), byPackage: false); - - Assert.Empty(OrphanSweep.SweepMarked([Out], result.EmittedPaths)); - Assert.True(File.Exists(At(".metaobjects/state.g.cs"))); - Assert.True(File.Exists(At("Handwritten.cs"))); - Assert.True(File.Exists(At("Notes.cs"))); - Assert.True(File.Exists(At("Alpha.g.cs"))); - } - - [Fact] - public void A_runner_of_several_runs_sweeps_their_union() - { - // A second run's directory nested in the first: swept alone, the first would delete its files. - var inner = Path.Combine(Out, "inner"); - var outer = Run(Root("Alpha"), byPackage: false); - var nested = Run(Root("Beta"), byPackage: false, outDir: inner); - File.WriteAllText(At("Stale.g.cs"), "// \n"); - - var emitted = outer.EmittedPaths.Union(nested.EmittedPaths).ToHashSet(StringComparer.Ordinal); - var removed = OrphanSweep.SweepMarked([Out, inner], emitted); - Assert.Equal([Path.GetFullPath(At("Stale.g.cs"))], removed); - Assert.True(File.Exists(Path.Combine(inner, "Beta.g.cs"))); - Assert.True(File.Exists(At("Alpha.g.cs"))); - } -} diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index edde17c572..446f709a18 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -47,6 +47,7 @@ import { AGG_ALL, AGG_COLLECT, resolveEnumMaxLength, + VALIDATOR_ATTR_DB_CHECK, } from "@metaobjectsdev/metadata"; import { columnNameFromField } from "./naming.js"; import { enumValues, intValueMapOf, intValueForMember } from "./enum-meta.js"; @@ -1030,8 +1031,10 @@ export function mapColumnType( if (dollarTypeRef !== undefined) result.dollarTypeRef = dollarTypeRef; if (leadingComment !== undefined) result.leadingComment = leadingComment; - // Enum fields: emit a CHECK constraint listing the valid member values. - if (subType === FIELD_SUBTYPE_ENUM && !isArray) { + // Enum fields: emit a CHECK constraint listing the valid member values — unless the enum opts + // out (`@dbCheck: false`, ADR-0039 resolving), exactly as migrate-ts's buildChecks decides, or + // `drizzle-kit push` would re-add the CHECK `meta migrate` leaves out. + if (subType === FIELD_SUBTYPE_ENUM && !isArray && field.attr(VALIDATOR_ATTR_DB_CHECK) !== false) { const values = enumValues(field); if (values !== undefined && values.length > 0) { const intMap = intValueMapOf(field); diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index d21704d906..010ef5cf6a 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -26,7 +26,7 @@ import { dialectModule } from "../dialect-module.js"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "../names.js"; -import { resolveTableSchema } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; @@ -194,6 +194,17 @@ export function renderDrizzleSchema( const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts new file mode 100644 index 0000000000..ebe14ff663 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-db-check.test.ts @@ -0,0 +1,57 @@ +// rc.20 @dbCheck: an enum with `@dbCheck: false` gets no membership CHECK in the Drizzle table, as +// `meta migrate` creates none — else `drizzle-kit push` would re-add the CHECK the model opted out +// of. A sibling enum keeps its own, and the enum's values still type the column. +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { renderDrizzleSchema } from "../src/templates/drizzle-schema.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import { buildExpectedSchema } from "@metaobjectsdev/migrate-ts/expected"; +import type { Dialect } from "../src/metaobjects-config.js"; + +async function load() { + const json = JSON.stringify({ "metadata.root": { children: [ + { "object.entity": { name: "Provider", children: [ + { "source.rdb": { name: "src", "@table": "providers" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "state", "@values": ["OPEN", "SHUT"], "@dbCheck": false } }, + { "field.enum": { name: "kind", "@values": ["CLINIC", "LAB"] } }, + { "field.enum": { name: "tier", "@values": ["GOLD", "SILVER"], "@constraintName": "CK_Providers_Tier" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ] } }, + ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + return res.root; +} + +async function emit(dialect: Dialect) { + const root = await load(); + const ctx = makeRenderContext({ + dialect, loadedRoot: root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(root), relationMap: buildRelationMap(root), + }); + return renderDrizzleSchema(root.findObject("Provider")!, ctx).toString(); +} + +describe("Drizzle: @dbCheck: false on a field.enum", () => { + for (const dialect of ["postgres", "sqlite"] as const) { + test(`${dialect}: the opted-out enum declares no CHECK; its sibling keeps one`, async () => { + const out = await emit(dialect); + expect(out).not.toContain("providers_state_chk"); + expect(out).toContain("providers_kind_chk"); + // A declared @constraintName names the CHECK, as meta migrate names it. + expect(out).toContain('"CK_Providers_Tier"'); + expect(out).not.toContain("providers_tier_chk"); + // The column is still the enum's: only the database CHECK is left out. + expect(out).toContain('"OPEN"'); + }); + + test(`${dialect}: the Drizzle CHECKs are the ones meta migrate creates`, async () => { + const root = await load(); + const migrate = buildExpectedSchema(root, { dialect }).tables.find((t) => t.name === "providers")!; + expect(migrate.checks.map((c) => c.name)).toEqual(["providers_kind_chk", "CK_Providers_Tier"]); + }); + } +}); From f82f75b225579a0d0f369b67c1242b2cfa0cde32 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Wed, 11 Nov 2026 19:32:11 -0500 Subject: [PATCH 166/267] fix(csharp): an enum several narrowed entries use is declared by one of them (G2) A shared enum used by objects of two Include-narrowed EntityGenerator entries was declared by both (CS0101 where the outputs build together). Its home is now its first consumer by resolution key, among the objects the project generates and the imported value objects the run emits; only the entry that emits the home declares it. Each entry decides from the model alone, so separate runs agree. Un-narrowed runs are unchanged. Test: GeneratorIncludeTests.An_enum_both_narrowed_entries_use_is_declared_once (both entries' output compiles together), watched red. Co-Authored-By: Claude Opus 5.5 --- .../GeneratorIncludeTests.cs | 44 +++++++++++++++++++ .../Generators/EntityGenerator.cs | 21 ++++++++- 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs index 51758bc4c9..8551e09740 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs @@ -160,5 +160,49 @@ public void A_narrowed_entry_declares_only_the_shared_enums_it_uses() Assert.DoesNotContain("OrderStatus.g.cs", customers); Assert.DoesNotContain("Mood.g.cs", customers); } + + // G2, rc.20 fix round 1: an enum both narrowed entries use is declared by exactly one of them, + // the one that emits its first consumer by resolution key, so their outputs build together. + private const string BothUse = """ + { "metadata.root": { "package": "acme", "children": [ + { "field.enum": { "name": "Level", "abstract": true, "@values": ["LOW", "HIGH"] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "level", "extends": "Level" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "level", "extends": "Level" } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + [Fact] + public void An_enum_both_narrowed_entries_use_is_declared_once() + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(BothUse, id: "both.json")]); + Assert.Empty(r.Errors); + // One run, one claim registry, as two entries of one generator list share. + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated" }, + }; + var orders = new EntityGenerator { Include = o => o.Name is "Order" }.Generate(ctx).ToList(); + var customers = new EntityGenerator { Include = o => o.Name is "Customer" }.Generate(ctx).ToList(); + // Customer sorts first (acme::Customer < acme::Order), so its entry declares Level. + Assert.Contains(customers, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + Assert.DoesNotContain(orders, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + // Order still names it. + Assert.Contains("global::Acme.Level", Assert.Single(orders, f => f.Path.EndsWith("Order.g.cs", StringComparison.Ordinal)).Content); + var errors = PackageNamespaceTests.CompileErrors(orders.Concat(customers)); + Assert.True(errors.Count == 0, "the two entries' output should build together, but got:\n" + string.Join("\n", errors)); + // Un-narrowed, it is declared as before. + Assert.Single(new EntityGenerator().Generate(ctx), f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 2dc471af09..b847ff86d9 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -1085,7 +1085,8 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I var importedShapes = valueShapes.Where(vo => !ctx.Root.InScope(vo)).ToList(); // G2 (rc.20): a narrowed run (Include) declares the enums of the objects it accepts and of // every value object it emits beyond them (a reached closure POCO), not the whole model's; - // another entry declares the rest. Un-narrowed, the set is unchanged. + // another entry declares the rest, and an enum both use is declared once (below). + // Un-narrowed, the set is unchanged. var reached = ctx.Scope is null ? importedShapes : valueShapes.ToList(); foreach (var shared in Fr019SharedEnum.CollectSharedEnums(ctx.Root, reached, ctx.Scope)) @@ -1095,6 +1096,13 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I var files = new List(); foreach (var e in Fr019SharedEnum.MaterializedSharedEnums(ctx.Root, reached, ctx.Scope)) { + // G2 (rc.20, fix round 1): an enum two narrowed entries both use is declared by ONE of them, + // so the entries' outputs build together (no CS0101). Decided from the model alone, so each + // entry reaches the same answer in its own run: the enum's home is its first consumer by + // resolution key, and the entry that emits that object declares it. + if (ctx.Scope is { } scope && SharedEnumHome(ctx, e, importedShapes) is { } home + && !scope(home) && !valueShapes.Contains(home)) + continue; // rc.19 R65: a shared enum is declared in its package's namespace; consumers name it // global::-qualified (Fr019SharedEnum.SharedEnumTypeReference). var ns = Fr019SharedEnum.MaterializedNamespace(e, ctx.Config); @@ -1115,6 +1123,17 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I return files; } + /// + /// The object a narrowed run's shared enum is declared beside (G2): the first, by resolution key, + /// of every object this project generates (and every imported value object this run emits) that has + /// a field of the enum. Null when nothing consumes it. + /// + private static MetaObject? SharedEnumHome(GenContext ctx, SharedEnum e, IReadOnlyList importedShapes) => + ctx.Root.Objects().Where(ctx.Root.InScope).Concat(importedShapes) + .Where(o => o.Fields().Any(f => Fr019SharedEnum.SharedEnumForField(f)?.Name == e.Name)) + .OrderBy(o => o.ResolutionKey(), StringComparer.Ordinal) + .FirstOrDefault(); + /// /// A shared enum's declaration: the declaration's doc attrs as the type's XML doc, each /// member's @intValueMap integer as its value, and each member's @enumDoc text as From d0180824a41301590f96bacc5b539b82297e7f56 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Wed, 11 Nov 2026 19:32:13 -0500 Subject: [PATCH 167/267] docs: rc.20 fix round 1 minors (M1, M3, M4, M5, M6) - The G2 CHANGELOG bullet says what is fixed and what is not (an enum whose first consumer no entry emits; placement is G3). - The @dbCheck validator description leads with the per-kind rule, so validator.comparison's table no longer opens "this numeric, length or regex validator"; the canonical registry, metamodel docs and site reference are regenerated, and the three db.json copies resynced. - ERR_CONSTRAINT_NAME_WITHOUT_CHECK's description names only the kinds it can fire on. - Two upstream test comments no longer name an adopter. - G4 tests: a bare reference keeps its spelling and links; a target the tree does not hold stays plain text in the Identity section. Co-Authored-By: Claude Opus 5.5 --- docs/features/own-your-codegen.md | 22 ++- fixtures/conformance/ERROR-CODES.json | 2 +- .../expected/types/validator.md | 14 +- .../expected-registry.json | 14 +- .../OrphanSweepRunnerTests.cs | 159 ++++++++++++++++++ .../MetaObjects.Codegen/CodegenRunner.cs | 2 +- .../csharp/MetaObjects.Codegen/OrphanSweep.cs | 122 +++++++------- .../EfModelGapsTests.cs | 4 +- .../MetaObjects/Persistence/Db/DbSchema.cs | 2 +- .../csharp/MetaObjects/SpecMetamodel/db.json | 2 +- .../meta/persistence/db/db_provider.py | 2 +- .../src/metaobjects/spec_metamodel/db.json | 2 +- .../test/docs-cross-package-links.test.ts | 4 + .../test/templates/docs-file.test.ts | 16 ++ .../persistence/db/db-definition.embedded.ts | 2 +- site-reference/types/validator.html | 14 +- spec/metamodel/db.json | 2 +- 17 files changed, 284 insertions(+), 101 deletions(-) create mode 100644 server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index 27d8163d61..3c81cd44bc 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -600,14 +600,20 @@ handles those files by one rule: that name is not mistaken for generated output. - **A dry run** (`meta gen --dry-run`) reports what it would remove and removes nothing. -On **C#**, a self-hosted runner that calls `CodegenRunner.Run` with no `GenStateDir` keeps no -manifest, so there is nothing this rule can read and nothing is swept. Such a runner can opt in -to `OrphanSweep.SweepMarked(dirs, emitted)` after a run of its whole list: it deletes each file -under `dirs` whose first lines carry the `` marker and that `emitted` -(`RunResult.EmittedPaths`) does not hold, which is the manifest-less write rule (a marked file -is the generator's to overwrite) applied to deletion. A file without the marker, and anything -under `.metaobjects`, is never touched. A runner that makes several runs passes the union of -their directories and emitted paths, since one run's files look orphaned to another. +On **C#**, a self-hosted runner that makes one `CodegenRunner.Run` per target sweeps once, after +all of them. Give every run the same `GenStateDir` and `ProjectRoot` and leave `SweepOrphans` off +(one run's files look orphaned to another), then call `OrphanSweep.Sweep(genStateDir, projectRoot, +dirs, emitted)` with every run's output directories and the union of their +`RunResult.EmittedPaths`. It is the rule above: only a file the manifest records with its hash is +deleted, an edited one is refused by name, and `` alone proves nothing (it is the +.NET convention, which Roslyn source generators and hand-written partials carry too). Paths compare +case-insensitively, so a case-only rename on macOS or Windows keeps its file. `dryRun: true` +reports and changes nothing. A runner that wrote files before it kept a manifest passes +`reportUnrecorded: true` once: `Result.Unrecorded` lists the files whose header says +`Generated by MetaObjects` but that the manifest does not record, for you to delete by hand; with no +recorded hash, an edited one cannot be told from an untouched one, so none is deleted. The first run +over files already on disk records the ones that match the fresh output and refuses the rest, as +any first `gen` with a manifest does; `Baseline = "adopt"` records what is on disk instead. On **Java and Kotlin** every `mvn metaobjects:generate` execution is a full run, since its `` list is always complete. Every manifest entry names its owner: the generator's diff --git a/fixtures/conformance/ERROR-CODES.json b/fixtures/conformance/ERROR-CODES.json index 44f601d17b..d3aa8df48c 100644 --- a/fixtures/conformance/ERROR-CODES.json +++ b/fixtures/conformance/ERROR-CODES.json @@ -56,7 +56,7 @@ "ERR_SEQUENCE_START_OUT_OF_RANGE": "An identity.primary @sequenceStart is below 1, or above the largest value its key field can hold (2147483647 for a field.int). Postgres would refuse the sequence when the migration is applied, so the model is refused at load.", "ERR_SEQUENCE_WITHOUT_INCREMENT": "An identity.primary sets @sequenceStart or @sequenceName, but its @generation is not \"increment\". Only an increment key draws from a sequence, so the attribute would change nothing: the identity is refused rather than silently ignored.", "ERR_CROSS_FIELD_WITHOUT_CHECK": "A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) sets @dbCheck: false. Nothing but its database CHECK enforces a cross-field validator, so false would leave the rule enforced nowhere: the validator is refused. Remove the validator instead.", - "ERR_CONSTRAINT_NAME_WITHOUT_CHECK": "A CHECK-generating validator (numeric, length, regex, comparison, requiredWhen, presentIff, atLeastOne) or a field.enum sets @dbCheck: false, which generates no database CHECK, and @constraintName, which names that CHECK. With no CHECK there is nothing to name, so the node is refused rather than one of the two silently ignored.", + "ERR_CONSTRAINT_NAME_WITHOUT_CHECK": "A numeric, length or regex validator or a field.enum sets @dbCheck: false, which generates no database CHECK, and @constraintName, which names that CHECK. With no CHECK there is nothing to name, so the node is refused rather than one of the two silently ignored.", "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH": "A string-stored field.enum declares @maxLength (its column length) shorter than one of its @values members, which could not be stored in the column. The longest offending member is named.", "ERR_ENUM_MAX_LENGTH_WITH_INT_VALUE_MAP": "A field.enum sets both @maxLength and @intValueMap. An @intValueMap enum is stored as an integer, so a column length would change nothing: the field is refused rather than silently ignored.", "ERR_FLATTENED_COLUMN_PREFIX_WITHOUT_FLATTENED_STORAGE": "@flattenedColumnPrefix is set on a field.object whose @storage is not \"flattened\" (jsonb, subdocument, or absent, which is jsonb). Only a flattened value object puts its members' columns in the owning table, so the prefix would change nothing: the field is refused rather than silently ignored.", diff --git a/fixtures/metamodel-docs/expected/types/validator.md b/fixtures/metamodel-docs/expected/types/validator.md index dd5014751e..1471ae5516 100644 --- a/fixtures/metamodel-docs/expected/types/validator.md +++ b/fixtures/metamodel-docs/expected/types/validator.md @@ -45,7 +45,7 @@ Cardinality of presence: at least one of the named fields (@fields) must be pres | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@fields` | string[] | yes | | | metaobjects-core-types | Names of the candidate fields; at least one must be present. | | `@max` | int | no | | | metaobjects-core-types | The most of @fields that may be present. Absent: no upper bound; @max 1 makes it exactly one of them. Between 1 and the number of @fields (ERR_BAD_ATTR_VALUE). | @@ -86,7 +86,7 @@ Cross-field ordering: requires two sibling fields of the owning entity stand in | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@left` | string | yes | | | metaobjects-core-types | Name of the left-hand field of the owning entity. | | `@op` | string | yes | | `gt`, `gte`, `lt`, `lte`, `ne`, `eq` | metaobjects-core-types | Relational operator: gt (>), gte (>=), lt (<), lte (<=), ne (<>), eq (=). | | `@right` | string | yes | | | metaobjects-core-types | Name of the right-hand field of the owning entity. | @@ -108,7 +108,7 @@ Bounds string length / collection size via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -129,7 +129,7 @@ Bounds a numeric value's magnitude via @min/@max. | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | @@ -153,7 +153,7 @@ Biconditional presence: the target field (@field) is present (NOT NULL) if and o | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; @field is present exactly when @when equals this. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field whose presence is governed by the condition. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field. | @@ -175,7 +175,7 @@ Requires the value match a regular expression (@pattern). | Attribute | Type | Required | Default | Allowed values | Provider | Description | | --- | --- | --- | --- | --- | --- | --- | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@max` | int | no | | | metaobjects-core-types | Maximum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@min` | int | no | | | metaobjects-core-types | Minimum allowed value (length, numeric value, or array element count depending on the validator subtype). | | `@pattern` | string | no | | | metaobjects-core-types | Regular expression the value must match. | @@ -216,7 +216,7 @@ One-directional conditional presence: when the gating field (@when) equals @equa | --- | --- | --- | --- | --- | --- | --- | | `@condition` | expression | no | | | metaobjects-core-types | The case this rule applies in: an expression over the owning entity's fields (the attr.expression grammar). Absent: always. The database CHECK is NOT (condition) OR (rule), so a row the condition does not hold for, or holds NULL for, is not checked. Enforced by the database only, like the rule itself. | | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | -| `@dbCheck` | boolean | no | | | metaobjects-db | false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | +| `@dbCheck` | boolean | no | | | metaobjects-db | On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | | `@equals` | string | yes | | | metaobjects-core-types | The gating value; when @when equals this, @field must be present. | | `@field` | string | yes | | | metaobjects-core-types | Name of the field that becomes required when the condition holds. | | `@when` | string | yes | | | metaobjects-core-types | Name of the gating field whose value triggers the requirement. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 2540fb9dae..e6162c2b1c 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -5036,7 +5036,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "fields", @@ -5103,7 +5103,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "left", @@ -5155,7 +5155,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "max", @@ -5192,7 +5192,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "max", @@ -5237,7 +5237,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "equals", @@ -5281,7 +5281,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "max", @@ -5341,7 +5341,7 @@ "valueType": "boolean", "isArray": false, "required": false, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." }, { "name": "equals", diff --git a/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs new file mode 100644 index 0000000000..d222e4fd1d --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/OrphanSweepRunnerTests.cs @@ -0,0 +1,159 @@ +// G5, rc.20 (fix round 1): a self-hosted runner that makes one CodegenRunner.Run per target sweeps +// once, after all of them, through the hash manifest (OrphanSweep.Sweep with the union of every +// run's directories and EmittedPaths). Ownership is the manifest's recorded hash, never a header: +// `// ` is the .NET convention (Roslyn source generators write it, adopters put it +// on hand-written partials), so a file carrying it that MetaObjects did not record is never touched, +// and an edited orphan is refused by name, as `dotnet meta gen` refuses one. Paths compare +// case-insensitively: on macOS or Windows a case-only rename keeps the old spelling on disk. + +using MetaObjects.Loader; +using MetaObjects.Meta; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public sealed class OrphanSweepRunnerTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "mo-runner-sweep-" + Guid.NewGuid().ToString("N")); + private string Out => Path.Combine(_root, "gen"); + private string State => Path.Combine(_root, ".metaobjects", ".gen-state"); + + public OrphanSweepRunnerTests() => Directory.CreateDirectory(_root); + public void Dispose() { try { Directory.Delete(_root, recursive: true); } catch { } } + + /// One file per value object, under its package directory when . + private sealed class PerValue(bool byPackage, string dir = "acme/") : IGenerator + { + public string Name => "values"; + public IEnumerable Generate(GenContext ctx) => + ctx.Root.Objects().Select(o => new EmittedFile( + (byPackage ? dir : "") + $"{o.Name}.g.cs", + $"// \n// Generated by MetaObjects values.\npublic sealed class {o.Name} {{ }}\n")); + } + + private static MetaRoot Root(params string[] values) + { + var children = string.Join(",", values.Select(v => $$"""{ "object.value": { "name": "{{v}}", "children": [ { "field.string": { "name": "x" } } ] } }""")); + var r = new MetaDataLoader().Load([new InMemoryStringSource($$"""{ "metadata.root": { "package": "acme", "children": [ {{children}} ] } }""", id: "m.json")]); + Assert.Empty(r.Errors); + return r.Root; + } + + private CodegenRunner.RunResult Run(MetaRoot root, IGenerator generator, string? outDir = null) => + CodegenRunner.Run(new GenConfig { OutDir = outDir ?? Out, Namespace = "Acme", GenStateDir = State, ProjectRoot = _root }, + root, [generator]); + + private string At(string rel) => Path.Combine(Out, rel); + + private OrphanSweep.Result Sweep(IEnumerable runs, string[] dirs, bool reportUnrecorded = false, bool dryRun = false) => + OrphanSweep.Sweep(State, _root, dirs.Select(d => (d, "")).ToList(), + runs.SelectMany(r => r.EmittedPaths).ToHashSet(StringComparer.Ordinal), reportUnrecorded: reportUnrecorded, dryRun: dryRun); + + [Fact] + public void A_layout_change_is_swept_through_the_manifest() + { + Run(Root("Alpha", "Beta"), new PerValue(byPackage: false)); + var moved = Run(Root("Alpha", "Beta"), new PerValue(byPackage: true)); + Assert.True(File.Exists(At("Alpha.g.cs"))); + + var swept = Sweep([moved], [Out]); + Assert.Equal(["Alpha.g.cs", "Beta.g.cs"], swept.Removed); + Assert.False(File.Exists(At("Alpha.g.cs"))); + Assert.True(File.Exists(At("acme/Alpha.g.cs"))); + } + + [Fact] + public void A_dry_run_reports_and_removes_nothing() + { + Run(Root("Alpha"), new PerValue(byPackage: false)); + var moved = Run(Root("Alpha"), new PerValue(byPackage: true)); + Assert.Equal(["Alpha.g.cs"], Sweep([moved], [Out], dryRun: true).Removed); + Assert.True(File.Exists(At("Alpha.g.cs"))); + // The manifest still records it, so the real sweep removes it. + Assert.Equal(["Alpha.g.cs"], Sweep([moved], [Out]).Removed); + } + + [Fact] + public void A_foreign_auto_generated_file_is_never_touched() + { + // A Roslyn source generator's output, and a hand-written partial carrying the marker to quiet analyzers. + Directory.CreateDirectory(At("obj-gen")); + File.WriteAllText(At("obj-gen/Regex.g.cs"), "// \n#nullable enable\npartial class R { }\n"); + File.WriteAllText(At("Quiet.cs"), "// \npublic partial class Alpha { }\n"); + var run = Run(Root("Alpha"), new PerValue(byPackage: false)); + + var swept = Sweep([run], [Out], reportUnrecorded: true); + Assert.Empty(swept.Removed); + Assert.Empty(swept.Refused); + Assert.Empty(swept.Unrecorded); + Assert.True(File.Exists(At("obj-gen/Regex.g.cs"))); + Assert.True(File.Exists(At("Quiet.cs"))); + } + + [Fact] + public void An_edited_orphan_is_refused_by_name() + { + Run(Root("Alpha", "Beta"), new PerValue(byPackage: false)); + File.AppendAllText(At("Beta.g.cs"), "// my edit\n"); + var after = Run(Root("Alpha"), new PerValue(byPackage: false)); + + var swept = Sweep([after], [Out]); + Assert.Empty(swept.Removed); + Assert.Equal(["gen/Beta.g.cs"], swept.Refused); + Assert.True(File.Exists(At("Beta.g.cs"))); + } + + [Fact] + public void A_case_only_rename_keeps_the_file_it_just_wrote() + { + // On macOS or Windows, overwriting Alpha.g.cs through the path ALPHA.g.cs keeps the old name, so + // the file on disk is spelled differently from the path the run emitted. Simulated here on any + // file system: the run emitted the upper-case spelling. + var run = Run(Root("Alpha"), new PerValue(byPackage: false)); + var emitted = run.EmittedPaths.Select(p => Path.Combine(Path.GetDirectoryName(p)!, Path.GetFileName(p).ToUpperInvariant())).ToHashSet(); + var swept = OrphanSweep.Sweep(State, _root, [(Out, "")], emitted); + Assert.Empty(swept.Removed); + Assert.True(File.Exists(At("Alpha.g.cs"))); + } + + [Fact] + public void A_directory_whose_case_changed_keeps_its_files() + { + var run = Run(Root("Alpha"), new PerValue(byPackage: true, dir: "acme/")); + var emitted = run.EmittedPaths.Select(p => p.Replace(Path.DirectorySeparatorChar + "acme" + Path.DirectorySeparatorChar, + Path.DirectorySeparatorChar + "ACME" + Path.DirectorySeparatorChar, StringComparison.Ordinal)).ToHashSet(); + Assert.Contains(emitted, p => p.Contains("ACME", StringComparison.Ordinal)); + var swept = OrphanSweep.Sweep(State, _root, [(Out, "")], emitted); + Assert.Empty(swept.Removed); + Assert.True(File.Exists(At("acme/Alpha.g.cs"))); + } + + [Fact] + public void Several_runs_sweep_their_union_and_nested_directories_survive() + { + var inner = Path.Combine(Out, "inner"); + var outer = Run(Root("Alpha"), new PerValue(byPackage: false)); + var nested = Run(Root("Beta"), new PerValue(byPackage: false), outDir: inner); + // Swept alone, the outer run's sweep would see the inner run's recorded files as orphans. + var swept = Sweep([outer, nested], [Out, inner]); + Assert.Empty(swept.Removed); + Assert.True(File.Exists(Path.Combine(inner, "Beta.g.cs"))); + Assert.True(File.Exists(At("Alpha.g.cs"))); + } + + [Fact] + public void Output_written_before_the_manifest_is_reported_never_deleted() + { + // A file an earlier, manifest-less run wrote: MetaObjects' own header, but no recorded hash, so + // an edit to it cannot be told from an untouched copy. + Directory.CreateDirectory(Out); + File.WriteAllText(At("Legacy.g.cs"), "// \n// Generated by MetaObjects values.\npublic sealed class Legacy { }\n"); + var run = Run(Root("Alpha"), new PerValue(byPackage: false)); + + var swept = Sweep([run], [Out], reportUnrecorded: true); + Assert.Empty(swept.Removed); + Assert.Equal(["gen/Legacy.g.cs"], swept.Unrecorded); + Assert.True(File.Exists(At("Legacy.g.cs"))); + Assert.Empty(Sweep([run], [Out]).Unrecorded); + } +} diff --git a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs index 5d6e6834e0..a81f4d549d 100644 --- a/server/csharp/MetaObjects.Codegen/CodegenRunner.cs +++ b/server/csharp/MetaObjects.Codegen/CodegenRunner.cs @@ -29,7 +29,7 @@ public sealed record RunResult(IReadOnlyList Files, IReadOnlyList OverwritePaths { get; init; } = new HashSet(); /// Absolute paths every generator of the run emitted (refused ones included): what a - /// self-hosted runner hands (G5, rc.20). + /// self-hosted runner that makes several runs passes the union of to (G5, rc.20). public IReadOnlySet EmittedPaths { get; init; } = new HashSet(); } diff --git a/server/csharp/MetaObjects.Codegen/OrphanSweep.cs b/server/csharp/MetaObjects.Codegen/OrphanSweep.cs index ac603842d6..af3ab1565f 100644 --- a/server/csharp/MetaObjects.Codegen/OrphanSweep.cs +++ b/server/csharp/MetaObjects.Codegen/OrphanSweep.cs @@ -39,7 +39,39 @@ public enum Verdict /// Project-relative paths of edited orphans, left in place. /// Edited orphans deleted anyway, because every generator writing into /// their directory declares (also in ). - public sealed record Result(IReadOnlyList Removed, IReadOnlyList Refused, IReadOnlyList Discarded); + public sealed record Result(IReadOnlyList Removed, IReadOnlyList Refused, IReadOnlyList Discarded) + { + /// + /// With reportUnrecorded: project-relative paths of files no generator emitted that the + /// manifest does not record but whose leading lines carry MetaObjects' own header + /// () — output written before the runner kept a manifest. Never deleted: + /// with no recorded hash there is no telling an edited file from an untouched one. Empty otherwise. + /// + public IReadOnlyList Unrecorded { get; init; } = []; + } + + /// The header every C# MetaObjects generator writes on a file's second line + /// (// Generated by MetaObjects <generator>); <auto-generated/> alone is the + /// .NET convention and is not ours. + public const string Signature = "Generated by MetaObjects "; + + /// How many leading lines are read for . + private const int SignatureLines = 5; + + private static bool CarriesSignature(string path) + { + try + { + using var reader = new StreamReader(path); + for (var i = 0; i < SignatureLines && reader.ReadLine() is { } line; i++) + if (line.Contains(Signature, StringComparison.Ordinal)) return true; + return false; + } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) + { + return false; + } + } /// /// Classify one committed file no generator emitted. is its absolute @@ -71,10 +103,13 @@ public static Verdict Classify( return key.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(key) ? null : key; } + // Case-insensitive, as every path comparison of the sweep (I3, rc.20): on a case-insensitive file + // system (macOS, Windows) an overwrite keeps the old spelling, so a case-only rename leaves the + // emitted file under its old name. Keeping too much is the safe failure for a sweep. private static bool IsUnder(string path, string dir) => Path.GetFullPath(path).StartsWith( Path.TrimEndingDirectorySeparator(Path.GetFullPath(dir)) + Path.DirectorySeparatorChar, - StringComparison.Ordinal); + StringComparison.OrdinalIgnoreCase); /// /// Delete the untouched files under that the manifest records and @@ -82,16 +117,29 @@ private static bool IsUnder(string path, string dir) => /// not hold, and forget every recorded path under those directories whose file is gone. /// Each directory comes with the label the run reports its files under. In a directory of /// (absolute paths) an edited orphan is deleted too. + /// + /// A self-hosted runner that makes several + /// calls (one per target) gives each the same and + /// , leaves off, and calls this + /// once afterwards with every run's directories and the union of their + /// : one run's files look orphaned to another (G5, + /// rc.20). lists, never deletes, the files MetaObjects wrote before + /// the runner kept a manifest (); reports what + /// would be removed and changes nothing. + /// /// public static Result Sweep( string genStateDir, string projectRoot, IReadOnlyList<(string Dir, string Label)> dirs, IReadOnlySet emitted, - IReadOnlySet? overwriteDirs = null) + IReadOnlySet? overwriteDirs = null, bool reportUnrecorded = false, bool dryRun = false) { var removed = new List(); var refused = new List(); var discarded = new List(); + var unrecorded = new List(); if (!HashManifest.Exists(genStateDir)) return new Result(removed, refused, discarded); + // The emitted paths compared case-insensitively (see IsUnder), whatever set the caller passed. + emitted = emitted.Select(Path.GetFullPath).ToHashSet(StringComparer.OrdinalIgnoreCase); var hashes = HashManifest.Load(genStateDir); var forget = new HashSet(StringComparer.Ordinal); var root = Path.GetFullPath(projectRoot); @@ -117,15 +165,18 @@ public static Result Sweep( var key = KeyFor(root, path)!; switch (Classify(hashes, root, path, dirRel)) { + case Verdict.Stranger when reportUnrecorded && CarriesSignature(path): + unrecorded.Add(key.Replace(Path.DirectorySeparatorChar, '/')); + break; case Verdict.Pristine: - File.Delete(path); + if (!dryRun) File.Delete(path); // Only the spelling it was recorded under: a legacy dir-relative key // is otherwise someone else's record in another directory. forget.Add(hashes.ContainsKey(key) ? key : dirRel); removed.Add(label + dirRel.Replace(Path.DirectorySeparatorChar, '/')); break; case Verdict.Edited when overwrite: - File.Delete(path); + if (!dryRun) File.Delete(path); forget.Add(hashes.ContainsKey(key) ? key : dirRel); removed.Add(label + dirRel.Replace(Path.DirectorySeparatorChar, '/')); discarded.Add(key.Replace(Path.DirectorySeparatorChar, '/')); @@ -149,69 +200,16 @@ public static Result Sweep( } } - if (forget.Count > 0) + if (forget.Count > 0 && !dryRun) { foreach (var key in forget) hashes.Remove(key); HashManifest.Save(genStateDir, hashes); } return new Result(removed, refused.Distinct().Order(StringComparer.Ordinal).ToList(), - discarded.Distinct().Order(StringComparer.Ordinal).ToList()); - } - - /// How many leading lines reads for the generated marker. - private const int MarkerLines = 5; - - /// - /// G5 (rc.20): the sweep for a self-hosted runner that keeps no hash manifest (no - /// ), so a layout change (the package layout, R39) does not - /// leave the old files behind. Deletes each file under that carries the - /// generated marker () in its first lines and that - /// (absolute paths; ) - /// does not hold, and returns the deleted absolute paths, sorted. - /// - /// This is the manifest-less write rule turned on deletion: with no manifest, a file carrying the - /// marker is the generator's to overwrite, edited or not, so it is also the generator's to - /// delete once nothing emits it. A file without the marker is never touched, nor is anything - /// under a .metaobjects directory. Opt-in, and only for the caller's own runner: it is - /// never called by . - /// Pass the union of every run's directories and emitted paths when one runner makes several - /// runs, since a file another run emitted would look orphaned to this one; and call it only - /// after a run of the whole generator list, for the same reason is. - /// - /// - public static IReadOnlyList SweepMarked(IEnumerable dirs, IReadOnlySet emitted) - { - var wanted = new HashSet(emitted.Select(Path.GetFullPath), StringComparer.Ordinal); - var removed = new SortedSet(StringComparer.Ordinal); - foreach (var dir in dirs.Select(Path.GetFullPath).Distinct(StringComparer.Ordinal)) + discarded.Distinct().Order(StringComparer.Ordinal).ToList()) { - if (!Directory.Exists(dir)) continue; - foreach (var path in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)) - { - var full = Path.GetFullPath(path); - if (wanted.Contains(full) || removed.Contains(full)) continue; - if (Path.GetRelativePath(dir, full).Split(Path.DirectorySeparatorChar).Contains(".metaobjects")) continue; - if (!CarriesMarker(full)) continue; - File.Delete(full); - removed.Add(full); - } - } - return removed.ToList(); - } - - private static bool CarriesMarker(string path) - { - try - { - using var reader = new StreamReader(path); - for (var i = 0; i < MarkerLines && reader.ReadLine() is { } line; i++) - if (line.Contains(CodegenRunner.GeneratedMarker, StringComparison.Ordinal)) return true; - return false; - } - catch (Exception e) when (e is IOException or UnauthorizedAccessException) - { - return false; - } + Unrecorded = unrecorded.Distinct().Order(StringComparer.Ordinal).ToList(), + }; } /// The warning for edited orphans. The same wording as codegen-ts's diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index 8920b3fdc4..db588e3e4f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -962,7 +962,7 @@ private static System.Reflection.Assembly MigrationsAssembly(string? line) } // rc.19 fix round (I4): EF reads [assembly: DesignTimeServicesReference] only from the startup and - // migrations assemblies. With the context in a third assembly (a library, as P3's Core) the + // migrations assemblies. With the context in a third assembly (a library, as an adopter's core project) the // reference generated beside it is never read: the migrations project needs the line itself. [Theory] [InlineData(false)] @@ -1259,7 +1259,7 @@ public void The_snapshot_records_the_json_column_comment() } // G1, rc.20 — an OwnedTypeConfig override decides how an object field is mapped. One that maps - // it as a jsonb property (P3 does, for every non-flattened value object) has no owned navigation, + // it as a jsonb property (an adopter's hook may, for every non-flattened value object) has no owned navigation, // so the owned type's annotation line would throw a NullReferenceException in OnModelCreating // and no model would build. The comment goes on the property's column instead; a mapping the // generator cannot see gets no comment line at all. diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index 90fb061224..d35c94d38e 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -116,7 +116,7 @@ public static class DbSchema Name: Core.Validator.ValidatorConstants.VALIDATOR_ATTR_DB_CHECK, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false, - Description: "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider."); + Description: "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider."); /// @dbCheck on a field.enum — false generates no membership CHECK. public static readonly AttrSchema EnumDbCheckSchema = new AttrSchema( diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index fef802cf23..4b6a2d2452 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -72,7 +72,7 @@ "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, - { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index e855a49959..cba60c9076 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -218,7 +218,7 @@ name=vc.VALIDATOR_ATTR_DB_CHECK, value_type=ATTR_SUBTYPE_BOOLEAN, required=False, - description="false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", + description="On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.", ) # The validators meta migrate renders as a CHECK: required is NOT NULL; array and base have none. _VALIDATOR_SUBTYPES_FOR_CONSTRAINT_NAME = ( diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index fef802cf23..4b6a2d2452 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -72,7 +72,7 @@ "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, - { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { diff --git a/server/typescript/packages/codegen-ts/test/docs-cross-package-links.test.ts b/server/typescript/packages/codegen-ts/test/docs-cross-package-links.test.ts index 15119e4d2a..88ef23b65e 100644 --- a/server/typescript/packages/codegen-ts/test/docs-cross-package-links.test.ts +++ b/server/typescript/packages/codegen-ts/test/docs-cross-package-links.test.ts @@ -41,9 +41,11 @@ const MODEL = [ { "field.long": { name: "id" } }, { "field.long": { name: "customerId", "@required": true } }, { "field.long": { name: "parentId" } }, + { "field.long": { name: "originalId" } }, { "identity.primary": { name: "id", "@fields": ["id"], "@generation": "increment" } }, { "identity.reference": { name: "customer", "@fields": ["customerId"], "@references": "acme::crm::Customer" } }, { "identity.reference": { name: "parent", "@fields": ["parentId"], "@references": "acme::sales::Order" } }, + { "identity.reference": { name: "original", "@fields": ["originalId"], "@references": "Order" } }, ], }, }, @@ -93,5 +95,7 @@ describe("docsFile — cross-page links follow package placement (item 11)", () const order = (await render()).get("acme/sales/Order.md")!; expect(order).toContain("**Reference:** `customerId` → [`acme::crm::Customer`](../crm/Customer.md)"); expect(order).toContain("**Reference:** `parentId` → [`acme::sales::Order`](./Order.md)"); + // A bare reference keeps its authored spelling as the label, and links all the same. + expect(order).toContain("**Reference:** `originalId` → [`Order`](./Order.md)"); }); }); diff --git a/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts b/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts index 3006d48b63..39441f9667 100644 --- a/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/docs-file.test.ts @@ -341,6 +341,22 @@ describe("renderDocsFile — Identity section", () => { expect(out).toContain("**Secondary index:** `visitorId`"); expect(out).toContain("**Reference:** `authorId` → [`Author`](./Author.md)"); }); + + test("a reference whose target the tree does not hold stays plain text (rc.20 G4)", () => { + const root = metaRoot(); + const post = metaObject(OBJECT_SUBTYPE_ENTITY, "Post"); + attachRdbSource(post, "posts"); + post.addChild(metaField(FIELD_SUBTYPE_LONG, "id")); + post.addChild(metaField(FIELD_SUBTYPE_LONG, "ghostId")); + const reference = meta(new TypeId(TYPE_IDENTITY, IDENTITY_SUBTYPE_REFERENCE), "ghost"); + reference.setAttr("fields", ["ghostId"]); + reference.setAttr("references", "Ghost"); + post.addChild(reference); + root.addChild(post); + const out = renderDocsFile(post, { dialect: "sqlite", loadedRoot: root }); + const bullet = out.split("\n").find((l) => l.startsWith("- **Reference:**")); + expect(bullet).toBe("- **Reference:** `ghostId` → `Ghost`"); + }); }); describe("renderDocsFile — Constraints", () => { diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index 798fbe975c..55920a3b9b 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -302,7 +302,7 @@ export const DB_DEFINITION: ProviderDefinition = { "name": "dbCheck", "min": 0, "max": 1, - "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." + "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, diff --git a/site-reference/types/validator.html b/site-reference/types/validator.html index dc0ff80c07..3807acefba 100644 --- a/site-reference/types/validator.html +++ b/site-reference/types/validator.html @@ -131,7 +131,7 @@

    validator.atLeastOne

    - + @@ -234,7 +234,7 @@

    validator.comparison

    - + @@ -299,7 +299,7 @@

    validator.length

    - + @@ -355,7 +355,7 @@

    validator.numeric

    - + @@ -421,7 +421,7 @@

    validator.presentIff

    - + @@ -486,7 +486,7 @@

    validator.regex

    - + @@ -569,7 +569,7 @@

    validator.requiredWhen

    - + diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index fef802cf23..4b6a2d2452 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -72,7 +72,7 @@ "subType": ["numeric", "length", "regex", "comparison", "requiredWhen", "presentIff", "atLeastOne"], "children": [ { "type": "attr", "subType": "string", "name": "constraintName", "min": 0, "max": 1, "description": "The database name of the CHECK constraint this validator generates (numeric, length, regex and the cross-field validators; the others generate no CHECK). Absent: the derived
    metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @fields metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @left metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @equals metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @max metaobjects-dbfalse: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider.
    @equals
    ___chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider." }, - { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "false: this numeric, length or regex validator generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. Absent: true. A cross-field validator (comparison, requiredWhen, presentIff, atLeastOne) is enforced only by its CHECK, so false on one of those is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } + { "type": "attr", "subType": "boolean", "name": "dbCheck", "min": 0, "max": 1, "description": "On a numeric, length or regex validator, false generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validators still enforce it on every write. On a cross-field validator (comparison, requiredWhen, presentIff, atLeastOne), which only its CHECK enforces, false is refused (ERR_CROSS_FIELD_WITHOUT_CHECK). Absent: true. For a column whose legacy rows break the rule, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider." } ] }, { From 974406ee567aa5d957994e0bdedb225d8c5fbdf7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Wed, 11 Nov 2026 19:32:42 -0500 Subject: [PATCH 168/267] fix(csharp): the runner sweep goes through the hash manifest, case-insensitively (I2, I3) Record commit: a staging slip put this change's files into 50386c4c6 (the removed OrphanSweepMarkedTests.cs and the CHANGELOG entry) and d0180824a (OrphanSweep.cs, CodegenRunner.cs, OrphanSweepRunnerTests.cs, docs/features/own-your-codegen.md). No history was rewritten. OrphanSweep.SweepMarked treated any file whose first lines held as its own. That is the .NET convention (Roslyn source generators, analyzer-quieted hand-written partials), so it could delete files MetaObjects never wrote, and it deleted edited orphans silently. It is removed. A runner that makes one Run per target gives each the same GenStateDir and ProjectRoot and calls OrphanSweep.Sweep once with every run's directories and the union of RunResult.EmittedPaths: ownership is the manifest's recorded hash, an edited orphan is refused by name, unrecorded files are never touched. Sweep gains dryRun and reportUnrecorded (lists, never deletes, "Generated by MetaObjects" files a manifest-less run wrote). Paths compare case-insensitively, meta gen's own sweep included, so a case-only rename on macOS or Windows keeps its file. Tests: OrphanSweepRunnerTests (8); the two case tests watched red with an ordinal compare. Co-Authored-By: Claude Opus 5.5 From a7625e4644c1f78379ddd0ef58ab2e519eb3502d Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Wed, 11 Nov 2026 20:25:57 -0500 Subject: [PATCH 169/267] chore(templates): resync the owned drizzle-schema copies (I1 follow-through) The three owned copies of templates/drizzle-schema.ts (test-generators, examples/showcase, examples/advanced-modeling) take 50386c4c6's @constraintName naming of the enum CHECK; the "owned template copies current" gate caught them stale. Co-Authored-By: Claude Opus 5.5 --- .../codegen/templates/drizzle-schema.ts | 13 ++++++++++++- .../showcase/codegen/templates/drizzle-schema.ts | 13 ++++++++++++- .../test-generators/src/templates/drizzle-schema.ts | 13 ++++++++++++- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index b828204ac8..39af23323d 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -26,7 +26,7 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; @@ -194,6 +194,17 @@ export function renderDrizzleSchema( const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index b828204ac8..39af23323d 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -26,7 +26,7 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; @@ -194,6 +194,17 @@ export function renderDrizzleSchema( const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { diff --git a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts index b828204ac8..39af23323d 100644 --- a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts @@ -26,7 +26,7 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; @@ -194,6 +194,17 @@ export function renderDrizzleSchema( const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); + // A declared @constraintName (ADR-0039 resolving) names the CHECK, as migrate-ts's + // withDeclaredName does: the literal name, the expression as either arm below spells it. + const declared = field.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + if (typeof declared === "string" && declared.length > 0) { + return { + name: code`${JSON.stringify(declared)}`, + expr: names === undefined || values === undefined + ? code`${spec.checkConstraint ?? ""}` + : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + }; + } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which // is what this file did unconditionally before. if (names === undefined || values === undefined) { From 783ac219e2159129a452d477e47d5ed20c61d7cc Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 13 Nov 2026 10:17:23 -0500 Subject: [PATCH 170/267] fix(python): pass only validated input to the repository in generated routes (#566) * fix(python): generated routes hand the repository only the validated input (1.2.1) The generated FastAPI create, PATCH and PUT handlers validated the body against Create / Patch and then passed the RAW body to the repository. Pydantic ignores undeclared keys and the input models leave out server-owned fields, so a client-sent id, a readOnly field and a made-up field such as isAdmin all reached the write. Security fix. Each handler (plain and TPH per-subtype) now rebinds dto to the keys the input model validated, at every depth, before any repository call, as the TypeScript routes do. Undeclared and non-settable keys are dropped silently, never 400'd, so a client sending an extra harmless field keeps working; values stay the body's own, so repositories see the same value types as in 1.2.0. Python package version 1.2.1 only; CHANGELOG entry under Security. Regression gate: tests/integration/test_generated_router_validated_input.py. * no-mistakes(document): python routes pass only validated input * no-mistakes(lint): regenerate showcase site payload for PyPI 1.2.1 --- CHANGELOG.md | 28 ++ docs/features/generated-mutations.md | 12 +- .../.metaobjects/.gen-state/.hashes.json | 2 +- .../generated/python/subscriber_router.py | 32 ++- examples/showcase/site-payload.json | 2 +- server/python/pyproject.toml | 2 +- .../src/metaobjects/codegen/KNOWN_GAPS.md | 6 +- .../codegen/generators/router_generator.py | 98 +++++-- .../test_generated_router_validated_input.py | 272 ++++++++++++++++++ server/python/uv.lock | 2 +- 10 files changed, 414 insertions(+), 42 deletions(-) create mode 100644 server/python/tests/integration/test_generated_router_validated_input.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 79042d8184..9fe7ecc774 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,34 @@ here.** ## [Unreleased] +## [1.2.1] — Python only + +_PyPI `1.2.1` only. npm, NuGet and Maven Central stay at `1.2.0` (`8.2.0`): none of them has a +product change. No vocabulary or `metamodelVersion` change._ + +### Security + +- **The generated Python routes passed raw request input to the repository.** The FastAPI + create, PATCH and PUT handlers validated the body against `Create` / `Patch` + and then handed the repository the raw body, not what was validated. Pydantic ignores a key a + model does not declare, so a client could write fields it must never touch: a client-sent `id` + on create (or on update, changing the row's identity), a `@mutability: readOnly` field, and any + made-up field such as `isAdmin` all reached the repository. Found by an external review of + 1.2.0. Every Python adopter serving the generated routes should upgrade and regenerate; an + ejected (owned) router needs the same change made by hand. + + The repository now receives only the validated input, as the TypeScript routes already do. + Each handler validates the body, then keeps only the keys the input model validated, at every + depth (a nested value object included), before any repository call, in the plain and the TPH + per-subtype handlers. A field the entity does not declare, a server-generated id, a `readOnly` + or derived field on create, and the id, `readOnly` and `writeOnce` fields on update are all + dropped silently. None of them is answered with a 400, so a client that sends an extra harmless + field keeps working; a malformed value on a field the client may set is still + `400 {"error": "validation"}`. An assigned key is still the caller's on create. Values are the + body's own, so a repository receives the same value types as in 1.2.0. + + Gated by `server/python/tests/integration/test_generated_router_validated_input.py`. + ## [1.2.0] — 2026-10-30 _npm `1.2.0` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._ diff --git a/docs/features/generated-mutations.md b/docs/features/generated-mutations.md index 57aa6f409a..3a367bbb6f 100644 --- a/docs/features/generated-mutations.md +++ b/docs/features/generated-mutations.md @@ -41,7 +41,9 @@ but the semantics are one contract — call them **PATCH-1..7** (FR-035): simply omits every non-settable field, and Zod drops unknown keys — so `safeParse` succeeds and the key never reaches the `SET`. The TPH discriminator is additionally deleted by hand after parse, the same convention. A malformed - *value* on a settable key is still `400 {"error":"validation"}`. + *value* on a settable key is still `400 {"error":"validation"}`. A key the entity + does not declare at all is dropped the same way. The Python routes hand the + repository only the keys their input model validated. This matters for `writeOnce` specifically: the generated edit form submits EVERY registered field (`handleSubmit` passes all values, and 0.19.2 switched the resolver to `UpdateSchema` on edit rather than diff-and-omit), so rejecting a @@ -109,10 +111,10 @@ repo.patch(id) { it[Authors.bio] = "…" } // touches only what you set the controller binds the partial JSON body via `Patch.fromJson` (presence-tracked) and delegates to `repository.patch`, so an omitted key is never written. -**Python** — the generated FastAPI route binds the raw JSON body (the set of -*present* keys — the tristate signal) and validates the present values against the -generated `Patch` model before delegating to the runtime `update`, which -`SET`s only those keys. +**Python** — the generated FastAPI route binds the JSON body (the set of +*present* keys — the tristate signal), validates the present values against the +generated `Patch` model, and hands the repository only the keys that model +validated. The runtime `update` then `SET`s only those keys. **C#** — the generated route runs a per-field merge loop over the present JSON keys (the app's configured `JsonSerializerOptions`), writing only the columns the body diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes.json index 8a7a4f6bb9..131a0265b9 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes.json @@ -10,7 +10,7 @@ "generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5", "generated/python/subscriber_filter_allowlist.py": "b0414cc95ff3982c80a0e1a06839f090c0b423e41f5a94275df93426cea09df5", "generated/python/subscriber_names.py": "269637a02bf9b46f55658b58cb42f83196c03a877e1e2101337847fd406c1561", - "generated/python/subscriber_router.py": "5a354e50b1aab48239a4249b670a6d2351c1816cbca6d710ea688f252e9612e5", + "generated/python/subscriber_router.py": "f3c81be3c07a10a94afb6a6a0f87eb84b9bca40ead03dd989ebd019f71b97dfc", "generated/ts/Subscriber.queries.ts": "9f1a459c57fafc98bf074b4443b506d4a1e7023ed188f293021ae89c298d4562", "generated/ts/Subscriber.routes.ts": "147d32ae658f985e024c3de6e8894ca7359f767eeaa765cec70756802e3bd300", "generated/ts/Subscriber.ts": "a78c17f915222ee108290c28468313d77f77b5cff438f485324409302e389a96", diff --git a/examples/showcase/generated/python/subscriber_router.py b/examples/showcase/generated/python/subscriber_router.py index 47aaaab7ce..fe148c5e3e 100644 --- a/examples/showcase/generated/python/subscriber_router.py +++ b/examples/showcase/generated/python/subscriber_router.py @@ -91,6 +91,26 @@ async def _json_body(request: Request) -> dict[str, Any] | None: return None +def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]: + """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the + input model does not declare (an undeclared name, a server-generated id, a readOnly field) + is dropped silently and never reaches the repository; values stay the body's own.""" + return { + _k: _validated_value(getattr(valid, _k), raw[_k]) + for _k in valid.model_fields_set + } + + +def _validated_value(valid: Any, raw: Any) -> Any: + if isinstance(valid, BaseModel) and isinstance(raw, dict): + return _validated_input(valid, raw) + if isinstance(valid, list) and isinstance(raw, list): + return [_validated_value(v, r) for v, r in zip(valid, raw)] + if isinstance(valid, dict) and isinstance(raw, dict): + return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw} + return raw + + _FROZEN_FIELDS: frozenset[str] = frozenset() @@ -198,9 +218,13 @@ def create_subscriber( # FR-036: run the generated field constraints (length / pattern / # numeric bounds) before persisting; a violation is the cross-port 400. try: - SubscriberCreate(**dto) + _valid = SubscriberCreate(**dto) except ValidationError: return JSONResponse(status_code=400, content={"error": "validation"}) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) # #203/ADR-0045: stamp @autoSet columns (server-owned; caller ignored). _asnow = _dt.datetime.now(_dt.timezone.utc) dto["createdAt"] = _asnow @@ -239,9 +263,13 @@ def update_subscriber( # FR-036: validate PRESENT, non-null values with the create rules (the # all-optional patch model never fires required-checks on ABSENT fields). try: - SubscriberPatch(**dto) + _valid = SubscriberPatch(**dto) except ValidationError: return JSONResponse(status_code=400, content={"error": "validation"}) + # SECURITY (1.2.1): only what the input model validated reaches the repository. A key + # it does not declare (an undeclared name, a server-generated id, a readOnly or derived + # field, a frozen one on update) is dropped silently, never 400'd. + dto = _validated_input(_valid, dto) dto.pop("createdAt", None) # onCreate @autoSet is write-once (server-owned) try: saved = repo.update(subscriber_id, dto) diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index cc09d97e22..237e16a881 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -1,7 +1,7 @@ { "registries": { "npm": "1.2.0", - "pypi": "1.2.0", + "pypi": "1.2.1", "nuget": "1.2.0", "maven": "8.2.0", "metamodel": "1.2" diff --git a/server/python/pyproject.toml b/server/python/pyproject.toml index 2854f66cad..2366d3f4bc 100644 --- a/server/python/pyproject.toml +++ b/server/python/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "metaobjects" -version = "1.2.0" +version = "1.2.1" description = "Cross-language metadata standard: declare typed entities once, generate idiomatic drift-checked code across languages — Python port." readme = "README.md" requires-python = ">=3.11" diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md index 2cb454b8d7..1b300bfa6f 100644 --- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md +++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md @@ -36,9 +36,9 @@ The generated router takes `dto: dict[str, Any]` for `POST` / `PATCH` / (`from . import , Patch`) and constructs them to enforce field constraints over HTTP — POST validates `(**dto)`, PATCH validates the all-optional `Patch(**dto)` (present values only) → `400 {"error":"validation"}`. -The repository seam still receives the original `dict` (preserving the FR-035 -present-key tristate + wire values), so the strong-typing simplification below -remains for the repo/response types; only the validation import was added. +The repository seam receives only the keys the input model validated, as a `dict` +(the FR-035 present-key tristate + wire values are kept), so the strong-typing +simplification below remains for the repo/response types. This keeps the router module decoupled from sibling generated files (the entity-model generator emits one `@dataclass`/Pydantic model per diff --git a/server/python/src/metaobjects/codegen/generators/router_generator.py b/server/python/src/metaobjects/codegen/generators/router_generator.py index 227346832c..9e0586bcdb 100644 --- a/server/python/src/metaobjects/codegen/generators/router_generator.py +++ b/server/python/src/metaobjects/codegen/generators/router_generator.py @@ -434,10 +434,9 @@ def _frozen_names(entity: MetaObject) -> list[str]: ADR-0045: the OUTERMOST generated write artifact enforces the mode, and for FastAPI that is the ROUTER, not the ``Patch`` model — the handler binds - ``dto`` (the raw body as a dict) and passes THAT to the repository, so a - field merely absent from the patch model still reaches the row. @autoSet gets - away with it because the router OVERWRITES its key server-side; a writeOnce - field has no server value to overwrite, so it must be popped explicitly.""" + ``dto`` as a dict. Since 1.2.1 the router hands the repository only the keys the + patch model validated (:func:`_validated_input_lines`), which already drops these; + the explicit pop stays as the FR-037 seam an owned router edits.""" return [ f.name for f in entity.fields() @@ -461,6 +460,49 @@ def _frozen_strip_lines(entity: MetaObject, indent: str = " ") -> list[str]: ] +#: 1.2.1 security fix. The request body cut down to what the input model validated, emitted +#: once per writable router. 1.2.0 validated the body and then handed the RAW body to the +#: repository, so a client-sent server-generated id, a ``readOnly`` field or a name the entity +#: does not declare (an ``isAdmin``) reached the write. Pydantic ignores a key a model does not +#: declare, and the input models leave out every field a client may not set, so keeping only +#: the keys the model validated (at every depth: a nested value object included) drops all of +#: them silently, as the TypeScript routes do. The values stay the body's own (decimal-exact) +#: values, so a repository receives the same value types as in 1.2.0. +_VALIDATED_INPUT_LINES: list[str] = [ + "def _validated_input(valid: BaseModel, raw: dict[str, Any]) -> dict[str, Any]:", + ' """GENERATED — *raw* cut down to the keys *valid* validated, at every depth. A key the', + " input model does not declare (an undeclared name, a server-generated id, a readOnly field)", + ' is dropped silently and never reaches the repository; values stay the body\'s own."""', + " return {_k: _validated_value(getattr(valid, _k), raw[_k]) for _k in valid.model_fields_set}", + "", + "", + "def _validated_value(valid: Any, raw: Any) -> Any:", + " if isinstance(valid, BaseModel) and isinstance(raw, dict):", + " return _validated_input(valid, raw)", + " if isinstance(valid, list) and isinstance(raw, list):", + " return [_validated_value(v, r) for v, r in zip(valid, raw)]", + " if isinstance(valid, dict) and isinstance(raw, dict):", + " return {k: _validated_value(v, raw[k]) for k, v in valid.items() if k in raw}", + " return raw", +] + + +def _validated_input_lines(model: str, *comment: str) -> list[str]: + """Validate ``dto`` against the input *model*, then rebind it to what the model validated + (see :data:`_VALIDATED_INPUT_LINES`): the repository never sees any other key.""" + return [ + *(f" # {line}" for line in comment), + " try:", + f" _valid = {model}(**dto)", + " except ValidationError:", + ' return JSONResponse(status_code=400, content={"error": "validation"})', + " # SECURITY (1.2.1): only what the input model validated reaches the repository. A key", + " # it does not declare (an undeclared name, a server-generated id, a readOnly or derived", + " # field, a frozen one on update) is dropped silently, never 400'd.", + " dto = _validated_input(_valid, dto)", + ] + + def _auto_set_split(entity: MetaObject) -> tuple[list[MetaField], list[MetaField]]: """The entity's ``@autoSet`` temporal fields split into ``(onCreate, onUpdate)``. @@ -1083,12 +1125,11 @@ def _emit_route_handler( ") -> Any:", *_DECIMAL_COERCE, *denied_strip, - " # FR-036: run the generated field constraints (length / pattern /", - " # numeric bounds) before persisting; a violation is the cross-port 400.", - " try:", - f" {model_name}(**dto)", - " except ValidationError:", - ' return JSONResponse(status_code=400, content={"error": "validation"})', + *_validated_input_lines( + model_name, + "FR-036: run the generated field constraints (length / pattern /", + "numeric bounds) before persisting; a violation is the cross-port 400.", + ), # #203/ADR-0045: the generated router (the API surface) stamps @autoSet columns # ABOVE the consumer repo seam — onCreate + onUpdate both stamped from one instant # (a fresh row's createdAt == updatedAt), ignoring any caller-supplied value. @@ -1114,12 +1155,11 @@ def _emit_route_handler( " for _k in _REQUIRED_FIELDS:", " if _k in dto and dto[_k] is None:", ' return JSONResponse(status_code=400, content={"error": "validation"})', - " # FR-036: validate PRESENT, non-null values with the create rules (the", - " # all-optional patch model never fires required-checks on ABSENT fields).", - " try:", - f" {patch_model}(**dto)", - " except ValidationError:", - ' return JSONResponse(status_code=400, content={"error": "validation"})', + *_validated_input_lines( + patch_model, + "FR-036: validate PRESENT, non-null values with the create rules (the", + "all-optional patch model never fires required-checks on ABSENT fields).", + ), # #203/ADR-0045: bump onUpdate @autoSet columns (server-owned) on EVERY patch, # above the repo seam — a server-inserted present key (compatible with the PATCH # present-key tristate); onCreate columns are never touched here. @@ -1468,6 +1508,9 @@ def _render_tph_router( parts.extend(_JSON_BODY_LINES) parts.append("") parts.append("") + parts.extend(_VALIDATED_INPUT_LINES) + parts.append("") + parts.append("") # FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so # the generated module always carries the seam (an entity that later gains a # writeOnce field changes one literal, not the module's shape). @@ -1547,11 +1590,9 @@ def list_sig(fn: str, route: str) -> list[str]: parts.append(") -> Any:") parts.extend(_DECIMAL_COERCE) parts.extend(denied_strip_tph) - parts.append(" # FR-036: run the subtype's field constraints before persisting.") - parts.append(" try:") - parts.append(f" {sub}Create(**dto)") - parts.append(" except ValidationError:") - parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})') + parts.extend(_validated_input_lines( + f"{sub}Create", "FR-036: run the subtype's field constraints before persisting." + )) # #203/ADR-0045: stamp @autoSet columns ABOVE the repo seam (empty for a # non-@autoSet hierarchy — byte-identical output). parts.extend(create_autoset) @@ -1584,11 +1625,9 @@ def list_sig(fn: str, route: str) -> list[str]: parts.append(" for _k in _REQUIRED_FIELDS:") parts.append(" if _k in dto and dto[_k] is None:") parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})') - parts.append(" # FR-036: validate PRESENT, non-null values with the subtype's create rules.") - parts.append(" try:") - parts.append(f" {sub}Patch(**dto)") - parts.append(" except ValidationError:") - parts.append(' return JSONResponse(status_code=400, content={"error": "validation"})') + parts.extend(_validated_input_lines( + f"{sub}Patch", "FR-036: validate PRESENT, non-null values with the subtype's create rules." + )) # #203/ADR-0045: pop the write-once onCreate column(s), bump onUpdate — ABOVE # the repo seam (empty for a non-@autoSet hierarchy — byte-identical output). parts.extend(update_autoset) @@ -1857,6 +1896,9 @@ def render_router( parts.extend(_JSON_BODY_LINES) parts.append("") parts.append("") + parts.extend(_VALIDATED_INPUT_LINES) + parts.append("") + parts.append("") # FR-037 R1 — the names a PATCH must never write. Emitted even when EMPTY so # the generated module always carries the seam (an entity that later gains a # writeOnce field changes one literal, not the module's shape). @@ -1892,8 +1934,8 @@ def render_router( create_autoset=create_autoset, update_autoset=update_autoset, # FR-037 R1 — ADR-0045: the ROUTER is the outermost write artifact for - # FastAPI (the handler binds the RAW body dict and hands THAT to the - # repository), so the strip has to live here, not in Patch. + # FastAPI (the handler binds the body as a dict), so the strip lives here, + # not in Patch. frozen_strip=_frozen_strip_lines(entity), denied_strip=_denied_strip_lines(denied_names), ) diff --git a/server/python/tests/integration/test_generated_router_validated_input.py b/server/python/tests/integration/test_generated_router_validated_input.py new file mode 100644 index 0000000000..b43ed21c08 --- /dev/null +++ b/server/python/tests/integration/test_generated_router_validated_input.py @@ -0,0 +1,272 @@ +"""1.2.1 security fix: a generated create / update hands the repository ONLY the validated input. + +The 1.2.0 router validated the request body against ``Create`` / ``Patch`` and +then passed the RAW body to the repository. Pydantic ignores a key a model does not declare, and +the input models leave out the server-owned fields, so a client-sent ``id``, a ``readOnly`` field +and a made-up ``isAdmin`` all reached the write. Now the repository receives only what the input +model validated, at every depth, as with the TypeScript routes: a name the entity does not +declare, a server-generated id, a ``readOnly`` field and the id on update are all dropped +silently. None of them is a 400: a client that sends an extra harmless field keeps working. + +The model is generated with the real Python codegen (``run_gen``: entity + filter-allowlist + +routes), the emitted package is imported unmodified, and the only hand-written piece is a +repository that records what it was handed. No database: the router is the artifact, as in the +other generated-router lanes. +""" +from __future__ import annotations + +import importlib +import json +import sys +import tempfile +import uuid +from pathlib import Path +from typing import Any + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from metaobjects import MetaDataLoader +from metaobjects.codegen.config import GenConfig +from metaobjects.codegen.generators.entity_model import entity_model +from metaobjects.codegen.generators.filter_allowlist_generator import filter_allowlist_generator +from metaobjects.codegen.generators.router_generator import router_generator +from metaobjects.codegen.runner import run_gen + +from .generated_tph_app import build_generated_tph_app + +_META = { + "metadata.root": { + "package": "acme::secfix", + "children": [ + {"object.value": { + "name": "Address", + "children": [ + {"field.string": {"name": "city", "@maxLength": 40}}, + ], + }}, + {"object.entity": { + "name": "Member", + "children": [ + {"source.rdb": {"@table": "members"}}, + {"field.long": {"name": "id"}}, + {"field.string": {"name": "name", "@required": True, "@maxLength": 80}}, + {"field.string": {"name": "role", "@maxLength": 20, "@mutability": "readOnly"}}, + {"field.string": {"name": "tenant", "@maxLength": 20, "@mutability": "writeOnce"}}, + {"field.object": {"name": "address", "@objectRef": "Address", "@storage": "jsonb"}}, + {"field.timestamp": {"name": "createdAt", "@autoSet": "onCreate"}}, + {"identity.primary": {"name": "id", "@fields": "id", "@generation": "increment"}}, + ], + }}, + {"object.entity": { + "name": "Account", + "children": [ + {"source.rdb": {"@table": "accounts"}}, + {"field.string": {"name": "code", "@maxLength": 20}}, + {"field.string": {"name": "label", "@maxLength": 80}}, + {"identity.primary": {"name": "code", "@fields": "code"}}, + ], + }}, + ], + } +} + + +class _RecordingRepo: + """The generated repository seam, recording every write it is handed.""" + + def __init__(self, pk: str) -> None: + self.pk = pk + self.writes: list[tuple[str, dict[str, Any]]] = [] + + def create(self, dto: Any) -> Any: + self.writes.append(("create", dict(dto))) + return {self.pk: 1, **dto} + + def update(self, id: Any, dto: Any) -> Any | None: + self.writes.append(("update", dict(dto))) + return {self.pk: id, **dto} + + +def _generate_package() -> str: + """Run the real Python codegen for ``_META`` into a temp package; return its name.""" + meta_dir = Path(tempfile.mkdtemp(prefix="secfix-meta-")) + (meta_dir / "meta.json").write_text(json.dumps(_META)) + loaded = MetaDataLoader.from_directory(str(meta_dir)) + assert not loaded.errors, "; ".join(f"{e.code}: {e.message}" for e in loaded.errors) + pkg = f"secfix_{uuid.uuid4().hex[:8]}" + root = Path(tempfile.mkdtemp(prefix="secfix-gen-")) + run_gen( + GenConfig(out_dir=str(root / pkg)), + loaded.root, + generators=[entity_model(), filter_allowlist_generator(), router_generator()], + ) + sys.path.insert(0, str(root)) + return pkg + + +_PKG = _generate_package() + + +def _client(router_module: str, pk: str) -> tuple[TestClient, _RecordingRepo, str]: + mod = importlib.import_module(f"{_PKG}.{router_module}") + repo = _RecordingRepo(pk) + app = FastAPI() + app.include_router(mod.router) + app.dependency_overrides[mod.get_repository] = lambda: repo + return TestClient(app), repo, mod.router.prefix + + +@pytest.fixture() +def member() -> tuple[TestClient, _RecordingRepo, str]: + return _client("member_router", "id") + + +@pytest.fixture() +def account() -> tuple[TestClient, _RecordingRepo, str]: + return _client("account_router", "code") + + +# --- the reported defect: a client-sent id and a made-up isAdmin reach the repository ------- + + +def test_create_never_hands_the_repository_a_client_id_or_an_undeclared_field(member) -> None: + client, repo, base = member + resp = client.post(base, json={"id": 999, "name": "Mallory", "isAdmin": True}) + assert resp.status_code == 201, resp.text + [(op, written)] = repo.writes + assert op == "create" + assert set(written) == {"name", "createdAt"} # createdAt is the router's own stamp + assert written["name"] == "Mallory" + + +@pytest.mark.parametrize("method", ["PATCH", "PUT"]) +def test_update_never_hands_the_repository_an_undeclared_field(member, method: str) -> None: + client, repo, base = member + resp = client.request(method, f"{base}/1", json={"name": "M", "isAdmin": True}) + assert resp.status_code == 200, resp.text + assert repo.writes == [("update", {"name": "M"})] + + +def test_an_undeclared_key_inside_a_value_object_never_reaches_the_repository(member) -> None: + client, repo, base = member + resp = client.post(base, json={"name": "Mallory", "address": {"city": "Oslo", "isAdmin": True}}) + assert resp.status_code == 201, resp.text + [(_op, written)] = repo.writes + assert written["address"] == {"city": "Oslo"} + + +def test_a_malformed_value_on_a_settable_field_is_still_a_400(member) -> None: + client, repo, base = member + resp = client.post(base, json={"name": "x" * 81, "isAdmin": True}) + assert resp.status_code == 400, resp.text + assert resp.json() == {"error": "validation"} + assert repo.writes == [] + + +# --- declared but not settable: dropped, never 400'd, and never handed to the repository ---- + + +def test_create_strips_the_client_id_and_a_read_only_field(member) -> None: + client, repo, base = member + resp = client.post( + base, + json={"id": 999, "name": "Mallory", "role": "admin", "tenant": "t1", + "address": {"city": "Oslo"}}, + ) + assert resp.status_code == 201, resp.text + [(op, written)] = repo.writes + assert op == "create" + # The server generates the id and owns `role`; `createdAt` is the router's own stamp. + assert set(written) == {"name", "tenant", "address", "createdAt"} + assert written["name"] == "Mallory" + assert written["tenant"] == "t1" # writeOnce is settable on create + assert written["address"] == {"city": "Oslo"} + + +@pytest.mark.parametrize("method", ["PATCH", "PUT"]) +def test_update_never_hands_the_repository_the_id_or_a_frozen_field(member, method: str) -> None: + client, repo, base = member + resp = client.request( + method, + f"{base}/1", + json={"id": 999, "name": "M2", "role": "admin", "tenant": "t2", "createdAt": "2000-01-01T00:00:00Z"}, + ) + assert resp.status_code == 200, resp.text + assert repo.writes == [("update", {"name": "M2"})] + + +def test_update_passes_a_present_null_through_as_a_clear(member) -> None: + """The PATCH present-key tristate is unchanged: an explicit null on a nullable field clears it.""" + client, repo, base = member + resp = client.patch(f"{base}/1", json={"address": None}) + assert resp.status_code == 200, resp.text + assert repo.writes == [("update", {"address": None})] + + +def test_an_assigned_key_is_still_the_callers_on_create_and_route_owned_on_update(account) -> None: + client, repo, base = account + created = client.post(base, json={"code": "ACME", "label": "Acme"}) + assert created.status_code == 201, created.text + updated = client.patch(f"{base}/ACME", json={"code": "EVIL", "label": "Acme 2"}) + assert updated.status_code == 200, updated.text + assert repo.writes == [ + ("create", {"code": "ACME", "label": "Acme"}), + ("update", {"label": "Acme 2"}), + ] + + +# --- TPH: the per-subtype create / update handlers are a separate code path ----------------- + + +def _find_tph_dir() -> Path: + cur = Path(__file__).resolve() + while cur != cur.parent: + candidate = cur / "fixtures" / "api-contract-conformance" / "tph" + if candidate.is_dir(): + return candidate + cur = cur.parent + raise RuntimeError("fixtures/api-contract-conformance/tph not found") + + +@pytest.fixture() +def tph() -> tuple[TestClient, list[tuple[str, str, dict[str, Any]]]]: + app, repo = build_generated_tph_app(_find_tph_dir()) + writes: list[tuple[str, str, dict[str, Any]]] = [] + create, update = repo.create, repo.update + + def recording_create(subtype: str, dto: Any) -> Any: + writes.append(("create", subtype, dict(dto))) + return create(subtype, dto) + + def recording_update(subtype: str, id: int, dto: Any) -> Any: + writes.append(("update", subtype, dict(dto))) + return update(subtype, id, dto) + + repo.create, repo.update = recording_create, recording_update + return TestClient(app), writes + + +def test_tph_subtype_create_drops_the_client_id_and_an_undeclared_field(tph) -> None: + client, writes = tph + resp = client.post( + "/api/auths/bridge", json={"id": 999, "reference": "R-1", "quantity": 2, "isAdmin": True} + ) + assert resp.status_code == 201, resp.text + [(op, subtype, written)] = writes + assert (op, subtype) == ("create", "Bridge") + assert "id" not in written + assert "isAdmin" not in written + assert {"reference", "quantity"} <= set(written) + + +def test_tph_subtype_update_drops_the_id_and_an_undeclared_field(tph) -> None: + client, writes = tph + # The store is unseeded, so the answer is a 404; what matters is what the write was handed. + client.patch("/api/auths/bridge/1", json={"id": 999, "quantity": 3, "isAdmin": True}) + [(op, subtype, written)] = writes + assert (op, subtype) == ("update", "Bridge") + assert "id" not in written + assert "isAdmin" not in written + assert written["quantity"] == 3 diff --git a/server/python/uv.lock b/server/python/uv.lock index 2999705817..a3b21881ca 100644 --- a/server/python/uv.lock +++ b/server/python/uv.lock @@ -399,7 +399,7 @@ wheels = [ [[package]] name = "metaobjects" -version = "1.2.0" +version = "1.2.1" source = { editable = "." } dependencies = [ { name = "pyyaml" }, From 499c413e83e9ffe13b2c99a8ad403e97ac66adfb Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 13:49:42 -0500 Subject: [PATCH 171/267] fix(checks): a TPH subtype's columns get their CHECKs on the base's table The CHECKs of a discriminator base's table were built from the base's own fields only, in meta migrate and in the C# EF context, so an enum or validator on a column a subtype folds into the shared table had none, and a subtype's cross-field validator was enforced nowhere. A subtype-only column's field-level CHECK is the base-column text, unguarded (a CHECK refuses only FALSE; a sibling's row holds NULL there). A subtype's cross-field validator is guarded by the discriminator, as an @condition ANDed with its own. The shared CHECK corpus gains a TPH input. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 ++++ .../check-constraint-conformance/README.md | 9 ++- .../expected.d1.json | 30 +++++++++ .../expected.postgres.json | 34 ++++++++++ .../expected.postgres.skip-redundant.json | 34 ++++++++++ .../expected.sqlite.json | 30 +++++++++ .../expected.sqlite.skip-redundant.json | 30 +++++++++ .../input/meta.tph.json | 66 +++++++++++++++++++ .../CheckConstraintConformanceTests.cs | 7 +- .../Generators/CheckConstraints.cs | 59 ++++++++++++++++- .../migrate-ts/src/expected-schema.ts | 63 ++++++++++++++++-- 11 files changed, 365 insertions(+), 10 deletions(-) create mode 100644 fixtures/check-constraint-conformance/input/meta.tph.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 26b8051eb7..fe51e114ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -557,6 +557,19 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, TypeScript and C#: a TPH subtype's columns get their CHECKs (rc.21).** `meta migrate`, + `meta verify --db` and the C# EF context built the CHECKs of a discriminator base's table from + the base's own fields only, so an enum or validator on a column a concrete subtype (or an + abstract level under the base) folds into the shared table had no database CHECK, and a + cross-field validator a subtype declared was enforced nowhere. The base's table now carries + them. A subtype-only column's field-level CHECK is the text a base column gets, with no + discriminator guard: a CHECK refuses only FALSE, and a sibling subtype's row holds NULL there. + A subtype's cross-field validator is guarded by the discriminator, as an `@condition` ANDed with + its own, listing every concrete subtype it reaches. The Drizzle schema already declared the + subtype enum CHECKs, so the two now agree. Pinned by `input/meta.tph.json` in the shared CHECK + corpus. **Upgrade note:** the next `meta migrate` (or EF migration) adds these CHECKs to an + existing TPH table; a legacy row outside a rule needs `@dbCheck: false` on that node first. + - **Fix, C#: a described `field.object` an `OwnedTypeConfig` override maps as a column no longer breaks the model build (G1).** `DbContextGenerator` assumed a non-flattened object field with no map is owned JSON, and whenever the field or its value object carried a `@description` it diff --git a/fixtures/check-constraint-conformance/README.md b/fixtures/check-constraint-conformance/README.md index 544973da5b..5a938bb4d5 100644 --- a/fixtures/check-constraint-conformance/README.md +++ b/fixtures/check-constraint-conformance/README.md @@ -1,6 +1,6 @@ # `check-constraint-conformance/` — the CHECKs one model gets, through either delivery path -One metadata input (`input/`) and the CHECK constraints `meta migrate` derives for it: every +The metadata input (`input/`) and the CHECK constraints `meta migrate` derives for it: every validator that can carry one (`validator.numeric`, `validator.length`, `validator.regex`, the cross-field `comparison` / `requiredWhen` / `presentIff` / `atLeastOne`, with an `@condition`) and every scalar `field.enum`. Each expected file maps a table to its CHECKs, in order, as a name @@ -29,6 +29,13 @@ The rules the corpus pins (ruling R55, which follows `meta migrate`): - no CHECK on an array column, and none on a derived (origin-bearing) field — it has no column — nor a cross-field CHECK naming one (`band`, an `origin.computed` reached by the `HighGadgets` projection's `@filter`); +- FR-017 TPH (`input/meta.tph.json`): the discriminator base's table carries its concrete + subtypes' CHECKs (`devices`). A subtype-only column's field-level CHECK is the text a base + column gets, unguarded — a CHECK refuses only FALSE, and a sibling's row holds NULL there. A + cross-field validator a subtype (or an abstract level, or a parent subtype) adds is guarded by + the discriminator, as an `@condition` ANDed with its own, listing every concrete subtype it + reaches (`powerRating` reaches `METER` and `SENSOR`). Subtypes in name order, fields + deduplicated by name as the column fold is; - a string-stored enum gets its membership CHECK and its `validator.length` CHECK, under `skipRedundant` too (`channel`); no regex CHECK on SQLite; `IS DISTINCT FROM` on Postgres, `IS NOT` on SQLite; `num_nonnulls` on Postgres, a sum of presence tests on SQLite. diff --git a/fixtures/check-constraint-conformance/expected.d1.json b/fixtures/check-constraint-conformance/expected.d1.json index 76c725c34a..c188de6cc4 100644 --- a/fixtures/check-constraint-conformance/expected.d1.json +++ b/fixtures/check-constraint-conformance/expected.d1.json @@ -68,5 +68,35 @@ "name": "gadgets_phone_atleastone_chk", "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.postgres.json b/fixtures/check-constraint-conformance/expected.postgres.json index 3cd7745287..b11e2dd872 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.json +++ b/fixtures/check-constraint-conformance/expected.postgres.json @@ -72,5 +72,39 @@ "name": "gadgets_phone_atleastone_chk", "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_serial_regex_chk", + "expression": "\"serial\" ~ '^M[0-9]+$'" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json index ac9f084b56..c61b39d11c 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json @@ -72,5 +72,39 @@ "name": "gadgets_phone_atleastone_chk", "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_serial_regex_chk", + "expression": "\"serial\" ~ '^M[0-9]+$'" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.sqlite.json b/fixtures/check-constraint-conformance/expected.sqlite.json index 76c725c34a..c188de6cc4 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.json @@ -68,5 +68,35 @@ "name": "gadgets_phone_atleastone_chk", "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + } ] } diff --git a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json index 27207ec778..9c24b2ea63 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json @@ -68,5 +68,35 @@ "name": "gadgets_phone_atleastone_chk", "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } + ], + "devices": [ + { + "name": "devices_kind_chk", + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + }, + { + "name": "devices_voltage_numeric_chk", + "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" + }, + { + "name": "devices_mode_chk", + "expression": "\"mode\" IN ('AUTO', 'MANUAL')" + }, + { + "name": "devices_label_length_chk", + "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" + }, + { + "name": "devices_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + }, + { + "name": "devices_unit_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" + }, + { + "name": "devices_label_cmp_chk", + "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + } ] } diff --git a/fixtures/check-constraint-conformance/input/meta.tph.json b/fixtures/check-constraint-conformance/input/meta.tph.json new file mode 100644 index 0000000000..321bcb376f --- /dev/null +++ b/fixtures/check-constraint-conformance/input/meta.tph.json @@ -0,0 +1,66 @@ +{ + "metadata.root": { + "package": "acme::checks", + "children": [ + { + "object.entity": { + "name": "Device", + "@discriminator": "kind", + "children": [ + { "source.rdb": { "@table": "devices" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@required": true, "@values": ["METER", "SENSOR", "SWITCH"] } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } + ] + } + }, + { + "object.entity": { + "name": "Powered", + "abstract": true, + "extends": "Device", + "children": [ + { "field.int": { "name": "voltage", "children": [ { "validator.numeric": { "@min": 1, "@max": 480 } } ] } }, + { "field.int": { "name": "watts" } }, + { "validator.atLeastOne": { "name": "powerRating", "@fields": ["voltage", "watts"] } } + ] + } + }, + { + "object.entity": { + "name": "Meter", + "extends": "Powered", + "@discriminatorValue": "METER", + "children": [ + { "field.string": { "name": "serial", "@required": true, "children": [ { "validator.regex": { "@pattern": "^M[0-9]+$" } } ] } } + ] + } + }, + { + "object.entity": { + "name": "Sensor", + "extends": "Powered", + "@discriminatorValue": "SENSOR", + "children": [ + { "field.enum": { "name": "mode", "@required": true, "@values": ["AUTO", "MANUAL"] } }, + { "field.string": { "name": "unit" } }, + { "validator.requiredWhen": { "name": "manualUnit", "@field": "unit", "@when": "mode", "@equals": "MANUAL" } } + ] + } + }, + { + "object.entity": { + "name": "Switch", + "extends": "Device", + "@discriminatorValue": "SWITCH", + "children": [ + { "field.string": { "name": "label", "children": [ { "validator.length": { "@min": 1, "@max": 12 } } ] } }, + { "field.enum": { "name": "legacyPosition", "@values": ["ON", "OFF"], "@dbCheck": false } }, + { "validator.comparison": { "name": "labelled", "@left": "label", "@op": "ne", "@right": "kind", + "@condition": { "op": "isNotNull", "arg": { "field": "label" } } } } + ] + } + } + ] + } +} diff --git a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs index 4e3580b90a..e4fd508bef 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs @@ -60,7 +60,8 @@ public void The_checks_are_meta_migrates_names_and_text(string file, string dial { var ctx = Ctx(Load(), dialect, skipRedundant); var actual = ctx.Root.Objects() - .Where(o => o.IsEntity() && o.DbTable is not null) + // A TPH subtype has no table of its own: its CHECKs are its base's (FR-017). + .Where(o => o.IsEntity() && o.DbTable is not null && !InstanceArtifacts.IsAbstract(o) && !TphPlanBuilder.IsTphSubtype(o, ctx.Root)) .Select(o => (Table: CSharpNaming.Table(o), Checks: CheckConstraints.For(o, ctx.Config))) .Where(t => t.Checks.Count > 0) .ToDictionary(t => t.Table, t => t.Checks.Select(c => (c.Name, c.Expression)).ToList()); @@ -84,6 +85,10 @@ public void The_context_declares_each_check_on_its_table() Assert.DoesNotContain("gadgets_legacy_state_chk", context); Assert.DoesNotContain("\\\"rank\\\" >= 1", context); Assert.Contains("t.HasCheckConstraint(\"gadgets_rank_numeric_chk\", \"\\\"rank\\\" <= 99\")", context); + // FR-017 TPH: a subtype's columns are on its base's table, and so are their CHECKs. + Assert.Contains("modelBuilder.Entity().ToTable(t => t.HasCheckConstraint(\"devices_mode_chk\", \"\\\"mode\\\" IN ('AUTO', 'MANUAL')\"));", context); + Assert.Contains("t.HasCheckConstraint(\"devices_unit_reqwhen_chk\", ", context); + Assert.DoesNotContain("devices_legacy_position_chk", context); } [Fact] diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index 4db2c691bb..d2c369d26d 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -45,7 +45,15 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co var strategy = config.ColumnNamingStrategy; var table = CSharpNaming.Table(entity); var checks = new List(); - foreach (var field in entity.Fields()) + // FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded + // columns (name-sorted subtypes, deduplicated by field name, as the column fold is), so it + // carries their CHECKs too. A subtype-only column's CHECK is the text a base column gets, + // with no discriminator guard: a CHECK refuses only FALSE, and a sibling subtype's row + // holds NULL there, for which every field-level expression is NULL. + var root = entity.Root() as MetaRoot; + var tph = root is null ? null : TphPlanBuilder.For(entity, root); + var fields = tph is null ? entity.Fields() : entity.Fields().Concat(TphPlanBuilder.CollectSubtypeFields(entity, root!)); + foreach (var field in fields) { // No field-level CHECK on an array column: every expression below is scalar-shaped. if (field.ResolvedIsArray()) continue; @@ -87,9 +95,47 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co if (CrossFieldCheck(v, entity, table, strategy, dialect) is { } check) checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); } + if (tph is not null) checks.AddRange(SubtypeCrossFieldChecks(entity, tph, table, strategy, dialect)); return checks; } + /// + /// FR-017 TPH: a cross-field validator a subtype adds holds for that subtype's rows only, so the + /// discriminator guards it — unlike a field-level CHECK, most cross-field rules are FALSE (not + /// NULL) over a sibling's NULL columns (atLeastOne, requiredWhen). The guard lists every concrete + /// subtype the validator reaches (one on an abstract level, or on a parent subtype, reaches each + /// of its concrete descendants), as an @condition ANDed with the validator's own. + /// + private static IEnumerable SubtypeCrossFieldChecks( + MetaObject entity, TphPlan tph, string table, ColumnNamingStrategy strategy, string? dialect) + { + var baseValidators = new HashSet(entity.Validators(), ReferenceEqualityComparer.Instance); + var reached = new List<(MetaValidator Validator, MetaObject Holder, List Values)>(); + foreach (var st in tph.Subtypes) + // ADR-0039: resolving — a validator on an abstract level or a parent subtype applies here too. + foreach (var v in st.Entity.Validators()) + { + if (baseValidators.Contains(v)) continue; + var i = reached.FindIndex(r => ReferenceEquals(r.Validator, v)); + if (i < 0) reached.Add((v, st.Entity, [st.Value])); + else reached[i].Values.Add(st.Value); + } + foreach (var (v, holder, values) in reached) + { + if (CrossFieldCheck(v, holder, table, strategy, dialect) is not { } check) continue; + IReadOnlyDictionary Eq(string value) => new Dictionary + { + [KeyOp] = FILTER_OP_EQ, + [KeyLeft] = new Dictionary { [KeyField] = tph.DiscriminatorField }, + [KeyRight] = new Dictionary { [KeyValue] = value }, + }; + var guard = values.Count == 1 + ? Eq(values[0]) + : new Dictionary { [KeyOp] = FILTER_COMPOSE_OR, [KeyArgs] = values.Select(x => (object?)Eq(x)).ToList() }; + yield return Named(WithCondition(check, v, holder, strategy, dialect, guard), v); + } + } + /// Whether a validator or field.enum opts out of its CHECK (@dbCheck: false, resolving). /// SkipRedundantChecks is independent of it: it only ever leaves more out. private static bool OptedOut(MetaData node) => node.Attr(VALIDATOR_ATTR_DB_CHECK) is false; @@ -215,9 +261,16 @@ private static (string Qcol, MetaField Field)? Ref(MetaObject entity, object? na /// A cross-field validator's @condition: the rule applies only when it holds, so the /// CHECK is the negated condition OR the rule. /// - private static CheckConstraint WithCondition(CheckConstraint check, MetaValidator v, MetaObject entity, ColumnNamingStrategy strategy, string? dialect) + private static CheckConstraint WithCondition( + CheckConstraint check, MetaValidator v, MetaObject entity, ColumnNamingStrategy strategy, string? dialect, + IReadOnlyDictionary? guard = null) { - if (v.Attr(VALIDATOR_ATTR_CONDITION) is not IReadOnlyDictionary condition) return check; + var own = v.Attr(VALIDATOR_ATTR_CONDITION) as IReadOnlyDictionary; + // A TPH subtype's validator holds only where its discriminator guard does (SubtypeCrossFieldChecks). + var condition = guard is null + ? own + : own is null ? guard : new Dictionary { [KeyOp] = FILTER_COMPOSE_AND, [KeyArgs] = new List { guard, own } }; + if (condition is null) return check; string? Column(string name) => entity.Fields().FirstOrDefault(f => f.Name == name) is { } f ? Quote(CSharpNaming.Column(f, strategy)) : null; // An int-backed enum stores a member as its integer; a duration in the form its column stores. diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index cd822da951..84c5224c4f 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -683,7 +683,7 @@ function buildTable( columns, indexes: buildSecondaryIndexes(entity, tableName, strategy), foreignKeys: buildForeignKeys(entity, tableName, resolveTargetTable, root, strategy, fkCtx, onConflict), - checks: buildChecks(entity, tableName, strategy, dialect, skipRedundantChecks), + checks: buildChecks(entity, tableName, strategy, dialect, skipRedundantChecks, root), primaryKey, }; const entityDesc = readDescription(entity); @@ -891,9 +891,27 @@ function buildChecks( strategy: ColumnNamingStrategy, dialect: Dialect | undefined, skipRedundant: boolean, + root?: MetaData, ): CheckDescriptor[] { const checks: CheckDescriptor[] = []; - for (const field of entity.fields()) { + // FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded + // columns, so it carries their CHECKs too — in name order, so every port lists them alike. + const subtypes = root === undefined ? [] : [...tphConcreteSubtypes(entity, root)] + .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + // A subtype-only column's CHECK is the text a base column gets, with no discriminator guard: + // a CHECK refuses only FALSE, and a sibling subtype's row holds NULL there, for which every + // field-level expression is NULL. Deduplicated by field name, as the column fold is. + const baseFieldNames = new Set(entity.fields().map((f) => f.name)); + const subtypeFields: MetaField[] = []; + for (const sub of subtypes) { + // ADR-0039: effective fields — a field on an abstract intermediate level is a column too. + for (const field of sub.fields()) { + if (baseFieldNames.has(field.name)) continue; + baseFieldNames.add(field.name); + subtypeFields.push(field); + } + } + for (const field of [...entity.fields(), ...subtypeFields]) { // No field-level CHECKs on array columns: the derived expressions assume a // SCALAR column. `"labels" IN ('A','B')` against a text[] is a type error at // CREATE TABLE; `length(col)`/range checks are equally scalar-shaped. Array @@ -966,6 +984,35 @@ function buildChecks( const check = crossFieldCheck(v, entity, tableName, strategy, dialect); if (check) checks.push(withDeclaredName(withCondition(check, v, entity, strategy, dialect), v)); } + // FR-017 TPH: a cross-field validator a subtype adds holds for that subtype's rows only — + // the discriminator guards it, because unlike a field-level CHECK most cross-field rules are + // FALSE (not NULL) over a sibling's NULL columns (atLeastOne, requiredWhen). The guard lists + // every concrete subtype the validator reaches (an abstract level's, or a parent subtype's, + // reaches each of its concrete descendants), as an @condition ANDed with the validator's own. + const discriminator = entity.attr(OBJECT_ATTR_DISCRIMINATOR); + if (typeof discriminator === "string" && subtypes.length > 0) { + const baseValidators = new Set(entity.validators()); + const reached = new Map(); + for (const sub of subtypes) { + // ADR-0039: effective — @discriminatorValue may be inherited (sub-subtype). + const value = String(sub.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE)); + // ADR-0039: effective validators — one declared on an abstract level or a parent subtype applies here too. + for (const v of sub.validators()) { + if (baseValidators.has(v)) continue; + const entry = reached.get(v); + if (entry === undefined) reached.set(v, { holder: sub, values: [value] }); + else entry.values.push(value); + } + } + for (const [v, { holder, values }] of reached) { + const check = crossFieldCheck(v, holder, tableName, strategy, dialect); + if (!check) continue; + const eq = (value: string): ExprNode => + ({ op: "eq", left: { field: discriminator }, right: { value } }) as unknown as ExprNode; + const guard = values.length === 1 ? eq(values[0]!) : ({ op: "or", args: values.map(eq) } as unknown as ExprNode); + checks.push(withDeclaredName(withCondition(check, v, holder, strategy, dialect, guard), v)); + } + } return checks; } @@ -1110,9 +1157,15 @@ function checkDeclaredCheckNames(tables: readonly TableDescriptor[], dialect: Di */ function withCondition( check: CheckDescriptor, v: MetaValidator, entity: MetaObject, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, + guard?: ExprNode, ): CheckDescriptor { - const condition = v.attr(VALIDATOR_ATTR_CONDITION); - if (condition === undefined || condition === null || typeof condition !== "object") return check; + const declared = v.attr(VALIDATOR_ATTR_CONDITION); + const own = declared === undefined || declared === null || typeof declared !== "object" ? undefined : (declared as ExprNode); + // A TPH subtype's validator holds only where its discriminator guard does (buildChecks). + const condition: ExprNode | undefined = guard === undefined + ? own + : own === undefined ? guard : ({ op: "and", args: [guard, own] } as unknown as ExprNode); + if (condition === undefined) return check; const column = (name: string): string | undefined => { const field = entity.fields().find((f) => f.name === name); return field === undefined ? undefined : quoteCheckCol(resolveColumnName(field, strategy)); @@ -1126,7 +1179,7 @@ function withCondition( const n = intMap === undefined || typeof value !== "string" ? undefined : intMap[value]; return typeof n === "number" ? String(n) : undefined; }; - const unless = renderExpressionSql(negateExpression(condition as ExprNode), column, dialect, stored); + const unless = renderExpressionSql(negateExpression(condition), column, dialect, stored); return { ...check, expression: `(${unless}) OR (${check.expression})` }; } From bc79f696d268441ff0276deb883c2d1179fda611 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 13:52:00 -0500 Subject: [PATCH 172/267] fix(codegen-ts): a projection extender with only its own source gets its view viewIsDerived read the projection's own children, so an extender adding nothing but its own view source had no anchor or origin and was dropped from the expected schema silently. It reads the effective children now. The audit found the same own read in the @sql view's dependsOn, which missed the anchor tables an extender inherits. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++++ .../src/projection/build-projection-views.ts | 21 ++++++++++------ .../projection-extends-projection.test.ts | 25 +++++++++++++++++++ 3 files changed, 47 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe51e114ba..4538f932c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -557,6 +557,14 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, TypeScript: a projection extender that declares only its own source gets its view + (rc.21).** `meta migrate` decided whether a projection's view is derived from the projection's + OWN children, so a projection that extends another projection and adds nothing but its own + `source.rdb` (`@kind: view`) had no anchor or origin of its own and was dropped from the + expected schema with no error. It now reads the effective children, as the view builder already + does (G13). The same audit fixed an `@sql` extender's dependencies: they now include the anchor + tables it inherits, so a column change on its base table drops and recreates it. + - **Fix, TypeScript and C#: a TPH subtype's columns get their CHECKs (rc.21).** `meta migrate`, `meta verify --db` and the C# EF context built the CHECKs of a discriminator base's table from the base's own fields only, so an enum or validator on a column a concrete subtype (or an diff --git a/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts b/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts index 2d81738ffe..bf4ab37213 100644 --- a/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts +++ b/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts @@ -361,8 +361,10 @@ function collectSqlDependsOn( const t = joinTables[host.resolutionKey()]; if (t !== undefined) tables.add(t); } - // Extends-bound anchor tables (a projection's read-model base). - for (const child of host.ownChildren()) { + // Extends-bound anchor tables (a projection's read-model base). ADR-0039: resolving — a + // projection extending another projection inherits its anchors, and so its dependencies + // (rc.21, U5 audit: an `@sql` extender with no anchor of its own had none). + for (const child of host.children()) { if (child.type !== TYPE_IDENTITY && child.type !== TYPE_FIELD) continue; const owner = refNamedOwner(child, root); if (owner === undefined) continue; @@ -407,17 +409,22 @@ function collectSqlDependsOn( * for custom SQL views and matviews — not a new hole. What changes is only that ONE * such view no longer blocks migration of every other entity in the tree. * - * ADR-0039: own — a projection's derivation is declared locally; an inherited extends or - * origin belongs to the parent's own view. + * ADR-0039: resolving — a projection that extends another projection (G13) inherits its + * anchors and its fields' origins, and its view is derived from them exactly as the base's is + * (`extractViewSpec` reads the effective fields, and `baseEntityFor` falls back to the super's + * anchor). Reading own children here dropped an extender that declares nothing but its own + * source, silently (rc.21, U5). Each field's origin is still read from that field node's own + * children: origin.* never inherits (ADR-0029), and an inherited field IS the parent's node. */ function viewIsDerived(projection: MetaObject): boolean { - const own = projection.ownChildren(); - const anchored = own.some( + const effective = projection.children(); + const anchored = effective.some( (c) => (c.type === TYPE_IDENTITY || c.type === TYPE_FIELD) && c.superRef !== undefined, ); if (anchored) return true; // Origins without an anchor = malformed, not standalone. Let extractViewSpec say so. - return own.some( + return effective.some( + // ADR-0039: own (category 4) — origin.* never inherits (ADR-0029). (f) => f.type === TYPE_FIELD && f.ownChildren().some((c) => c.type === TYPE_ORIGIN), ); } diff --git a/server/typescript/packages/codegen-ts/test/projection/projection-extends-projection.test.ts b/server/typescript/packages/codegen-ts/test/projection/projection-extends-projection.test.ts index fc49f4091a..3ac8a3000f 100644 --- a/server/typescript/packages/codegen-ts/test/projection/projection-extends-projection.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/projection-extends-projection.test.ts @@ -59,6 +59,31 @@ describe("G13 — a projection extending a projection", () => { expect(buildProjectionViews(root, { dialect: "postgres" }).map((v) => v.name).sort()).toEqual(["v_da_plans", "v_plan_extract"]); }); + // rc.21 (U5): an extender that declares nothing but its own source still gets its view — + // `viewIsDerived` read the extender's own children, found no anchor and no origin, and dropped + // the projection silently. + test("an extender declaring only its own source gets the inherited view", async () => { + const bare = { "object.projection": { name: "PlanCopy", extends: "PlanExtract", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_plan_copy" } }, + ] } }; + const { root, errors } = await load([base(true), bare]); + expect(errors).toEqual([]); + const views = buildProjectionViews(root, { dialect: "postgres" }); + expect(views.map((v) => v.name)).toEqual(["v_plan_copy"]); + expect(views[0]!.sql).toMatch(/p\.id AS plan_id,\s+p\.name AS label,\s+COUNT\(DISTINCT w\.id\) AS week_count/); + }); + + // rc.21 (U5 audit): an `@sql` extender's dependencies are the anchors it inherits. + test("an @sql extender depends on the base's anchor table", async () => { + const sqlCopy = { "object.projection": { name: "PlanSql", extends: "PlanExtract", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_plan_sql", "@sql": "SELECT id AS plan_id FROM plans" } }, + ] } }; + const { root, errors } = await load([base(true), sqlCopy]); + expect(errors).toEqual([]); + const view = buildProjectionViews(root, { dialect: "postgres" }).find((v) => v.name === "v_plan_sql"); + expect(view?.dependsOn).toEqual(["plans"]); + }); + test("an extender without its own source is refused, never emitted under the base's name", async () => { const { errors } = await load([base(false), extender(false)]); expect(errors.map((e) => String(e.message)).join("\n")).toMatch(/DataAggregationPlans' inherits a source/); From 8fcaf9b804f1a04d9b9548af1174487306c70589 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 13:54:24 -0500 Subject: [PATCH 173/267] fix(loader): a dotted extends with a missing member names the owner's members A dotted extends onto an identity the owner inherits already resolves, by the identity's name. An identity declared without a name is named after its subtype, so Owner.id (the identity spelled by its field) failed, and the error advised qualifying the owner with its package although the owner had resolved. The error now lists the owner's members of the referrer's type, inherited ones included, and gives the package advice only when the owner itself did not resolve. TypeScript and C#. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++ .../SuperResolveTests.cs | 46 +++++++++++++++++++ .../MetaObjects/Loader/MetaDataLoader.cs | 2 +- server/csharp/MetaObjects/SuperResolve.cs | 35 +++++++++++++- .../metadata/src/loader/meta-data-loader.ts | 2 +- .../packages/metadata/src/super-resolve.ts | 43 ++++++++++++++++- .../test/unresolved-super-hint.test.ts | 37 +++++++++++++++ 7 files changed, 170 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4538f932c0..0339de0ec5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -557,6 +557,17 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, TypeScript and C#: a dotted `extends` whose member is missing names the owner's members + (rc.21, U1).** `extends: "Authorization.id"` on an `identity.primary`, where `Authorization` + inherits its identity from an abstract base, failed with `ERR_UNRESOLVED_SUPER` and the advice to + qualify `Authorization` with its package, although `Authorization` had resolved. The member was + the problem: an identity declared without a name is named after its subtype (`primary`), and the + inherited one resolves as `Authorization.primary`, which already worked. The error now says + so: `'acme::auth::Authorization' has no identity named "id"; its identity children are: + "primary" (identity.primary). An identity.primary declared without a name is named "primary".` + The package advice is given only when the owner itself did not resolve. Java and Python keep + their message. + - **Fix, TypeScript: a projection extender that declares only its own source gets its view (rc.21).** `meta migrate` decided whether a projection's view is derived from the projection's OWN children, so a projection that extends another projection and adds nothing but its own diff --git a/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs b/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs index 682fa9bc49..17352c6187 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs @@ -24,4 +24,50 @@ public void Nonexistent_extends_collects_ERR_UNRESOLVED_SUPER() System.IO.Path.Combine(CorpusRoot.Path, "error-extends-nonexistent", "input")); Assert.Contains(result.Errors, e => e.Code == ErrorCode.ERR_UNRESOLVED_SUPER); } + + // rc.21 (U1): a projection over a TPH root anchors its identity on the root's identity, which the + // root inherits from an abstract base in another package. The identity is unnamed, so it is + // named "primary": `Authorization.primary` resolves through the inherited member, and + // `Authorization.id` (the identity spelled by its field) names the members it could have meant. + private static string U1Model(string target) => """ + { "metadata.root": { "package": "acme::common", "children": [ + { "object.entity": { "name": "BaseEntity", "abstract": true, "children": [ + { "field.int": { "name": "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } } + """ + "\u0000" + """ + { "metadata.root": { "package": "acme::auth", "children": [ + { "object.entity": { "name": "Authorization", "extends": "acme::common::BaseEntity", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "authorizations" } }, + { "field.string": { "name": "kind" } } ] } }, + { "object.entity": { "name": "PriorAuth", "extends": "Authorization", "@discriminatorValue": "Prior", "children": [ + { "field.string": { "name": "key" } } ] } }, + { "object.projection": { "name": "AuthView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_auth" } }, + { "field.int": { "name": "id", "extends": "Authorization.id" } }, + { "field.string": { "name": "key", "extends": "PriorAuth.key" } }, + { "identity.primary": { "extends": "TARGET" } } ] } } ] } } + """.Replace("TARGET", target); + + private static LoadResult LoadU1(string target) + { + var parts = U1Model(target).Split('\u0000'); + return new MetaDataLoader(FullCoreRegistry.Compose(), strict: true).Load([new InMemoryStringSource(parts[0], id: "common.json"), new InMemoryStringSource(parts[1], id: "auth.json")]); + } + + [Fact] + public void A_dotted_extends_resolves_an_identity_the_owner_inherits() + { + var result = LoadU1("Authorization.primary"); + Assert.Empty(result.Errors); + } + + [Fact] + public void A_dotted_extends_naming_a_missing_member_lists_the_owners_members() + { + var error = Assert.Single(LoadU1("Authorization.id").Errors, e => e.Code == ErrorCode.ERR_UNRESOLVED_SUPER); + Assert.Contains("'acme::auth::Authorization' has no identity named \"id\"; its identity children are: \"primary\" (identity.primary).", error.Message); + Assert.Contains("An identity.primary declared without a name is named \"primary\".", error.Message); + // The owner was found, so the same-named-object FQN advice would be wrong. + Assert.DoesNotContain("Qualify it with its package", error.Message); + } } diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index 847b4ce27c..eb825624c1 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -472,7 +472,7 @@ public LoadResult Load(IReadOnlyList sources) continue; } errors.Add(new MetaError( - $"the SuperClass '{failure.Ref}' does not exist (referenced by {failure.NodeFqn}){NamingRefs.DidYouMeanSuperHint(root, failure.Ref)}", + $"the SuperClass '{failure.Ref}' does not exist (referenced by {failure.NodeFqn}){failure.MemberHint ?? NamingRefs.DidYouMeanSuperHint(root, failure.Ref)}", ErrorCode.ERR_UNRESOLVED_SUPER, Envelope: envelope)); } diff --git a/server/csharp/MetaObjects/SuperResolve.cs b/server/csharp/MetaObjects/SuperResolve.cs index 8316596b13..8edda83465 100644 --- a/server/csharp/MetaObjects/SuperResolve.cs +++ b/server/csharp/MetaObjects/SuperResolve.cs @@ -231,7 +231,8 @@ public sealed record DeferredSuperFailure( MetaData? Node = null, SuperFailureKind Kind = SuperFailureKind.Unresolved, TypeIdentity? Target = null, - TypeIdentity? Referrer = null); + TypeIdentity? Referrer = null, + string? MemberHint = null); /// /// Resolve every node's SuperRef against the full root, collecting unresolved @@ -350,10 +351,40 @@ void ResolveNode(MetaData node) } else { - failures.Add(new DeferredSuperFailure(node.Fqn(), node.SuperRef, node)); + failures.Add(new DeferredSuperFailure(node.Fqn(), node.SuperRef, node, + MemberHint: DottedMemberHint(node, effectivePkg))); } } + // rc.21 (U1): a dotted ref whose OWNER resolves but whose member does not names the + // owner's members of the referrer's type, inherited ones included — the usual cause is an + // identity spelled by its field (`Owner.id`) where the identity is named otherwise (an + // unnamed identity.primary is "primary"). Without it the only hint was the same-named + // object's FQN, which is wrong advice when the owner was found. + string? DottedMemberHint(MetaData node, string pkg) + { + if (!IsChildTargetingRef(node.SuperRef!) || ParseChildTargetingRef(node.SuperRef!) is not { } parsed) return null; + if (TryResolve(parsed.OwnerRef, pkg) is not MetaData current) return null; + foreach (var seg in parsed.Path[..^1]) + { + var matches = current.Children().Where(c => c.Name == seg).ToList(); + if (matches.Count != 1) return null; + current = matches[0]; + } + var last = parsed.Path[^1]; + // ADR-0039: resolving — an inherited member is a legal target. + var candidates = current.Children().Where(c => c.Type == node.Type).ToList(); + var owner = current is MetaObject ? current.ResolutionKey() : current.Fqn(); + var listed = candidates.Count == 0 + ? $"it has no {node.Type} children" + : $"its {node.Type} children are: {string.Join(", ", candidates.Select(c => $"\"{c.Name}\" ({c.Type}.{c.SubType})"))}"; + // The default name of an unnamed identity.primary is its subtype (the registry's defaultName). + var unnamed = node.Type == BaseTypes.TYPE_IDENTITY && candidates.Any(c => c.Name == IdentityConstants.IDENTITY_SUBTYPE_PRIMARY) + ? $" An {BaseTypes.TYPE_IDENTITY}.{IdentityConstants.IDENTITY_SUBTYPE_PRIMARY} declared without a name is named \"{IdentityConstants.IDENTITY_SUBTYPE_PRIMARY}\"." + : ""; + return $" '{owner}' has no {node.Type} named \"{last}\"; {listed}.{unnamed}"; + } + foreach (var node in pending) ResolveNode(node); return failures.AsReadOnly(); } diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index 7d8d4b84f5..ad31e8eb53 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -608,7 +608,7 @@ export class MetaDataLoader { } errors.push( new ParseError( - `the SuperClass '${failure.ref}' does not exist (referenced by ${failure.nodeFqn})${didYouMeanSuperHint(root, failure.ref)}`, + `the SuperClass '${failure.ref}' does not exist (referenced by ${failure.nodeFqn})${failure.memberHint ?? didYouMeanSuperHint(root, failure.ref)}`, { code: "ERR_UNRESOLVED_SUPER", source: resolvedSource(failure.source, failure.nodeFqn, failure.ref), diff --git a/server/typescript/packages/metadata/src/super-resolve.ts b/server/typescript/packages/metadata/src/super-resolve.ts index aa81b086f0..78aa77874a 100644 --- a/server/typescript/packages/metadata/src/super-resolve.ts +++ b/server/typescript/packages/metadata/src/super-resolve.ts @@ -15,8 +15,8 @@ import type { MetaData } from "./shared/meta-data.js"; import { PACKAGE_SEPARATOR, CHILD_REF_SEPARATOR } from "./shared/structural.js"; import { ownerCandidateKeys, RefOverDropError } from "./naming-refs.js"; -import { TYPE_IDENTITY } from "./shared/base-types.js"; -import { IDENTITY_UNIQUE_KEY_SUBTYPES } from "./core/identity/identity-constants.js"; +import { TYPE_IDENTITY, TYPE_OBJECT } from "./shared/base-types.js"; +import { IDENTITY_SUBTYPE_PRIMARY, IDENTITY_UNIQUE_KEY_SUBTYPES } from "./core/identity/identity-constants.js"; // --------------------------------------------------------------------------- // Tree search helper @@ -223,6 +223,11 @@ export interface DeferredSuperFailure { target?: { type: string; subType: string }; /** target-mismatch only: the extending node's type/subtype, for the message. */ referrer?: { type: string; subType: string }; + /** + * unresolved dotted ref only (rc.21, U1): when the OWNER resolves but the member does not, a + * message suffix naming the owner's members of the referrer's type, inherited ones included. + */ + memberHint?: string; } /** @@ -344,15 +349,49 @@ export function resolveDeferredSupers(root: MetaData): DeferredSuperFailure[] { // set (e.g. Base extends AbstractRoot). Memoized — no re-work. resolveNode(target); } else { + const memberHint = dottedMemberHint(node, effectivePkg); failures.push({ nodeFqn: node.fqn(), ref: node.superRef, source: node.source, kind: "unresolved", + ...(memberHint !== undefined ? { memberHint } : {}), }); } }; + // rc.21 (U1): a dotted ref whose OWNER resolves but whose member does not names the owner's + // members of the referrer's type, inherited ones included — the usual cause is an identity + // spelled by its field (`Owner.id`) where the identity is named otherwise (an unnamed + // identity.primary is "primary"). Without it the only hint was the same-named object's FQN, + // which is wrong advice when the owner was found. + const dottedMemberHint = (node: MetaData, pkg: string): string | undefined => { + const ref = node.superRef; + if (ref === undefined || !isChildTargetingRef(ref)) return undefined; + const parsed = parseChildTargetingRef(ref); + if (parsed === undefined) return undefined; + const owner = tryResolve(parsed.ownerRef, pkg); + if (owner === undefined || owner === "over-drop") return undefined; + let current: MetaData = owner; + for (const seg of parsed.path.slice(0, -1)) { + const matches = current.children().filter((c) => c.name === seg); + if (matches.length !== 1) return undefined; + current = matches[0]!; + } + const last = parsed.path[parsed.path.length - 1]!; + // ADR-0039: resolving — an inherited member is a legal target. + const candidates = current.children().filter((c) => c.type === node.type); + const ownerName = current.type === TYPE_OBJECT ? current.resolutionKey() : current.fqn(); + const listed = candidates.length === 0 + ? `it has no ${node.type} children` + : `its ${node.type} children are: ${candidates.map((c) => `"${c.name}" (${c.type}.${c.subType})`).join(", ")}`; + // The default name of an unnamed identity.primary is its subtype (the registry's defaultName). + const unnamed = node.type === TYPE_IDENTITY && candidates.some((c) => c.name === IDENTITY_SUBTYPE_PRIMARY) + ? ` An ${TYPE_IDENTITY}.${IDENTITY_SUBTYPE_PRIMARY} declared without a name is named "${IDENTITY_SUBTYPE_PRIMARY}".` + : ""; + return ` '${ownerName}' has no ${node.type} named "${last}"; ${listed}.${unnamed}`; + }; + for (const node of pending) resolveNode(node); return failures; } diff --git a/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts b/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts index 1fca9b71d5..c7089b83d9 100644 --- a/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts +++ b/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts @@ -29,3 +29,40 @@ describe("ERR_UNRESOLVED_SUPER names the fix", () => { expect(err!.message).not.toContain("exists in"); }); }); + +// rc.21 (U1): a projection over a TPH root anchors its identity on the root's identity, which the +// root inherits from an abstract base in another package. The identity is unnamed, so it is named +// "primary": `Authorization.primary` resolves through the inherited member, and `Authorization.id` +// (the identity spelled by its field) names the members it could have meant. +describe("a dotted extends onto an inherited identity", () => { + const common = JSON.stringify({ "metadata.root": { package: "acme::common", children: [ + { "object.entity": { name: "BaseEntity", abstract: true, children: [ + { "field.int": { name: "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } }); + const auth = (target: string) => JSON.stringify({ "metadata.root": { package: "acme::auth", children: [ + { "object.entity": { name: "Authorization", extends: "acme::common::BaseEntity", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "authorizations" } }, + { "field.string": { name: "kind" } } ] } }, + { "object.entity": { name: "PriorAuth", extends: "Authorization", "@discriminatorValue": "Prior", children: [ + { "field.string": { name: "key" } } ] } }, + { "object.projection": { name: "AuthView", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_auth" } }, + { "field.int": { name: "id", extends: "Authorization.id" } }, + { "field.string": { name: "key", extends: "PriorAuth.key" } }, + { "identity.primary": { extends: target } } ] } } ] } }); + const load = (target: string) => new MetaDataLoader({ strict: true }).load([ + new InMemoryStringSource(common, { id: "common.json", format: "json" }), + new InMemoryStringSource(auth(target), { id: "auth.json", format: "json" }), + ]); + + test("resolves through the member the owner inherits", async () => { + expect((await load("Authorization.primary")).errors).toEqual([]); + }); + + test("a missing member lists the owner's members, not a package qualification", async () => { + const err = (await load("Authorization.id")).errors.find((e) => (e as { code?: string }).code === "ERR_UNRESOLVED_SUPER"); + expect(err!.message).toContain(`'acme::auth::Authorization' has no identity named "id"; its identity children are: "primary" (identity.primary).`); + expect(err!.message).toContain(`An identity.primary declared without a name is named "primary".`); + expect(err!.message).not.toContain("Qualify it with its package"); + }); +}); From dbd890b9efa41fc82f52b0908f866e23290579c7 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 13:55:43 -0500 Subject: [PATCH 174/267] fix(loader): a @via hop under a guessed name lists the reverse hops The first hop from a projection's base entity already walks a reference backwards, named by the holder's collection name. When @collectionName is singular that name is hard to guess, and the refusal did not say what it was. It now lists every reverse hop onto the entity and the reference each walks. TypeScript and C#. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++ .../ReverseHopHintTests.cs | 49 +++++++++++++++++++ .../MetaObjects/Loader/ValidationPasses.cs | 3 +- .../MetaObjects/Meta/ReverseReferenceHops.cs | 30 ++++++++++++ .../projection/reverse-reference-hop.test.ts | 20 ++++++++ .../src/core/relationship/find-reference.ts | 32 ++++++++++++ .../typescript/packages/metadata/src/index.ts | 2 +- .../metadata/src/loader/validation-passes.ts | 5 +- 8 files changed, 146 insertions(+), 4 deletions(-) create mode 100644 server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0339de0ec5..1fb8d29f42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -557,6 +557,15 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, TypeScript and C#: a `@via` hop under a guessed name lists the reverse hops (rc.21, U9).** + The first hop from a projection's base entity already walks an `identity.reference` backwards + (`Case.caseHistory` for `CaseHistory.caseId`), named by the holder's collection name, first + letter lowercased. A holder whose `@collectionName` is singular (`CaseHistory`) makes that name + hard to guess, and the refusal (`no such relationship or reference "histories" on Case`) did not + say what it was. It now ends `The reverse hops from Case are: "caseHistory" (walks + CaseHistory.caseId backwards) — …`. No hop name changes: an `@inverseName` spelling is not + accepted, because no registered vocabulary declares one. + - **Fix, TypeScript and C#: a dotted `extends` whose member is missing names the owner's members (rc.21, U1).** `extends: "Authorization.id"` on an `identity.primary`, where `Authorization` inherits its identity from an abstract base, failed with `ERR_UNRESOLVED_SUPER` and the advice to diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs new file mode 100644 index 0000000000..a2ff7d39ae --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs @@ -0,0 +1,49 @@ +// rc.21 (U9): the first @via hop from a projection's base entity already walks an +// identity.reference backwards, under the holder's collection name. An author who guesses the +// name (the reference's own name, a plural a @collectionName overrides) is now told the name the +// rule gives: the refusal lists the reverse hops onto the entity. + +using MetaObjects; +using MetaObjects.Loader; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class ReverseHopHintTests +{ + private static LoadResult Load(string via, string? collectionName = null) => + new MetaDataLoader(FullCoreRegistry.Compose(), strict: true).Load([new InMemoryStringSource($$""" + { "metadata.root": { "package": "acme::cases", "children": [ + { "object.entity": { "name": "Case", "children": [ + { "source.rdb": { "@table": "cases" } }, + { "field.int": { "name": "id" } }, { "field.int": { "name": "statusId" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } }, + { "object.entity": { "name": "CaseHistory", {{(collectionName is null ? "" : $"\"@collectionName\": \"{collectionName}\",")}} "children": [ + { "source.rdb": { "@table": "case_history" } }, + { "field.int": { "name": "id" } }, { "field.int": { "name": "caseId" } }, { "field.int": { "name": "statusId" } }, + { "field.timestamp": { "name": "createdDate" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, + { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "Case" } } ] } }, + { "object.projection": { "name": "CaseView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_case" } }, + { "field.int": { "name": "id", "extends": "Case.id" } }, + { "field.int": { "name": "statusId", "extends": "Case.statusId" } }, + { "field.timestamp": { "name": "statusDate", "children": [ { "origin.aggregate": { "@via": "{{via}}", "@of": "CaseHistory.createdDate", + "@agg": "min", "@filter": { "statusId": { "eq": { "field": "statusId" } } } } } ] } }, + { "identity.primary": { "name": "id", "extends": "Case.id" } } ] } } ] } } + """, id: "cases.json")]); + + [Fact] + public void The_first_hop_walks_the_reference_backwards_under_the_collection_name() + { + Assert.Empty(Load("Case.caseHistory", collectionName: "CaseHistory").Errors); + } + + [Fact] + public void A_guessed_hop_name_is_refused_naming_the_reverse_hops() + { + var error = Assert.Single(Load("Case.histories", collectionName: "CaseHistory").Errors); + Assert.Equal(ErrorCode.ERR_INVALID_ORIGIN, error.Code); + Assert.Contains("The reverse hops from Case are: \"caseHistory\" (walks CaseHistory.caseId backwards)", error.Message); + } +} diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index ac63829943..506a9f4f64 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1188,7 +1188,8 @@ private static bool IsReferenceHop(MetaData hop) errors.Add(new MetaError( $"origin.@via \"{viaAttr}\" on {projectionName}.{fieldName}: " + $"no such relationship or reference \"{relName}\" on {currentObj.Name}. " + - $"Deepest valid prefix was \"{prefix}\".", + $"Deepest valid prefix was \"{prefix}\"." + + (currentObj is MetaObject from && root is MetaRoot all ? ReverseReferenceHops.Hint(from, all.Objects()) : ""), ErrorCode.ERR_INVALID_ORIGIN, Envelope: ResolvedSource.From(originSource, referrer, viaAttr))); return null; diff --git a/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs b/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs index f450b73925..2c5f20875c 100644 --- a/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs +++ b/server/csharp/MetaObjects/Meta/ReverseReferenceHops.cs @@ -44,4 +44,34 @@ public static IReadOnlyList Find(MetaObject target, string } return found; } + + /// + /// rc.21 — every reverse hop a @via may take from : one per + /// identity.reference onto it from a concrete object, under that object's . + /// For the "no such relationship" message, so an author who guessed a hop name (the reference's + /// own name, a plural the holder's @collectionName overrides) sees the one the rule gives. + /// + public static IReadOnlyList<(string HopName, ReverseReferenceHop Hop)> OnTo(MetaObject target, IEnumerable objects) + { + var found = new List<(string, ReverseReferenceHop)>(); + foreach (var holder in objects) + { + if (holder.IsAbstract) continue; + foreach (var r in holder.ReferenceIdentities()) + // ADR-0059 R7: compare the bound target, never a short name. + if (ReferenceEquals(NamingRefs.RefTarget(r, IDENTITY_REFERENCE_ATTR_REFERENCES), target)) + found.Add((HopName(holder), new ReverseReferenceHop(holder, r))); + } + return found; + } + + /// The message suffix naming 's hops, or "" when there are none. + public static string Hint(MetaObject target, IEnumerable objects) + { + var hops = OnTo(target, objects); + if (hops.Count == 0) return ""; + return $" The reverse hops from {target.Name} are: " + + string.Join(", ", hops.Select(h => $"\"{h.HopName}\" (walks {h.Hop.Holder.Name}.{h.Hop.Reference.Name} backwards)")) + + " — a reverse hop is named by the holder's collection name (its @collectionName, else the plural), first letter lowercased."; + } } diff --git a/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts b/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts index 878efd3ff6..dbb3804827 100644 --- a/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/reverse-reference-hop.test.ts @@ -86,3 +86,23 @@ describe("R-walk — a @via hop over the reverse of an identity.reference", () = expect(String(errors[0]!.message)).toContain('"patient", "witness"'); }); }); + +// rc.21 (U9): the first hop from the base entity already walks a reference backwards; what an +// author who guesses the name (the reference's own name, a plural a @collectionName overrides) +// lacked was the name the rule gives. The refusal now lists the reverse hops onto the entity. +describe("a reverse hop under a guessed name", () => { + test("the refusal names the reverse hops onto the entity", async () => { + const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::care::Patient.consents", "acme::care::Patient.patient")); + const { errors } = await load(m); + const msg = errors.map((e) => String(e.message)).join("\n"); + expect(msg).toContain(`no such relationship or reference "patient" on Patient`); + expect(msg).toContain(`The reverse hops from Patient are: "consents" (walks Consent.patient backwards)`); + }); + + test("a @collectionName renames the hop, and the refusal says so", async () => { + const m = JSON.parse(JSON.stringify(MODEL).replaceAll("acme::care::Patient.consents", "acme::care::Patient.consents2")); + m["metadata.root"].children[1]["object.entity"]["@collectionName"] = "ConsentLog"; + const { errors } = await load(m); + expect(errors.map((e) => String(e.message)).join("\n")).toContain(`"consentLog" (walks Consent.patient backwards)`); + }); +}); diff --git a/server/typescript/packages/metadata/src/core/relationship/find-reference.ts b/server/typescript/packages/metadata/src/core/relationship/find-reference.ts index 452682ac4b..5db51a715c 100644 --- a/server/typescript/packages/metadata/src/core/relationship/find-reference.ts +++ b/server/typescript/packages/metadata/src/core/relationship/find-reference.ts @@ -110,3 +110,35 @@ export function findReverseReferenceHops( } return found; } + +/** + * rc.21 — every reverse hop a `@via` may take from `target`: one per identity.reference onto it + * from a concrete object, under that object's {@link reverseHopName}. For the "no such + * relationship" message, so an author who guessed a hop name (the reference's own name, a plural + * the holder's `@collectionName` overrides) sees the one the rule gives. + */ +export function reverseReferenceHopsOnto( + target: MetaObject, + objects: readonly MetaObject[], +): { hopName: string; hop: ReverseReferenceHop }[] { + const found: { hopName: string; hop: ReverseReferenceHop }[] = []; + for (const holder of objects) { + if (holder.isAbstract) continue; + for (const ref of holder.referenceIdentities()) { + // ADR-0059 R7: compare the bound target, never a short name. + if (refTarget(ref, IDENTITY_REFERENCE_ATTR_REFERENCES) === target) { + found.push({ hopName: reverseHopName(holder), hop: { holder, referenceIdentity: ref } }); + } + } + } + return found; +} + +/** The message suffix naming {@link reverseReferenceHopsOnto}'s hops, or "" when there are none. */ +export function reverseHopHint(target: MetaObject, objects: readonly MetaObject[]): string { + const hops = reverseReferenceHopsOnto(target, objects); + if (hops.length === 0) return ""; + return ` The reverse hops from ${target.name} are: ` + + hops.map((h) => `"${h.hopName}" (walks ${h.hop.holder.name}.${h.hop.referenceIdentity.name} backwards)`).join(", ") + + " — a reverse hop is named by the holder's collection name (its @collectionName, else the plural), first letter lowercased."; +} diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 6a4da0da07..3fc1429098 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -164,7 +164,7 @@ export { MetaRelationship } from "./core/relationship/meta-relationship.js"; // Cross-entity reference lookup export { resolveFlattenedMember, resolveFieldPathColumn, type FlattenedMember } from "./core/field/flattened-member.js"; export { - findReferenceBetween, findReferencesBetween, findReverseReferenceHops, reverseHopName, + findReferenceBetween, findReferencesBetween, findReverseReferenceHops, reverseHopName, reverseReferenceHopsOnto, reverseHopHint, type ReverseReferenceHop, } from "./core/relationship/find-reference.js"; export type { ReferenceLookup } from "./core/relationship/find-reference.js"; diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 32bb8f6a34..d49ba7eaf2 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -25,7 +25,7 @@ import { } from "../core/validator/validator-constants.js"; import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; -import { findReverseReferenceHops } from "../core/relationship/find-reference.js"; +import { findReverseReferenceHops, reverseHopHint } from "../core/relationship/find-reference.js"; import { resolveFlattenedMember } from "../core/field/flattened-member.js"; import { resolveFilterPath } from "../core/relationship/filter-path.js"; import { effectiveProjectionFilter } from "../core/object/effective-projection-filter.js"; @@ -799,7 +799,8 @@ function _validateViaPath( errors.push( new ParseError( `origin.@via "${viaAttr}" on ${projectionName}.${fieldName}: no such relationship or reference "${relName}" on ${currentObj.name}. ` + - `Deepest valid prefix was "${prefix}".`, + `Deepest valid prefix was "${prefix}".` + + (isMetaRoot(root) ? reverseHopHint(currentObj as MetaObject, root.objects()) : ""), { code: "ERR_INVALID_ORIGIN", source: resolvedSource(originSource, referrer, viaAttr), From 765a9f1a60622122d7ce4248578fdca85ce0e7ea Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 13:58:12 -0500 Subject: [PATCH 175/267] fix(names): no names entry for a derived field with no column A derived field of an entity read from its table is no column of that table, yet the names artifact named a column for it. It now emits no entry for such a field. A projection's or write-through entity's derived field is a column of its view and keeps its entry. TypeScript and C#. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++ .../NamesGeneratorTests.cs | 32 ++++++++++++++++- .../MetaObjects.Codegen/CSharpNaming.cs | 12 ++++--- .../packages/codegen-ts/src/names.ts | 16 ++++++--- .../test/names-derived-field.test.ts | 35 +++++++++++++++++++ 5 files changed, 95 insertions(+), 9 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/test/names-derived-field.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fb8d29f42..4131ef8d97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -557,6 +557,15 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, TypeScript and C#: `Names` has no entry for a derived field with no column + (rc.21, U7).** A derived (`origin.*`) field of an entity read from its table is no column of + that table (a projection that reaches it lowers it inline), yet the names artifact emitted a + `…Field`/`…Column` pair (C#) or a `fields..column` (TypeScript) for it, and a + `ColumnsByField` entry, all naming a column that does not exist. It now emits no entry for such + a field, so code reading one fails to compile instead of querying a missing column. A + projection's derived field is a column of its view, and a write-through entity's is a column of + its read view: both keep their entry. Java and Kotlin are unchanged (no entity-derived fields). + - **Fix, TypeScript and C#: a `@via` hop under a guessed name lists the reverse hops (rc.21, U9).** The first hop from a projection's base entity already walks an `identity.reference` backwards (`Case.caseHistory` for `CaseHistory.caseId`), named by the holder's collection name, first diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs index 09c8bb8701..924e8f6d5f 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs @@ -51,7 +51,7 @@ public class NamesGeneratorTests private static MetaRoot Load(string model) { var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "gen.json")]); - Assert.Empty(r.Errors); + Assert.Empty(r.Errors.Select(e => $"{e.Code}: {e.Message}")); return r.Root; } @@ -127,6 +127,36 @@ public void Emits_const_string_members_for_table_and_columns() Assert.Contains("public const string CreatedAtColumn = \"created_at\";", src); } + // rc.21 (U7): a derived field of a table-backed entity has no column, so the artifact names no + // column for it (no `…Field`/`…Column` pair, no ColumnsByField entry). A projection's derived + // field IS a column of its view and keeps its pair. + [Fact] + public void A_derived_field_of_a_table_entity_has_no_column_constant() + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Account", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "score" } }, + { "field.boolean": { "name": "isHigh", "children": [ { "origin.computed": { "@expr": { + "op": "gte", "left": { "field": "score" }, "right": { "value": 4 } } } } ] } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.projection": { "name": "AccountView", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_accounts" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "field.int": { "name": "doubled", "children": [ { "origin.computed": { "@expr": { + "fn": "coalesce", "args": [ { "field": "score" }, { "value": 0 } ] } } } ] } }, + { "identity.primary": { "name": "id", "extends": "Account.id" } } ] } } ] } } + """; + var files = new NamesGenerator().Generate(Ctx(Load(model))).ToList(); + var account = files.Single(f => f.Path.EndsWith("AccountNames.g.cs", StringComparison.Ordinal)).Content; + Assert.Contains("public const string ScoreColumn = \"score\";", account); + Assert.DoesNotContain("IsHigh", account); + var view = files.Single(f => f.Path.EndsWith("AccountViewNames.g.cs", StringComparison.Ordinal)).Content; + Assert.Contains("public const string DoubledColumn = \"doubled\";", view); + } + [Fact] public void An_explicit_column_wins_over_the_naming_strategy() { diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index 916e199790..f4a0fc7e6b 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -562,13 +562,16 @@ public static bool HasPrimarySource(MetaObject obj) => if (source is null) return null; var fields = new Dictionary(StringComparer.Ordinal); + // rc.21 (U7): a derived field of an object read from its table has no column, so it has + // no names entry — no `…Column` constant naming a column that does not exist. + var noColumn = source.IsWritable() && !obj.IsWriteThrough(); // ADR-0039: Fields() is the RESOLVING accessor — an inherited @column must // resolve here, or the constant disagrees with the column EF actually binds. - foreach (var f in obj.Fields()) + foreach (var f in obj.Fields().Where(f => !(noColumn && f.IsDerived()))) fields[f.Name] = FieldNamesOf(f, strategy); // ADR-0039's sanctioned own-accessor use: what this artifact DECLARES. var ownFields = new Dictionary(StringComparer.Ordinal); - foreach (var f in obj.OwnFields()) + foreach (var f in obj.OwnFields().Where(f => !(noColumn && f.IsDerived()))) ownFields[f.Name] = FieldNamesOf(f, strategy); var superObj = NamesArtifactSuperOf(obj); @@ -768,10 +771,11 @@ private static bool DeclaresNamesContent(MetaObject obj) => { strategy ??= ColumnNamingStrategy.SnakeCase; if (!DeclaresNamesContent(obj)) return null; - var own = obj.OwnFields(); + // rc.21 (U7): an abstract ENTITY's derived field is no column of the tables extending it. + var own = obj.OwnFields().Where(f => !(obj.IsEntity() && f.IsDerived())).ToList(); var fields = new Dictionary(StringComparer.Ordinal); - foreach (var f in obj.Fields()) + foreach (var f in obj.Fields().Where(f => !(obj.IsEntity() && f.IsDerived()))) fields[f.Name] = FieldNamesOf(f, strategy); var ownFields = new Dictionary(StringComparer.Ordinal); foreach (var f in own) diff --git a/server/typescript/packages/codegen-ts/src/names.ts b/server/typescript/packages/codegen-ts/src/names.ts index e5afa42dc5..c0beba56e2 100644 --- a/server/typescript/packages/codegen-ts/src/names.ts +++ b/server/typescript/packages/codegen-ts/src/names.ts @@ -15,6 +15,8 @@ import { resolveTableSchema, isMetaObject, isMetaSource, + isWritableSource, + OBJECT_SUBTYPE_ENTITY, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_STORAGE, FIELD_SUBTYPE_OBJECT, @@ -34,6 +36,7 @@ import { code, imp, type Code } from "ts-poet"; import { crossEntitySpecifier } from "./import-path.js"; import type { RenderContext } from "./render-context.js"; import { effectivePackage } from "./docs-paths.js"; +import { isWriteThrough } from "./projection/projection-detector.js"; /** * One field's names. `column` is the field's resolved column. @@ -362,12 +365,15 @@ export function resolveObjectNames( // level down from the one this file exists to prevent (a NAME resolved twice). const source = primaryRdbSource(obj); if (source === undefined) return undefined; - const ownFieldList = obj.ownFields(); + // rc.21 (U7): a derived field of an object read from its table has no column, so it has no + // names entry — no `column` naming a column that does not exist. + const columnless = (f: MetaField): boolean => isWritableSource(source) && !isWriteThrough(obj) && f.isDerived(); + const ownFieldList = obj.ownFields().filter((f) => !columnless(f)); const fields: Record = {}; // ADR-0039: fields() is the RESOLVING accessor — inherited fields must appear, and an // inherited @column must resolve, or the constant disagrees with the DDL. - for (const f of obj.fields()) { + for (const f of obj.fields().filter((x) => !columnless(x))) { fields[f.name] = fieldNamesOf(f, strategy); } // ADR-0039's sanctioned own-accessor use: what this artifact DECLARES. See ObjectNames. @@ -454,10 +460,12 @@ export function resolveSuperFragmentNames( strategy?: ColumnNamingStrategy, ): ObjectNames | undefined { if (!declaresNamesContent(obj)) return undefined; - const ownFieldList = obj.ownFields(); + // rc.21 (U7): an abstract ENTITY's derived field is no column of the tables extending it. + const columnless = (f: MetaField): boolean => obj.subType === OBJECT_SUBTYPE_ENTITY && f.isDerived(); + const ownFieldList = obj.ownFields().filter((f) => !columnless(f)); const fields: Record = {}; - for (const f of obj.fields()) { + for (const f of obj.fields().filter((x) => !columnless(x))) { fields[f.name] = fieldNamesOf(f, strategy); } const ownFields: Record = {}; diff --git a/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts b/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts new file mode 100644 index 0000000000..53ac29c557 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts @@ -0,0 +1,35 @@ +// rc.21 (U7): a derived (origin-bearing) field of a table-backed entity has no column — it is +// lowered where a projection reads it — so its names entry would name a column that does not +// exist. The artifact carries no entry for it. A projection's derived field IS a column of its +// view and keeps its entry. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource, isMetaObject, type MetaObject } from "@metaobjectsdev/metadata"; +import { resolveObjectNames } from "../src/names.js"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Account", children: [ + { "source.rdb": { "@table": "accounts" } }, + { "field.long": { name: "id" } }, + { "field.int": { name: "score" } }, + { "field.boolean": { name: "isHigh", children: [ { "origin.computed": { "@expr": { + op: "gte", left: { field: "score" }, right: { value: 4 } } } } ] } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "AccountView", "@filter": { isHigh: true }, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_accounts" } }, + { "field.long": { name: "id", extends: "Account.id" } }, + { "field.int": { name: "doubled", children: [ { "origin.computed": { "@expr": { + fn: "coalesce", args: [ { field: "score" }, { value: 0 } ] } } } ] } }, + { "identity.primary": { name: "id", extends: "Account.id" } } ] } } ] } }; + +describe("names of a derived field", () => { + test("a table entity's derived field has no names entry; a projection's keeps its column", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + const obj = (name: string) => root.objects().find((o) => o.name === name && isMetaObject(o)) as MetaObject; + const account = resolveObjectNames(obj("Account"))!; + expect(Object.keys(account.fields).sort()).toEqual(["id", "score"]); + expect(Object.keys(account.ownFields).sort()).toEqual(["id", "score"]); + expect(resolveObjectNames(obj("AccountView"))!.fields["doubled"]?.column).toBe("doubled"); + }); +}); From 0ddc75a10e4cc27acebda30baaa319c44d72f4c9 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 14:01:41 -0500 Subject: [PATCH 176/267] fix(csharp): a reference over a flattened member configures the owned type's navigation When the owned type carries a navigation to the target, EF's convention builds a relationship from it, and the generated navigation-less HasOne over the same columns made a second one with a shadow FK property. The relationship is now configured through the navigation EF found on the owned type over those FK properties, read from the model at build time, and navigation-less when there is none. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++++++++ .../Generators/DbContextGenerator.cs | 18 ++++++++++--- .../EfModelGapsTests.cs | 26 +++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4131ef8d97..f00261cf75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -557,6 +557,18 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, C#: a reference over a flattened member configures the owned type's own navigation + (rc.21, U6).** `identity.reference { @fields: address.countryId, @references: Country }` emitted + `OwnsOne(x => x.Address).HasOne().WithMany().HasForeignKey(e => e.CountryId)`. When the + owned type also carries a `Country` navigation (an adopter's partial class, say), EF's + convention builds a relationship from it as the owned type joins the model, so the + navigation-less call made a second one, with a shadow FK property (`CountryId1`) and a second + foreign key. The relationship is now configured through the navigation EF found on the owned + type over the same FK properties, read from the model at build time (`OwnsOne(x => x.Address, + b => b.HasOne()…)`), and navigation-less when there is + none. One foreign key, no shadow column, and `@onDelete` / `@constraintName` land on it. + Generated output changes for every reference over a flattened member. + - **Fix, TypeScript and C#: `Names` has no entry for a derived field with no column (rc.21, U7).** A derived (`origin.*`) field of an entity read from its table is no column of that table (a projection that reaches it lowers it inline), yet the names artifact emitted a diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 57016cdb3a..bf7507aec3 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -1566,7 +1566,8 @@ protected virtual IEnumerable ReferenceConfig( /// G6 (reference half): the relationship for a reference whose @fields are members of /// one flattened value object. The member properties live on the owned type, so the foreign /// key is configured on its builder, one statement: - /// modelBuilder.Entity<Plan>().OwnsOne(x => x.Address).HasOne<Country>().WithMany().HasForeignKey(e => e.CountryId). + /// modelBuilder.Entity<Plan>().OwnsOne(x => x.Address, b => b.HasOne<Country>(<nav>).WithMany().HasForeignKey(e => e.CountryId)), + /// where <nav> is the owned type's navigation to the target over those properties, if it has one. /// Fields spread over the entity and a value object, or over two value objects, have no EF /// mapping: the run warns and configures none. /// @@ -1583,11 +1584,22 @@ private IEnumerable FlattenedMemberReferenceConfig( var nav = PropertyName((MetaField)members[0]!.Embedding); var props = members.Select(m => PropertyName((MetaField)m!.Member)).ToList(); var actions = ReferentialActions.Resolve(entity, reference); - return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}).HasOne<{ValueObjectNames.GlobalRef(target, ctx.Config)}>()" + var targetRef = ValueObjectNames.GlobalRef(target, ctx.Config); + // rc.21 (U6): the owned type is the adopter's to extend (a partial with a navigation to the + // target is the usual shape), and EF's convention builds a relationship from such a navigation + // the moment the owned type joins the model. A second, navigation-less HasOne over the same + // columns would then be a second relationship, with a shadow FK beside it (`_1`). + // So the relationship is configured THROUGH the navigation EF found over these FK properties, + // when there is one, and navigation-less otherwise. Read from the model, not reflected. + var linq = "global::System.Linq.Enumerable"; + var fkNames = string.Join(", ", props.Select(p => $"\"{p}\"")); + var navigation = $"{linq}.FirstOrDefault(b.OwnedEntityType.GetNavigations(), n => n.TargetEntityType.ClrType == typeof({targetRef}) " + + $"&& {linq}.SequenceEqual({linq}.Select(n.ForeignKey.Properties, p => p.Name), new[] {{ {fkNames} }}))?.Name"; + return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.HasOne<{targetRef}>({navigation})" + $".WithMany().HasForeignKey({ForeignKeyExpression("e", props)})" + PrincipalKeyCall(reference, target) + $"{OnDeleteCall(entity, fkFields, actions.OnDelete, ctx)}" - + ConstraintNameCall(reference) + ";"]; + + ConstraintNameCall(reference) + ");"]; } /// diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index db588e3e4f..fa2cb72817 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -206,6 +206,32 @@ public void A_reference_over_a_flattened_member_is_a_foreign_key_of_the_owned_ty Assert.Equal(DeleteBehavior.Restrict, fk.DeleteBehavior); } + // rc.21 (U6): the owned type carries a navigation to the target (an adopter's hand-written + // member here, as a partial class would add). EF's convention builds the relationship from it, + // so the reference is configured through that navigation: ONE foreign key over CountryId, no + // shadow `CountryId1`, and the declared delete behaviour on it. + private sealed class AddressWithCountry : MetaObjects.Codegen.Generators.EntityGenerator + { + protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + { + if (entity.Name == "Address") + sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? Country {{ get; set; }}"); + } + } + + [Fact] + public void A_reference_over_a_flattened_member_uses_the_owned_types_navigation() + { + var gen = GeneratedEfModel.Compile(FlattenedReferenceModel, "Acme.FlatNav", entities: new AddressWithCountry()); + using var db = gen.ModelOnlyContext(); + var address = EntityType(db, "Plan").FindNavigation("Address")!.TargetEntityType; + var fk = Assert.Single(address.GetForeignKeys(), f => f.PrincipalEntityType.ClrType.Name == "Country"); + Assert.Equal(new[] { "CountryId" }, fk.Properties.Select(p => p.Name)); + Assert.Equal("Country", fk.DependentToPrincipal?.Name); + Assert.Equal(DeleteBehavior.Restrict, fk.DeleteBehavior); + Assert.DoesNotContain(address.GetProperties(), p => p.Name.StartsWith("CountryId", StringComparison.Ordinal) && p.Name != "CountryId"); + } + [Fact] public void A_reference_carries_its_constraint_name_and_its_principal_key_into_the_model() { From dc286e1cd3fd4ded15d94175b2e4076fe2f9125a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 14:12:27 -0500 Subject: [PATCH 177/267] feat(enum): @stringValueMap, a member's stored string (TypeScript) A string-stored field.enum may now declare the string each member is stored as ({member: string}), for a legacy column whose spelling differs from the member symbols. The string twin of @intValueMap: keys must match @values, values are unique non-empty strings, and it is refused with @intValueMap and on an array enum (ERR_BAD_ATTR_VALUE). TypeScript honours it in meta migrate (the CHECK, a @default, a @condition or @equals literal, the column length), the Drizzle column (a codec mapping member <-> stored string), the runtime ObjectManager (write, read and filter), and the view, report and Cube lowerings. Registered in the spec, so every port loads it; the other ports follow. Co-Authored-By: Claude Opus 5.5 --- examples/showcase/site-payload.json | 2 +- .../expected.d1.json | 14 ++++ .../expected.postgres.json | 14 ++++ .../expected.postgres.skip-redundant.json | 14 ++++ .../expected.sqlite.json | 14 ++++ .../expected.sqlite.skip-redundant.json | 14 ++++ .../input/meta.stored.json | 25 +++++++ .../enum-string-value-map/expected.json | 59 +++++++++++++++ .../input/meta.enums.json | 32 +++++++++ .../expected-errors.json | 15 ++++ .../input/meta.enums.json | 24 +++++++ .../expected-errors.json | 15 ++++ .../input/meta.enums.json | 23 ++++++ .../expected-errors.json | 15 ++++ .../input/meta.enums.json | 23 ++++++ .../expected-errors.json | 15 ++++ .../input/meta.enums.json | 24 +++++++ fixtures/metamodel-docs/expected/INDEX.md | 2 +- fixtures/metamodel-docs/expected/providers.md | 2 +- .../metamodel-docs/expected/types/field.md | 7 +- .../expected-registry.json | 13 +++- .../MetaObjects/SpecMetamodel/field.json | 9 +-- .../src/metaobjects/spec_metamodel/field.json | 9 +-- .../packages/codegen-ts/src/column-mapper.ts | 50 +++++++++++-- .../codegen-ts/src/cube/build-cube-model.ts | 4 +- .../codegen-ts/src/cube/cube-members.ts | 11 +-- .../packages/codegen-ts/src/enum-meta.ts | 13 +++- .../src/projection/extract-view-spec.ts | 25 +++---- .../codegen-ts/src/projection/report-sql.ts | 4 +- .../src/templates/enum-int-codec.ts | 28 ++++++++ .../test/drizzle-enum-stringvaluemap.test.ts | 71 +++++++++++++++++++ .../string-value-map-view-filter.test.ts | 22 ++++++ .../metadata/src/attr-schema-validate.ts | 47 ++++++++++++ .../metadata/src/core/field/enum-storage.ts | 29 ++++++++ .../src/core/field/field-constants.ts | 9 +++ .../core/field/field-definition.embedded.ts | 14 +++- .../packages/metadata/src/enum-length.ts | 8 +-- .../typescript/packages/metadata/src/index.ts | 1 + .../metadata/src/loader/validation-passes.ts | 12 ++-- .../field-definition-completeness.test.ts | 4 +- .../migrate-ts/src/expected-schema.ts | 18 ++++- .../migrate-ts/test/string-value-map.test.ts | 34 +++++++++ .../packages/runtime-ts/src/query-builder.ts | 7 +- .../packages/runtime-ts/src/type-coercer.ts | 48 ++++++++++++- .../test/string-value-map-codec.test.ts | 36 ++++++++++ site-reference/index.html | 2 +- site-reference/providers.html | 2 +- site-reference/types/field.html | 15 +++- spec/metamodel/field.json | 9 +-- 49 files changed, 834 insertions(+), 73 deletions(-) create mode 100644 fixtures/check-constraint-conformance/input/meta.stored.json create mode 100644 fixtures/conformance/enum-string-value-map/expected.json create mode 100644 fixtures/conformance/enum-string-value-map/input/meta.enums.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json create mode 100644 fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json create mode 100644 server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts create mode 100644 server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts create mode 100644 server/typescript/packages/metadata/src/core/field/enum-storage.ts create mode 100644 server/typescript/packages/migrate-ts/test/string-value-map.test.ts create mode 100644 server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 6a3c53abc1..91f83a2e98 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 464, + "fixtures": 468, "corpora": 38, "baseTypes": 17 }, diff --git a/fixtures/check-constraint-conformance/expected.d1.json b/fixtures/check-constraint-conformance/expected.d1.json index c188de6cc4..5201a31eab 100644 --- a/fixtures/check-constraint-conformance/expected.d1.json +++ b/fixtures/check-constraint-conformance/expected.d1.json @@ -69,6 +69,20 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], + "feeds": [ + { + "name": "feeds_status_chk", + "expression": "\"status\" IN ('pending', 'done', 'failed')" + }, + { + "name": "feeds_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "feeds_done_at_cmp_chk", + "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + } + ], "devices": [ { "name": "devices_kind_chk", diff --git a/fixtures/check-constraint-conformance/expected.postgres.json b/fixtures/check-constraint-conformance/expected.postgres.json index b11e2dd872..e7e431302e 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.json +++ b/fixtures/check-constraint-conformance/expected.postgres.json @@ -73,6 +73,20 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], + "feeds": [ + { + "name": "feeds_status_chk", + "expression": "\"status\" IN ('pending', 'done', 'failed')" + }, + { + "name": "feeds_error_reqwhen_chk", + "expression": "(\"status\" IS DISTINCT FROM 'failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "feeds_done_at_cmp_chk", + "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + } + ], "devices": [ { "name": "devices_kind_chk", diff --git a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json index c61b39d11c..0646c3546f 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json @@ -73,6 +73,20 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], + "feeds": [ + { + "name": "feeds_status_chk", + "expression": "\"status\" IN ('pending', 'done', 'failed')" + }, + { + "name": "feeds_error_reqwhen_chk", + "expression": "(\"status\" IS DISTINCT FROM 'failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "feeds_done_at_cmp_chk", + "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + } + ], "devices": [ { "name": "devices_kind_chk", diff --git a/fixtures/check-constraint-conformance/expected.sqlite.json b/fixtures/check-constraint-conformance/expected.sqlite.json index c188de6cc4..5201a31eab 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.json @@ -69,6 +69,20 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], + "feeds": [ + { + "name": "feeds_status_chk", + "expression": "\"status\" IN ('pending', 'done', 'failed')" + }, + { + "name": "feeds_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "feeds_done_at_cmp_chk", + "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + } + ], "devices": [ { "name": "devices_kind_chk", diff --git a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json index 9c24b2ea63..97f27264f8 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json @@ -69,6 +69,20 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], + "feeds": [ + { + "name": "feeds_status_chk", + "expression": "\"status\" IN ('pending', 'done', 'failed')" + }, + { + "name": "feeds_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'failed') OR (\"error\" IS NOT NULL)" + }, + { + "name": "feeds_done_at_cmp_chk", + "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + } + ], "devices": [ { "name": "devices_kind_chk", diff --git a/fixtures/check-constraint-conformance/input/meta.stored.json b/fixtures/check-constraint-conformance/input/meta.stored.json new file mode 100644 index 0000000000..b221fc4ca7 --- /dev/null +++ b/fixtures/check-constraint-conformance/input/meta.stored.json @@ -0,0 +1,25 @@ +{ + "metadata.root": { + "package": "acme::checks", + "children": [ + { + "object.entity": { + "name": "Feed", + "children": [ + { "source.rdb": { "@table": "feeds" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@required": true, "@values": ["Pending", "Done", "Failed"], + "@stringValueMap": { "Pending": "pending", "Done": "done", "Failed": "failed" } } }, + { "field.string": { "name": "error" } }, + { "field.timestamp": { "name": "startedAt" } }, + { "field.timestamp": { "name": "doneAt" } }, + { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, + { "validator.requiredWhen": { "name": "failureReason", "@field": "error", "@when": "status", "@equals": "Failed" } }, + { "validator.comparison": { "name": "finished", "@left": "doneAt", "@op": "gte", "@right": "startedAt", + "@condition": { "op": "eq", "left": { "field": "status" }, "right": { "value": "Done" } } } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/enum-string-value-map/expected.json b/fixtures/conformance/enum-string-value-map/expected.json new file mode 100644 index 0000000000..b6545a2f1b --- /dev/null +++ b/fixtures/conformance/enum-string-value-map/expected.json @@ -0,0 +1,59 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "status", + "@default": "Pending", + "@stringValueMap": { + "Delivered": "delivered", + "Failed": "failed", + "Pending": "pending" + }, + "@values": [ + "Pending", + "Delivered", + "Failed" + ] + } + }, + { + "field.enum": { + "name": "authType", + "@maxLength": 16, + "@stringValueMap": { + "KeyFileContent": "Key_File_Content", + "KeyFilePath": "Key_File_Path", + "None": "None" + }, + "@values": [ + "None", + "KeyFilePath", + "KeyFileContent" + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/enum-string-value-map/input/meta.enums.json b/fixtures/conformance/enum-string-value-map/input/meta.enums.json new file mode 100644 index 0000000000..62b3ccaad9 --- /dev/null +++ b/fixtures/conformance/enum-string-value-map/input/meta.enums.json @@ -0,0 +1,32 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Pending", "Delivered", "Failed"], + "@stringValueMap": { "Pending": "pending", "Delivered": "delivered", "Failed": "failed" }, + "@default": "Pending" + } + }, + { + "field.enum": { + "name": "authType", + "@values": ["None", "KeyFilePath", "KeyFileContent"], + "@stringValueMap": { "None": "None", "KeyFilePath": "Key_File_Path", "KeyFileContent": "Key_File_Content" }, + "@maxLength": 16 + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-array/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json new file mode 100644 index 0000000000..adc91b84d3 --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "tags", + "isArray": true, + "@values": ["Hot", "Cold"], + "@stringValueMap": { "Hot": "hot", "Cold": "cold" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json new file mode 100644 index 0000000000..52e727aecc --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Pending", "Waiting"], + "@stringValueMap": { "Pending": "pending", "Waiting": "pending" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json new file mode 100644 index 0000000000..e53647b538 --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json @@ -0,0 +1,23 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Pending", "Delivered"], + "@stringValueMap": { "Pending": "pending", "Lost": "lost" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json new file mode 100644 index 0000000000..a5f2e7920a --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.enums.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[1]['field.enum']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json new file mode 100644 index 0000000000..b44297ff09 --- /dev/null +++ b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Pending", "Delivered"], + "@intValueMap": { "Pending": 0, "Delivered": 1 }, + "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } + } + }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] + } + } + ] + } +} diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 36fb5bc43c..394e925caa 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -35,7 +35,7 @@ children and the cardinality of that subtype. Documentation attributes | `field.decimal` | Precision-exact decimal (use @precision/@scale). Native TS binding is string (lossless); DB column is NUMERIC(p,s); the wire form is a string. Classified DATA_TYPE_STRING so an exact decimal is never silently rounded through a double. | [types/field.md#fielddecimal](types/field.md#fielddecimal) | | `field.double` | Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/number type; DB column is DOUBLE PRECISION. Not for money — use field.currency or field.decimal. | [types/field.md#fielddouble](types/field.md#fielddouble) | | `field.duration` | A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — a concept with a native type + behavior). Binds to TS string (TS has no native duration type); other ports bind to their native type (C# System.TimeSpan, Java and Kotlin java.time.Duration, Python datetime.timedelta). DB column is the Postgres-native interval type; SQLite, D1 and MySQL store a 64-bit integer count of microseconds, which orders and compares as the span does. The wire form is an ISO-8601 duration: every port writes [-]PT[nH][nM][n[.f]S] (hours never folded into days, as many fractional digits as its native type holds, zero is PT0S) and reads that form plus leading week and day counts (nW, exactly 7 days; nD, exactly 24 hours) and a fraction of any length, truncated toward zero. Years and months are refused: a calendar span is not a fixed length. | [types/field.md#fieldduration](types/field.md#fieldduration) | -| `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. | [types/field.md#fieldenum](types/field.md#fieldenum) | +| `field.enum` | String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer). | [types/field.md#fieldenum](types/field.md#fieldenum) | | `field.float` | Single-precision floating point. Binds to the native double/number type (TS has no distinct float); DB column is REAL. Not for money. | [types/field.md#fieldfloat](types/field.md#fieldfloat) | | `field.inet` | An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native type + behavior, so a subtype not a @stringFormat). Binds to TS string (TS has no native IP type, same as field.uuid); other ports bind to their native IP type (Java java.net.InetAddress, C# System.Net.IPAddress, Python ipaddress, Kotlin java.net.InetAddress). DB column is the Postgres-native inet type. Codegen emits an IPv4-or-IPv6 literal validator (a Zod regex union in TS — z.string().ip() was removed in Zod 4 — native IP-type parsing in the other ports); add @lenient to bind a plain string with no validator. v1 ships WITHOUT @kind — the native type subsumes ipv4/ipv6; @kind is reserved for a later ipv4\|ipv6 value-constraint. | [types/field.md#fieldinet](types/field.md#fieldinet) | | `field.int` | 32-bit signed integer. Binds to the native int type; DB column is INTEGER. | [types/field.md#fieldint](types/field.md#fieldint) | diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index 2fa1e8467c..c7f1133abe 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -20,7 +20,7 @@ Core metaobjects metamodel types and subtypes. - `field.base`: `@default`, `@mutability`, `@required`, `@unique` - `field.currency`: `@currency` - `field.decimal`: `@precision`, `@scale` -- `field.enum`: `@intValueMap`, `@maxLength`, `@provided`, `@values` +- `field.enum`: `@intValueMap`, `@maxLength`, `@provided`, `@stringValueMap`, `@values` - `field.inet`: `@lenient` - `field.map`: `@objectRef`, `@valueType` - `field.object`: `@objectRef` diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index eafe7abc08..a28ee68986 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -249,11 +249,11 @@ A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — ### field.enum -String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence. +String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer). **Owning provider:** metaobjects-core-types -**Rules:** Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize). +**Rules:** Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize). **When to use:** A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks. @@ -282,8 +282,9 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@required` | boolean | no | | | metaobjects-core-types | When true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction. | | `@sortable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD sort allowlists. Inherits from @filterable by default; set false to opt out. | | `@sortableDefaultOrder` | string | no | | `asc`, `desc` | metaobjects-ui | Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'. | +| `@stringValueMap` | properties | no | | | metaobjects-core-types | Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE). | | `@unique` | boolean | no | | | metaobjects-core-types | When true, the field gets a column-level UNIQUE constraint. | -| `@values` | string[] | yes | | | metaobjects-core-types | Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string. | +| `@values` | string[] | yes | | | metaobjects-core-types | Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it. | | `@xmlText` | boolean | no | | | metaobjects-prompt | When true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json. | **Allowed children** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index e6162c2b1c..af98f20006 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1169,8 +1169,8 @@ { "type": "field", "subType": "enum", - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", "attrs": [ { @@ -1338,6 +1338,13 @@ ], "description": "Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'." }, + { + "name": "stringValueMap", + "valueType": "properties", + "isArray": false, + "required": false, + "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." + }, { "name": "unique", "valueType": "boolean", @@ -1350,7 +1357,7 @@ "valueType": "string", "isArray": true, "required": true, - "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." + "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "name": "xmlText", diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index af5ce16fcc..c81d0eb3c5 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -145,14 +145,15 @@ "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ - { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, - { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index af5ce16fcc..c81d0eb3c5 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -145,14 +145,15 @@ "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ - { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, - { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index 446f709a18..9944f3b8c0 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -47,6 +47,8 @@ import { AGG_ALL, AGG_COLLECT, resolveEnumMaxLength, + storedEnumValue, + stringValueMapOf, VALIDATOR_ATTR_DB_CHECK, } from "@metaobjectsdev/metadata"; import { columnNameFromField } from "./naming.js"; @@ -244,6 +246,12 @@ export interface EnumIntCustomType { members: string[]; /** Member symbol -> stored integer. */ intByMember: Record; + /** + * rc.21 — set for a STRING-stored enum with `@stringValueMap` (scalar only; the loader refuses + * it on an array): member symbol -> stored string. The codec then maps member <-> stored string + * over a text/varchar column, and `intByMember` is empty. + */ + storedByMember?: Record; /** * Set only for an `isArray` field. `"native"`: the element codec under Drizzle's * Postgres `.array()` (PgArray maps each element through it), so the column is @@ -473,6 +481,28 @@ function buildEnumIntCustomType( }; } +/** rc.21 — the codec descriptor of a `@stringValueMap` enum: member <-> stored string. */ +function buildEnumStoredCustomType( + field: MetaField, + storedByMember: Readonly>, + dataType: string, +): EnumIntCustomType | undefined { + const members = enumValues(field); + if (members === undefined || members.length === 0) return undefined; + const base = field.name.replace(/[^A-Za-z0-9]/g, ""); + const camel = base.charAt(0).toLowerCase() + base.slice(1); + const screaming = screamingSnake(base); + return { + fnConstName: `${camel}StoredEnum`, + toIntConstName: `${screaming}_TO_STORED`, + fromIntConstName: `${screaming}_FROM_STORED`, + members, + intByMember: {}, + storedByMember: Object.fromEntries(members.map((m) => [m, storedByMember[m] ?? m])), + dataType, + }; +} + /** * The Drizzle pg-core column functions that can carry an IDENTITY clause — * i.e. the builders extending `PgIntColumnBaseBuilder`, the only ones declaring @@ -703,7 +733,10 @@ export function mapColumnType( enumIntCustomType = buildEnumIntCustomType(field, im); fnName = enumIntCustomType?.fnConstName ?? "integer"; } else { - fnName = "text"; + const stored = isArray ? undefined : stringValueMapOf(field); + // rc.21: a @stringValueMap enum maps member <-> stored string at the column. + enumIntCustomType = stored === undefined ? undefined : buildEnumStoredCustomType(field, stored, "text"); + fnName = enumIntCustomType?.fnConstName ?? "text"; } } break; @@ -862,7 +895,13 @@ export function mapColumnType( // creates; with none the column is unbounded text, as before. An array enum is // a text[] column, whose elements carry no length (migrate's arrayElementSqlType). const sized = isArray ? undefined : resolveEnumMaxLength(field); - if (sized !== undefined) { + const stored = isArray ? undefined : stringValueMapOf(field); + if (stored !== undefined) { + // rc.21: the column holds each member's @stringValueMap string, so a codec maps + // member <-> stored string at the column, as the int-backed codec does. + enumIntCustomType = buildEnumStoredCustomType(field, stored, sized === undefined ? "text" : `varchar(${sized})`); + fnName = enumIntCustomType?.fnConstName ?? "text"; + } else if (sized !== undefined) { fnName = "varchar"; fnOptions = { length: sized }; } else { @@ -1048,10 +1087,9 @@ export function mapColumnType( .map((v) => String(intValueForMember(intMap, v, `CHECK for column '${dbName}'`))) .join(", "); } else { - // Single-quote escaping is belt-and-suspenders: the loader's - // ENUM_MEMBER_PATTERN already rejects quote-bearing members (members are - // validated to be identifier-safe), so this never fires in practice. - list = values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", "); + // rc.21: a member is stored as its @stringValueMap string, else as itself — exactly + // migrate-ts's buildChecks. A stored string may carry a quote, so it is escaped. + list = values.map((v) => `'${storedEnumValue(field, v).replace(/'/g, "''")}'`).join(", "); } result.checkConstraint = `${dbName} IN (${list})`; result.checkConstraintValues = list; diff --git a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts index cd7b4a1b7a..b02fdd5aea 100644 --- a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts +++ b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts @@ -52,7 +52,7 @@ import { type MetaSegment, type ReportShape, } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf } from "../enum-meta.js"; import type { ColumnNamingStrategy } from "../metaobjects-config.js"; import { hasWritableRdbSource, servedReport } from "../source-detect.js"; import { isTphSubtype, tphDiscriminatorBase, tphDiscriminatorPin } from "../tph.js"; @@ -978,7 +978,7 @@ class CubeModelBuilder { if (field === undefined) throw new Error(`${where}: discriminator field '${pin.fieldName}' is not a field of '${entity.name}'.`); const value = field.subType === FIELD_SUBTYPE_ENUM - ? encodeIntEnumFilterValue(pin.value, FILTER_OP_EQ, intValueMapOf(field), pin.fieldName, where) + ? encodeIntEnumFilterValue(pin.value, FILTER_OP_EQ, enumStorageMapOf(field), pin.fieldName, where) : pin.value; return { kind: "cmp", ref: `${prefix}${sourceColumnNameFor(field, this.mc.extract)}`, op: FILTER_OP_EQ, value }; } diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts index 5971c61a25..54f3ae6a4c 100644 --- a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts +++ b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts @@ -36,7 +36,7 @@ import { type MetaRoot, type MetaSegment, } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf } from "../enum-meta.js"; import { sourceColumnNameFor, type ExtractContext } from "../projection/extract-view-spec.js"; import { ratioOperand, resolveAggregate } from "../projection/report-resolve.js"; import { cond, mysqlTupleCount, resolveReportFilter, type SqlRenderer } from "../projection/report-sql.js"; @@ -122,11 +122,12 @@ export function dimensionColumn( const d = mc.dialect; const col = cubeColumn(sourceColumnNameFor(field, mc.extract), d, renderer); if (field.subType === FIELD_SUBTYPE_ENUM) { - const intMap = intValueMapOf(field); + const intMap = enumStorageMapOf(field); if (intMap !== undefined) { - // An int-backed enum stores the integer; the wire carries the member symbol, as every - // port's read does. - const arms = Object.entries(intMap).map(([symbol, n]) => `WHEN ${String(n)} THEN ${renderer.literal(symbol, d)}`); + // An int-backed enum stores the integer (a @stringValueMap one its stored string, rc.21); + // the wire carries the member symbol, as every port's read does. + const arms = Object.entries(intMap).map(([symbol, n]) => + `WHEN ${typeof n === "number" ? String(n) : renderer.literal(n, d)} THEN ${renderer.literal(symbol, d)}`); return { sql: `CASE ${col} ${arms.join(" ")} END`, type: "string" }; } } diff --git a/server/typescript/packages/codegen-ts/src/enum-meta.ts b/server/typescript/packages/codegen-ts/src/enum-meta.ts index b5fe8ec7cb..95a627eb4d 100644 --- a/server/typescript/packages/codegen-ts/src/enum-meta.ts +++ b/server/typescript/packages/codegen-ts/src/enum-meta.ts @@ -3,7 +3,7 @@ // extraction and the z.enum([...]) expression are derived in exactly one place. import type { MetaField } from "@metaobjectsdev/metadata"; -import { FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP } from "@metaobjectsdev/metadata"; +import { FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, stringValueMapOf } from "@metaobjectsdev/metadata"; /** * Effective enum member values (`@values`) for a field, as strings. @@ -55,3 +55,14 @@ export function intValueForMember( } return n; } + +/** + * rc.21 — member symbol → what the column stores, for an enum whose storage differs from its + * members: the `@intValueMap` integer, or the `@stringValueMap` string. Undefined when every member + * is its own stored string. For the lowerings (a view or report `@filter`, a TPH pin, a Cube + * dimension) that write a member into SQL. + */ +export type EnumStorageMap = Readonly>; +export function enumStorageMapOf(field: MetaField): EnumStorageMap | undefined { + return intValueMapOf(field) ?? stringValueMapOf(field); +} diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index 28cd71f13b..0cac60fda0 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -77,7 +77,7 @@ import { type ReferenceLookup, } from "@metaobjectsdev/metadata"; import { type MetaData, type MetaField, type MetaReferenceIdentity, type MetaRoot, type MetaSource, MetaObject } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf, type EnumStorageMap } from "../enum-meta.js"; import { columnNameFromField, viewNameFromProjection, @@ -259,7 +259,7 @@ function lowerFilterValue( return { kind: "colRef", ref: `${outer.alias}.${sourceColumnNameFor(other, ctx)}` } satisfies ColRef; } return encodeIntEnumFilterValue( - raw, op, field.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(field as MetaField) : undefined, key, where, + raw, op, field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field as MetaField) : undefined, key, where, ); } @@ -284,11 +284,12 @@ function originScope( * Own-only at either hop would silently emit the member symbol into an integer column * (ADR-0039). */ -function intEnumMapsOf(projection: MetaObject): ReadonlyMap> { - const out = new Map>(); +function intEnumMapsOf(projection: MetaObject): ReadonlyMap { + // rc.21: a @stringValueMap enum's stored strings take the same lowering. + const out = new Map(); for (const f of projection.fields()) { if (f.subType !== FIELD_SUBTYPE_ENUM) continue; - const map = intValueMapOf(f); + const map = enumStorageMapOf(f); if (map !== undefined) out.set(f.name, map); } return out; @@ -309,7 +310,7 @@ function intEnumMapsOf(projection: MetaObject): ReadonlyMap | undefined, + intMap: EnumStorageMap | undefined, fieldName: string, /** Names the filter being lowered, for the error text: the row-scope view @filter * (`Projection P: view @filter`) or an aggregate's scoping filter @@ -323,7 +324,7 @@ export function encodeIntEnumFilterValue( assertNoRelativeDate(value, `${host} on "${fieldName}"`); if (intMap === undefined) return value; if (op === FILTER_OP_IS_NULL) return value; - if (op === FILTER_OP_LIKE) { + if (op === FILTER_OP_LIKE && Object.values(intMap).some((n) => typeof n === "number")) { throw new Error( `${host} uses "like" on "${fieldName}", an ` + `int-backed field.enum (@intValueMap) — it stores as an integer column, so a ` + @@ -333,10 +334,10 @@ export function encodeIntEnumFilterValue( const encode = (v: unknown): unknown => { if (typeof v !== "string") return v; const n = intMap[v]; - if (typeof n !== "number") { + if (typeof n !== "number" && typeof n !== "string") { throw new Error( `${host} value "${v}" for "${fieldName}" has no ` + - `entry in @intValueMap.`, + `entry in @intValueMap / @stringValueMap.`, ); } return n; @@ -363,7 +364,7 @@ function resolveViewFilter( filter: unknown, columnsByField: ReadonlyMap, projectionName: string, - intMapsByField: ReadonlyMap>, + intMapsByField: ReadonlyMap, /** The field each key names (rc.19 `now` reads its type to lower a relative date). */ fieldsByKey: ReadonlyMap = new Map(), ): ViewFilterClause | undefined { @@ -1041,7 +1042,7 @@ export function tphScopeOf(entity: MetaObject, ctx: ExtractContext): TphScope | if (pin === undefined) continue; const field = level.fields().find((f) => f.name === pin.fieldName); if (field === undefined) continue; - const map = field.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(field) : undefined; + const map = field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field) : undefined; column = sourceColumnNameFor(field, ctx); values.push(map?.[pin.value] ?? pin.value); } @@ -1943,7 +1944,7 @@ export function extractViewSpec( const reached = (key: string, f: MetaField, entity: MetaObject, alias: string): void => { columnsByField.set(key, filterColumnFor(key, f, entity, alias, root, usedAliases, ctx, projection.name)); fieldsByKey.set(key, f); - const map = f.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(f) : undefined; + const map = f.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(f) : undefined; if (map !== undefined) intMaps.set(key, map); }; // I1: lazily — only the keys the filter names. Reaching every base field would inline (and diff --git a/server/typescript/packages/codegen-ts/src/projection/report-sql.ts b/server/typescript/packages/codegen-ts/src/projection/report-sql.ts index 8a230e867d..a5300409ca 100644 --- a/server/typescript/packages/codegen-ts/src/projection/report-sql.ts +++ b/server/typescript/packages/codegen-ts/src/projection/report-sql.ts @@ -27,7 +27,7 @@ import { type MetaSegment, type RelativeStartOf, } from "@metaobjectsdev/metadata"; -import { intValueMapOf } from "../enum-meta.js"; +import { enumStorageMapOf } from "../enum-meta.js"; import { desugarClause, encodeIntEnumFilterValue, @@ -183,7 +183,7 @@ function lowerFilterValue(raw: unknown, op: string, field: MetaField, key: strin return encodeIntEnumFilterValue( raw, op, - field.subType === FIELD_SUBTYPE_ENUM ? intValueMapOf(field) : undefined, + field.subType === FIELD_SUBTYPE_ENUM ? enumStorageMapOf(field) : undefined, key, where, ); diff --git a/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts b/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts index 6f2d1ecdb6..111793d921 100644 --- a/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts +++ b/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "../column-mapper.js"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,30 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does. + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => ${t.toIntConstName}[value], + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts new file mode 100644 index 0000000000..8121ca4ac9 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts @@ -0,0 +1,71 @@ +// rc.21 — a string-stored field.enum with @stringValueMap: its member<->stored-string codec lives +// in the COLUMN, as the int-backed codec does (drizzle-enum-intvaluemap.test.ts), and its CHECK +// lists the stored strings, as `meta migrate` does. +// +// (The int-backed note follows.) Task 5 — an int-backed field.enum's symbol<->int codec lives in the COLUMN +// definition, as a generated Drizzle customType. Nothing downstream changes: +// db.insert().values() encodes on bind, a selected row decodes on read, and a +// filter comparison encodes because Drizzle binds through the column type. +// +// Chosen over a Zod write-transform + generated read-decode because TS's +// generated queries return raw Drizzle rows and have NO decode seam — that route +// meant inventing one and wrapping every generated read. This is also the direct +// analogue of the other four ports' codec seams (EF Core HasConversion, OMDB +// JdbcFieldCodec, Exposed customEnumeration, Python ObjectManager coercion). + +import { describe, test, expect } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { renderDrizzleSchema } from "../src/templates/drizzle-schema.js"; +import { makeRenderContext } from "../src/render-context.js"; +import { buildPkMap } from "../src/pk-resolver.js"; +import { buildRelationMap } from "../src/relation-resolver.js"; +import type { Dialect } from "../src/metaobjects-config.js"; + +const VALUES = ["Pending", "Delivered"]; +const STORED = { Pending: "pending", Delivered: "delivered" }; + +async function emit(statusDecl: Record, extraRoots: unknown[] = [], dialect: Dialect = "postgres") { + const json = JSON.stringify({ + "metadata.root": { + children: [ + ...extraRoots, + { + "object.entity": { + name: "Order", + children: [ + { "field.long": { name: "id" } }, + { "field.enum": statusDecl }, + { "source.rdb": { name: "src", "@table": "orders" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ], + }, + }, + ], + }, + }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + const ctx = makeRenderContext({ + dialect, loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root), + }); + return renderDrizzleSchema(res.root.findObject("Order")!, ctx).toString(); +} + +describe("Drizzle codegen — @stringValueMap field.enum customType", () => { + for (const dialect of ["postgres", "sqlite"] as const) { + test(`maps member <-> stored string at the column, and the CHECK lists the stored strings (${dialect})`, async () => { + const out = await emit({ name: "status", "@values": VALUES, "@stringValueMap": STORED }, [], dialect); + expect(out).toContain('const STATUS_TO_STORED = { "Pending": "pending", "Delivered": "delivered" }'); + expect(out).toContain('const STATUS_FROM_STORED: Record = { "pending": "Pending", "delivered": "Delivered" }'); + expect(out).toContain('dataType: () => "text"'); + expect(out).toContain('statusStoredEnum("status")'); + expect(out).toContain("IN ('pending', 'delivered')"); + }); + } + + test("a sized column is the varchar(n) meta migrate creates", async () => { + const out = await emit({ name: "status", "@values": VALUES, "@stringValueMap": STORED, "@maxLength": 12 }); + expect(out).toContain('dataType: () => "varchar(12)"'); + }); +}); diff --git a/server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts b/server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts new file mode 100644 index 0000000000..380145f138 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/string-value-map-view-filter.test.ts @@ -0,0 +1,22 @@ +// rc.21 — a projection's @filter on a @stringValueMap enum compares the member's stored string. + +import { expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; + +test("a view @filter on a @stringValueMap enum binds the stored string", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Upload", children: [ + { "source.rdb": { "@table": "uploads" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Pending", "Delivered"], "@stringValueMap": { Pending: "pending", Delivered: "delivered" } } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "PendingUploads", "@filter": { status: "Pending" }, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_pending_uploads" } }, + { "field.long": { name: "id", extends: "Upload.id" } }, + { "identity.primary": { name: "id", extends: "Upload.id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + const sql = buildProjectionViews(root, { dialect: "postgres" })[0]!.sql; + expect(sql).toContain("'pending'"); + expect(sql).not.toContain("'Pending'"); +}); diff --git a/server/typescript/packages/metadata/src/attr-schema-validate.ts b/server/typescript/packages/metadata/src/attr-schema-validate.ts index 9be7c41f44..28e5f3d4b2 100644 --- a/server/typescript/packages/metadata/src/attr-schema-validate.ts +++ b/server/typescript/packages/metadata/src/attr-schema-validate.ts @@ -56,6 +56,7 @@ import { FIELD_ATTR_COERCE_DEFAULT, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, ENUM_MEMBER_PATTERN, } from "./core/field/field-constants.js"; import { isSharedEnumDeclaration } from "./core/field/shared-enum.js"; @@ -498,6 +499,52 @@ function validateNode( } } } + // --- Check 5c (rc.21): field.enum @stringValueMap content rules --- + // + // The string twin of Check 5b, with its policies: own-only (an inherited map is validated + // on its declaring node), a shared enum's backing owned by the shared declaration. Keys must + // exactly match @values; values are unique non-empty strings. An enum that is not + // string-stored refuses it: an @intValueMap enum stores integers, and an array enum stores + // its members as text[] elements, which no port maps through it. + const rawStringValueMap = node.ownAttrs().get(FIELD_ATTR_STRING_VALUE_MAP); + if (rawStringValueMap !== undefined) { + const bad = (message: string, code: "ERR_BAD_ATTR_VALUE" | "ERR_ENUM_EXTENDS_VALUES_CONFLICT" = "ERR_BAD_ATTR_VALUE") => + errors.push(new ParseError(`${nodeLabel(node)} attribute '@${FIELD_ATTR_STRING_VALUE_MAP}' ${message}`, { code, source: node.source })); + if (sharedSuper !== undefined) { + bad(`is declared on a field extending shared abstract enum '${nodeLabel(sharedSuper)}' — a shared enum's ` + + `stored strings are owned by the shared declaration; move it onto '${nodeLabel(sharedSuper)}' to inherit it.`, + "ERR_ENUM_EXTENDS_VALUES_CONFLICT"); + } else if (node.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined) { + bad(`is refused beside '@${FIELD_ATTR_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one.`); + } else if ((node as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() === true) { + bad(`is refused on an array enum: its column holds the members as text[] elements, which no port maps through @${FIELD_ATTR_STRING_VALUE_MAP}.`); + } else if (typeof rawStringValueMap !== "object" || rawStringValueMap === null || Array.isArray(rawStringValueMap)) { + bad(`must be an object of { member: storedString }.`); + } else { + const map = rawStringValueMap as Record; + const effectiveValues = node.attrs().get(FIELD_ATTR_VALUES); + const declaredMembers: string[] = Array.isArray(effectiveValues) ? effectiveValues : []; + const memberSet = new Set(declaredMembers); + const keySet = new Set(Object.keys(map)); + const missing = declaredMembers.filter((m) => !keySet.has(m)); + const extra = Object.keys(map).filter((k) => !memberSet.has(k)); + if (missing.length > 0 || extra.length > 0) { + bad(`keys must exactly match '@${FIELD_ATTR_VALUES}' members` + + (missing.length > 0 ? ` (missing: ${missing.join(", ")})` : "") + + (extra.length > 0 ? ` (unknown: ${extra.join(", ")})` : "") + "."); + } + const seen = new Map(); + for (const [member, value] of Object.entries(map)) { + if (typeof value !== "string" || value.length === 0) { + bad(`member '${member}' must map to a non-empty string.`); + continue; + } + const owner = seen.get(value); + if (owner !== undefined) bad(`members '${owner}' and '${member}' share the stored string '${value}'; every member must have a unique one.`); + else seen.set(value, member); + } + } + } } // --- Check 6 (R6 Plan 2b): @dbColumnType (logical subtype × value) pairing --- diff --git a/server/typescript/packages/metadata/src/core/field/enum-storage.ts b/server/typescript/packages/metadata/src/core/field/enum-storage.ts new file mode 100644 index 0000000000..7a2fce032a --- /dev/null +++ b/server/typescript/packages/metadata/src/core/field/enum-storage.ts @@ -0,0 +1,29 @@ +// rc.21 — the string a string-stored field.enum member is stored as: its @stringValueMap entry, +// else the member itself. ONE definition every consumer that writes a member into the database +// (a CHECK, a column length, a DEFAULT, a @condition literal, a converter) reads, so none can +// spell a member the database does not hold. + +import type { MetaData } from "../../shared/meta-data.js"; +import { FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_VALUES } from "./field-constants.js"; + +/** The effective (ADR-0039: resolving, it may be inherited) `@stringValueMap`, or undefined. */ +export function stringValueMapOf(field: MetaData): Readonly> | undefined { + const raw = field.attr(FIELD_ATTR_STRING_VALUE_MAP); + if (raw === undefined || raw === null || typeof raw !== "object" || Array.isArray(raw)) return undefined; + return raw as Record; +} + +/** The string `member` is stored as: its @stringValueMap entry, else the member. */ +export function storedEnumValue(field: MetaData, member: string): string { + const map = stringValueMapOf(field); + const stored = map?.[member]; + return typeof stored === "string" ? stored : member; +} + +/** Every member of @values (ADR-0039: resolving), as stored, in declaration order. */ +export function storedEnumValues(field: MetaData): string[] { + const values = field.attr(FIELD_ATTR_VALUES); + return (Array.isArray(values) ? values : []) + .filter((v): v is string => typeof v === "string") + .map((v) => storedEnumValue(field, v)); +} diff --git a/server/typescript/packages/metadata/src/core/field/field-constants.ts b/server/typescript/packages/metadata/src/core/field/field-constants.ts index 0c340412a1..e313497dfb 100644 --- a/server/typescript/packages/metadata/src/core/field/field-constants.ts +++ b/server/typescript/packages/metadata/src/core/field/field-constants.ts @@ -202,6 +202,15 @@ export const FIELD_ATTR_VALUES = "values"; */ export const FIELD_ATTR_INT_VALUE_MAP = "intValueMap"; +/** + * field.enum (rc.21) — optional per-member stored strings: `{ member: string }`, the string twin of + * {@link FIELD_ATTR_INT_VALUE_MAP}, for a string-stored enum whose database spelling differs from its + * member symbols. Keys must exactly match @values; values must be unique non-empty strings. Refused + * with @intValueMap and on an array enum. The column, its CHECK, its length, a @default and a + * @condition literal hold the stored strings; the native type and the wire keep the members. + */ +export const FIELD_ATTR_STRING_VALUE_MAP = "stringValueMap"; + /** * Pattern every enum member must satisfy: a legal identifier in all target * languages (TS union member, Java/C#/Python enum member). Ensures symbol == diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index f315b48302..3e57b08ad1 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -264,9 +264,9 @@ export const FIELD_DEFINITION: ProviderDefinition = { "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ { "type": "attr", @@ -275,7 +275,7 @@ export const FIELD_DEFINITION: ProviderDefinition = { "isArray": true, "min": 1, "max": 1, - "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." + "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", @@ -300,6 +300,14 @@ export const FIELD_DEFINITION: ProviderDefinition = { "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." + }, + { + "type": "attr", + "subType": "properties", + "name": "stringValueMap", + "min": 0, + "max": 1, + "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, diff --git a/server/typescript/packages/metadata/src/enum-length.ts b/server/typescript/packages/metadata/src/enum-length.ts index af3d3e5a90..7cfdf1b795 100644 --- a/server/typescript/packages/metadata/src/enum-length.ts +++ b/server/typescript/packages/metadata/src/enum-length.ts @@ -11,6 +11,7 @@ import { FIELD_SUBTYPE_ENUM, } from "./core/field/field-constants.js"; import { TYPE_OBJECT } from "./shared/base-types.js"; +import { storedEnumValues } from "./core/field/enum-storage.js"; /** The `enums` block in `.metaobjects/config.json`. */ export const ENUMS_KEY_MAX_LENGTH = "maxLength"; @@ -48,15 +49,14 @@ export function resolveEnumMaxLength(field: MetaData): number | undefined { if (typeof own === "number") return own; const fallback = enumDefaultsOf(field).maxLength; if (fallback === undefined) return undefined; - const values = field.attr(FIELD_ATTR_VALUES); - const longest = (Array.isArray(values) ? values : []) - .filter((v): v is string => typeof v === "string") + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + const longest = storedEnumValues(field) .reduce((a, v) => (a === undefined || v.length > a.length ? v : a), undefined); if (longest !== undefined && longest.length > fallback) { const owner = field.parent; const label = owner !== undefined && owner.type === TYPE_OBJECT ? `${owner.name}.${field.name}` : field.name; throw new MetaModelError( - `field.enum "${label}" has the member "${longest}" (${longest.length} characters), longer than ` + + `field.enum "${label}" has the stored value "${longest}" (${longest.length} characters), longer than ` + `the project's enums.maxLength ${fallback}. Give the field its own @maxLength of at least ` + `${longest.length}, raise enums.maxLength, or shorten the member.`, { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" }, diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index 3fc1429098..d2934b959c 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -27,6 +27,7 @@ export * from "./shared/base-types.js"; export * from "./shared/structural.js"; export * from "./core/object/object-constants.js"; export * from "./core/field/field-constants.js"; +export * from "./core/field/enum-storage.js"; export * from "./core/field/duration-wire.js"; // FR-037 R1 — THE mutability accessors. Every consumer deciding "may this be // written, and when?" must go through these rather than reading the attr, so the diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index d49ba7eaf2..06d1f0ff2b 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -26,6 +26,7 @@ import { import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; import { findReverseReferenceHops, reverseHopHint } from "../core/relationship/find-reference.js"; +import { storedEnumValues } from "../core/field/enum-storage.js"; import { resolveFlattenedMember } from "../core/field/flattened-member.js"; import { resolveFilterPath } from "../core/relationship/filter-path.js"; import { effectiveProjectionFilter } from "../core/object/effective-projection-filter.js"; @@ -94,6 +95,7 @@ import { FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_ENUM, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_SUBTYPE_OBJECT, @@ -2125,7 +2127,7 @@ export function validateEnumMaxLength(root: MetaData): ParseError[] { } }; const checkEnum = (field: MetaData): void => { - const declares = [FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP] + const declares = [FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, FIELD_ATTR_STRING_VALUE_MAP] .some((a) => field.ownAttr(a) !== undefined); const maxLength = field.attr(FIELD_ATTR_MAX_LENGTH); if (!declares || typeof maxLength !== "number") return; @@ -2138,13 +2140,13 @@ export function validateEnumMaxLength(root: MetaData): ParseError[] { )); return; } - const values = field.attr(FIELD_ATTR_VALUES); - const tooLong = (Array.isArray(values) ? values : []) - .filter((v): v is string => typeof v === "string" && v.length > maxLength) + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + const tooLong = storedEnumValues(field) + .filter((v) => v.length > maxLength) .sort((a, b) => b.length - a.length); if (tooLong.length > 0) { errors.push(new ParseError( - `field.enum "${label}" @maxLength ${maxLength} is shorter than its member "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, + `field.enum "${label}" @maxLength ${maxLength} is shorter than its stored value "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", source: field.source }, )); } diff --git a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts index f15eeeddb0..049e4e30ec 100644 --- a/server/typescript/packages/metadata/test/field-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/field-definition-completeness.test.ts @@ -12,7 +12,7 @@ // decimal → @precision, @scale // object → @objectRef // currency → @currency -// enum → @values, @provided, @intValueMap, @maxLength +// enum → @values, @provided, @intValueMap, @stringValueMap, @maxLength // int/long/double/float/boolean/date/time/timestamp/uuid → none // - the "any attr" wildcard is gone; a misplaced attr is now ERR_UNKNOWN_ATTR. // @@ -104,6 +104,8 @@ const ENUM_CORE_EXTRA: Record = { values: { valueType: "string", required: true }, provided: { valueType: "boolean", required: false }, intValueMap: { valueType: "intMap", required: false }, + // rc.21: the per-member stored strings of a string-stored enum (refused beside @intValueMap). + stringValueMap: { valueType: "properties", required: false }, // The column length of a string-stored enum (refused beside @intValueMap at load). maxLength: { valueType: "int", required: false }, }; diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 84c5224c4f..0f9ccb84cb 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -2,6 +2,7 @@ import { DuplicateSqlNameError, FkTargetNotUniqueError, InvalidCheckNameError, type CheckNameProblem, type FkTargetViolation, } from "./errors.js"; import { negateExpression, renderExpressionSql } from "./check-expression.js"; +import { storedEnumValue, stringValueMapOf } from "@metaobjectsdev/metadata"; import { canBeUniqueConstraint, resolveSchemaConventions, type SchemaConventions } from "./schema-conventions.js"; import type { ColumnNamingStrategy, MetaData, MetaField, MetaObject, MetaReferenceIdentity, MetaRoot, MetaValidator, @@ -954,7 +955,8 @@ function buildChecks( }); expression = `${qcol} IN (${ints.join(", ")})`; } else { - expression = `${qcol} IN (${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ")})`; + // rc.21: a member is stored as its @stringValueMap string, else as itself. + expression = `${qcol} IN (${values.map((v) => `'${storedEnumValue(field, v).replace(/'/g, "''")}'`).join(", ")})`; } const enumCheck = { name: `${tableName}_${col}_chk`, expression }; checks.push(withDeclaredName(enumCheck, field)); @@ -1085,7 +1087,9 @@ function renderEquals( || whenField.subType === FIELD_SUBTYPE_DOUBLE || whenField.subType === FIELD_SUBTYPE_FLOAT || whenField.subType === FIELD_SUBTYPE_DECIMAL || whenField.subType === FIELD_SUBTYPE_CURRENCY; if (numeric && /^-?\d+(\.\d+)?$/.test(s)) return s; - return `'${s.replace(/'/g, "''")}'`; + // rc.21: a member of a @stringValueMap enum is compared as its stored string. + const stored = whenField.subType === FIELD_SUBTYPE_ENUM ? storedEnumValue(whenField, s) : s; + return `'${stored.replace(/'/g, "''")}'`; } /** Whether a validator or field.enum opts out of its CHECK (`@dbCheck: false`; ADR-0039 resolving). @@ -1177,7 +1181,12 @@ function withCondition( if (field?.subType === FIELD_SUBTYPE_DURATION) return durationLiteralSql(field, value, dialect, "@condition"); const intMap = field === undefined ? undefined : intValueMapOf(field); const n = intMap === undefined || typeof value !== "string" ? undefined : intMap[value]; - return typeof n === "number" ? String(n) : undefined; + if (typeof n === "number") return String(n); + // rc.21: a member compared with a @stringValueMap enum is its stored string. + if (field !== undefined && typeof value === "string" && stringValueMapOf(field) !== undefined) { + return `'${storedEnumValue(field, value).replace(/'/g, "''")}'`; + } + return undefined; }; const unless = renderExpressionSql(negateExpression(condition), column, dialect, stored); return { ...check, expression: `(${unless}) OR (${check.expression})` }; @@ -1560,6 +1569,9 @@ function buildColumn( ); } col.default = { kind: "literal", value: String(mapped) }; + } else if (field.subType === FIELD_SUBTYPE_ENUM && stringValueMapOf(field) !== undefined) { + // rc.21: a string-stored enum's @default names a member; the column holds its stored string. + col.default = { kind: "literal", value: storedEnumValue(field, defaultRaw) }; } else { // #235: an EMPTY-string default (`@default: ""`) is a real literal default — // codegen emits `.default("")` and the DB gets `DEFAULT ''`, so dropping it here diff --git a/server/typescript/packages/migrate-ts/test/string-value-map.test.ts b/server/typescript/packages/migrate-ts/test/string-value-map.test.ts new file mode 100644 index 0000000000..b639d695b3 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/string-value-map.test.ts @@ -0,0 +1,34 @@ +// rc.21 — a string-stored field.enum whose database spelling differs from its members +// (@stringValueMap): the column default, length and CHECK hold the stored strings. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../src/expected-schema.js"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Upload", children: [ + { "source.rdb": { "@table": "uploads" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Pending", "Delivered"], "@default": "Pending", + "@stringValueMap": { Pending: "pending", Delivered: "delivered" } } }, + { "field.enum": { name: "authType", "@values": ["KeyFilePath", "KeyFileContent"], "@maxLength": 16, + "@stringValueMap": { KeyFilePath: "Key_File_Path", KeyFileContent: "Key_File_Content" } } }, + { "identity.primary": { name: "id", "@fields": "id", "@generation": "increment" } } ] } } ] } }; + +describe("@stringValueMap in the expected schema", () => { + test("the default, the length and the CHECK hold the stored strings", async () => { + const { root, errors } = await new MetaDataLoader({ strict: true }).load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + const table = buildExpectedSchema(root, { dialect: "postgres" }).tables.find((t) => t.name === "uploads")!; + const status = table.columns.find((c) => c.name === "status")!; + expect(status.default).toEqual({ kind: "literal", value: "pending" }); + expect(table.checks.map((c) => c.expression)).toContain(`"auth_type" IN ('Key_File_Path', 'Key_File_Content')`); + }); + + test("a stored string longer than @maxLength is refused at load", async () => { + const m = JSON.parse(JSON.stringify(MODEL)); + m["metadata.root"].children[0]["object.entity"].children[3]["field.enum"]["@maxLength"] = 14; + const { errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(m))]); + expect(errors.map((e) => String(e.message)).join("\n")).toContain(`shorter than its stored value "Key_File_Content"`); + }); +}); diff --git a/server/typescript/packages/runtime-ts/src/query-builder.ts b/server/typescript/packages/runtime-ts/src/query-builder.ts index 03de26baac..d3aa0ebee6 100644 --- a/server/typescript/packages/runtime-ts/src/query-builder.ts +++ b/server/typescript/packages/runtime-ts/src/query-builder.ts @@ -5,7 +5,8 @@ import { IDENTITY_ATTR_FIELDS, OBJECT_SUBTYPE_REPORT, DEFAULT_COLUMN_NAMING_STRATEGY, - FIELD_SUBTYPE_DURATION, + FIELD_SUBTYPE_DURATION, FIELD_SUBTYPE_ENUM, + storedEnumValue, stringValueMapOf, resolveTableName, resolveColumnName, durationToStoredMicros, formatDuration, formatPostgresInterval, parseDurationLiteral, } from "@metaobjectsdev/metadata"; @@ -184,6 +185,10 @@ function encodeFilterValue(field: MetaData, value: T, dialect?: Dialect): T { if (dialect === "memory") return micros as T; return formatDuration(micros) as T; } + // rc.21: a @stringValueMap enum is compared as the member's stored string. + if (field.subType === FIELD_SUBTYPE_ENUM && typeof value === "string" && stringValueMapOf(field) !== undefined) { + return storedEnumValue(field, value) as T; + } const intMap = intValueMapOf(field); if (intMap === undefined || typeof value !== "string") return value; const stored = intMap[value]; diff --git a/server/typescript/packages/runtime-ts/src/type-coercer.ts b/server/typescript/packages/runtime-ts/src/type-coercer.ts index 5d3a968b85..fc85e2c345 100644 --- a/server/typescript/packages/runtime-ts/src/type-coercer.ts +++ b/server/typescript/packages/runtime-ts/src/type-coercer.ts @@ -38,6 +38,8 @@ import { STORAGE_JSONB, STORAGE_FLATTENED, DB_COLUMN_TYPE_JSONB, + storedEnumValue, + stringValueMapOf, } from "@metaobjectsdev/metadata"; import type { Dialect, Row } from "./persistence-driver.js"; import { decimalFits, decimalToWire, parseDecimalInput } from "./decimal-wire.js"; @@ -47,7 +49,7 @@ import { export function coerceRowOnRead(entity: MetaData, row: Row, dialect: Dialect): Row { const hydrated = parseJsonTextArrays(entity, deserializeJsonbObjectFields(entity, row)); - const decoded = canonicalizeDurations(entity, canonicalizeDecimals(entity, decodeIntBackedEnums(entity, hydrated))); + const decoded = canonicalizeDurations(entity, canonicalizeDecimals(entity, decodeStoredStringEnums(entity, decodeIntBackedEnums(entity, hydrated)))); if (dialect !== "sqlite" && dialect !== "mysql") return decoded; return mapBooleansFromInt(entity, decoded); } @@ -100,6 +102,48 @@ function encodeIntBackedEnum(intMap: Record, value: unknown): un * null would hide the corruption behind a nullable column. Every port throws * here — the generated Drizzle `customType`'s `fromDriver` included. */ +/** + * rc.21 — a string-stored enum with `@stringValueMap` holds each member's stored string; the row + * read back carries the MEMBER. A stored string with no member throws, for the reason an unmapped + * integer does (the database holds a value the model does not describe). Scalar only: the loader + * refuses the attribute on an array enum. + */ +function decodeStoredStringEnums(entity: MetaData, row: Row): Row { + let out: Row | null = null; + // ADR-0039: resolving — the enum may be inherited from a base via extends. + for (const child of entity.children()) { + if (child.type !== TYPE_FIELD || child.subType !== FIELD_SUBTYPE_ENUM) continue; + const map = stringValueMapOf(child); + if (map === undefined || !(child.name in row)) continue; + const raw = row[child.name]; + if (typeof raw !== "string") continue; + const member = Object.keys(map).find((k) => map[k] === raw); + if (member === undefined) { + throw new Error( + `field.enum '${child.name}' read stored value '${raw}' with no member in ` + + `@stringValueMap (declared: ${JSON.stringify(map)}) — the database holds a value the model does not describe.`, + ); + } + out ??= { ...row }; + out[child.name] = member; + } + return out ?? row; +} + +/** rc.21 — the write side of {@link decodeStoredStringEnums}: member → stored string. */ +function encodeStoredStringEnums(entity: MetaData, row: Row): Row { + let out: Row | null = null; + for (const child of entity.children()) { + if (child.type !== TYPE_FIELD || child.subType !== FIELD_SUBTYPE_ENUM) continue; + if (stringValueMapOf(child) === undefined || !(child.name in row)) continue; + const raw = row[child.name]; + if (typeof raw !== "string") continue; + out ??= { ...row }; + out[child.name] = storedEnumValue(child, raw); + } + return out ?? row; +} + function decodeIntBackedEnums(entity: MetaData, row: Row): Row { let out: Row | null = null; // ADR-0039: resolving — an int-backed enum may be inherited from a base via extends. @@ -204,7 +248,7 @@ export function coerceRowOnWrite(entity: MetaData, row: Row, dialect: Dialect): // Dialect-independent: an int-backed enum's column is INTEGER on every dialect // (SQLite has one integer storage class), so the symbol→int encode is not gated // on the dialect the way the boolean mapping below is. - const encoded = encodeIntBackedEnums(entity, jsonbColumned); + const encoded = encodeStoredStringEnums(entity, encodeIntBackedEnums(entity, jsonbColumned)); if (dialect === "mysql") return mapBooleansToInt(entity, isoTimestampsToDates(entity, encoded)); if (dialect !== "sqlite") return encoded; return mapBooleansToInt(entity, encoded); diff --git a/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts new file mode 100644 index 0000000000..f5b7fc7a4d --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts @@ -0,0 +1,36 @@ +// rc.21 — a string-stored field.enum with @stringValueMap: the ObjectManager writes the member's +// stored string, reads the member back, and binds the stored string in a filter. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource, type MetaData } from "@metaobjectsdev/metadata"; +import { coerceRowOnRead, coerceRowOnWrite } from "../src/type-coercer.js"; +import { compileFilter } from "../src/query-builder.js"; + +async function upload(): Promise { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Upload", children: [ + { "source.rdb": { "@table": "uploads" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["Pending", "Delivered"], "@stringValueMap": { Pending: "pending", Delivered: "delivered" } } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + return root.findObject("Upload")!; +} + +describe("@stringValueMap — ObjectManager codec", () => { + test("writes the stored string and reads the member", async () => { + const entity = await upload(); + expect(coerceRowOnWrite(entity, { id: 1, status: "Delivered" }, "postgres")["status"]).toBe("delivered"); + expect(coerceRowOnRead(entity, { id: 1, status: "delivered" }, "postgres")["status"]).toBe("Delivered"); + }); + + test("an unmapped stored string read back throws", async () => { + const entity = await upload(); + expect(() => coerceRowOnRead(entity, { id: 1, status: "lost" }, "postgres")).toThrow(/no member in @stringValueMap/); + }); + + test("a filter binds the stored string", async () => { + const entity = await upload(); + expect(JSON.stringify(compileFilter(entity, { status: "Pending" }))).toContain('"pending"'); + }); +}); diff --git a/site-reference/index.html b/site-reference/index.html index 9b114688f3..699a85a986 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -162,7 +162,7 @@ - + diff --git a/site-reference/providers.html b/site-reference/providers.html index ad88f7763b..40c8e0ec96 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -57,7 +57,7 @@

    metaobjects-core-types

  • field.base: @default, @mutability, @required, @unique
  • field.currency: @currency
  • field.decimal: @precision, @scale
  • -
  • field.enum: @intValueMap, @maxLength, @provided, @values
  • +
  • field.enum: @intValueMap, @maxLength, @provided, @stringValueMap, @values
  • field.inet: @lenient
  • field.map: @objectRef, @valueType
  • field.object: @objectRef
  • diff --git a/site-reference/types/field.html b/site-reference/types/field.html index 7f9289c351..ba4560c4d6 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -1138,9 +1138,9 @@

    field.duration

  • view.* — 0..*
  • field.enum

    -

    String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.

    +

    String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).

    Owning provider: metaobjects-core-types

    -

    Rules: Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).

    +

    Rules: Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).

    When to use: A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.

    Attributes

    field.enumString-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer). types/field.md#fieldenum
    @@ -1345,6 +1345,15 @@

    field.enum

    + + + + + + + + + @@ -1360,7 +1369,7 @@

    field.enum

    - + diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index af5ce16fcc..c81d0eb3c5 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -145,14 +145,15 @@ "subType": "enum", "dataType": "string", "extendsBase": true, - "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string with no name/value divergence.", + "description": "String-backed enumeration constrained to a closed set of member symbols (@values). Each member is its own stored string, unless @stringValueMap gives it another (or @intValueMap an integer).", "whenToUse": "A field is a fixed, closed set of string values. Set @values so the union type, DB CHECK, and validation are generated — don't hand-roll constants + checks.", - "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so symbol == stored string in every target language. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", + "rules": "Required @values is a non-empty, duplicate-free set; each member must match ^[A-Za-z_][A-Za-z0-9_]*$ so it is a legal identifier in every target language, and is its own stored string unless @stringValueMap (string) or @intValueMap (integer) maps it. Optional FR-010/FR-011 overlays add tolerant-extract aliasing (@enumAlias), per-member docs (@enumDoc), an uncoercible-value fallback (@coerceDefault, must be one of @values), and ASCII normalization mode (@normalize).", "children": [ - { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string." }, + { "type": "attr", "subType": "string", "name": "values", "isArray": true, "min": 1, "max": 1, "description": "Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it." }, { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, - { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." } + { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { From a2775c4a54222d679e9c3b741f1b820d8425f6db Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 14:18:15 -0500 Subject: [PATCH 178/267] feat(enum): @stringValueMap in C# (converter, CHECK, length, loader rules) The C# EF context converts a @stringValueMap enum member <-> stored string (a per-member chain ending in a throwing helper, as the int-backed pair does), its CHECK and the @condition and @equals literals hold the stored strings, and the column length fits the longest stored string. The loader applies the TypeScript rules. The length messages keep saying "member" when no map is declared. Co-Authored-By: Claude Opus 5.5 --- .../Generators/CheckConstraints.cs | 15 +++-- .../Generators/DbContextGenerator.cs | 61 +++++++++++++++++-- .../EfModelGapsTests.cs | 31 ++++++++++ .../MetaObjects/Core/Field/FieldConstants.cs | 8 +++ .../MetaObjects/Core/Field/FieldSchema.cs | 7 +++ server/csharp/MetaObjects/CoreTypes.cs | 2 +- .../MetaObjects/Loader/ValidationPasses.cs | 61 ++++++++++++++++++- server/csharp/MetaObjects/Meta/EnumLength.cs | 5 +- server/csharp/MetaObjects/Meta/EnumStorage.cs | 23 +++++++ .../packages/metadata/src/enum-length.ts | 4 +- .../metadata/src/loader/validation-passes.ts | 4 +- 11 files changed, 200 insertions(+), 21 deletions(-) create mode 100644 server/csharp/MetaObjects/Meta/EnumStorage.cs diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index d2c369d26d..35dbf44247 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -66,8 +66,9 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co if (field.SubType == FIELD_SUBTYPE_ENUM && !OptedOut(field) && field.EffectiveEnumValues is { Count: > 0 } values) { var ints = field.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; + // rc.21: a string member is stored as its @stringValueMap string, else as itself. var members = ints is null - ? values.Select(Literal) + ? values.Select(v => Literal(EnumStorage.StoredValue(field, v))) : values.Select(v => ints.TryGetValue(v, out var n) && n is not null ? Number(n) : throw new InvalidOperationException( @@ -278,9 +279,12 @@ private static CheckConstraint WithCondition( { var field = entity.Fields().FirstOrDefault(f => f.Name == name); if (field?.SubType == FIELD_SUBTYPE_DURATION) return DurationLiteral(field, value, dialect, "@condition"); - return field?.Attr(FIELD_ATTR_INT_VALUE_MAP) is IReadOnlyDictionary ints - && value is string s && ints.TryGetValue(s, out var n) && n is not null && IsNumber(n) - ? Number(n) + if (field?.Attr(FIELD_ATTR_INT_VALUE_MAP) is IReadOnlyDictionary ints + && value is string s && ints.TryGetValue(s, out var n) && n is not null && IsNumber(n)) + return Number(n); + // rc.21: a member compared with a @stringValueMap enum is its stored string. + return field is not null && value is string member && EnumStorage.StringValueMapOf(field) is not null + ? Literal(EnumStorage.StoredValue(field, member)) : null; } var unless = Render(Negate(condition), Column, dialect, Stored); @@ -315,7 +319,8 @@ private static string EqualsLiteral(object? raw, MetaField when, string? dialect var numeric = when.SubType is FIELD_SUBTYPE_INT or FIELD_SUBTYPE_LONG or FIELD_SUBTYPE_DOUBLE or FIELD_SUBTYPE_FLOAT or FIELD_SUBTYPE_DECIMAL or FIELD_SUBTYPE_CURRENCY; if (numeric && Regex.IsMatch(s, @"^-?\d+(\.\d+)?$")) return s; - return Literal(s); + // rc.21: a member of a @stringValueMap enum is compared as its stored string. + return Literal(when.SubType == FIELD_SUBTYPE_ENUM ? EnumStorage.StoredValue(when, s) : s); } // ---- field.duration literals (typescript metadata duration-wire.ts) ---- diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index bf7507aec3..9920adea16 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -359,6 +359,8 @@ public virtual IEnumerable Generate(GenContext ctx) if (NeedsUnmappedEnumHelper(objects, ctx.Root) || modelLines.Any(l => l.Contains(UnmappedEnumMemberHelperName + "(", StringComparison.Ordinal))) EmitUnmappedEnumHelper(sb); + if (modelLines.Any(l => l.Contains(UnmappedEnumStoredMemberHelperName + "(", StringComparison.Ordinal))) + EmitUnmappedStoredEnumHelper(sb); // Gated on the EMITTED text, not on a second derivation of it. Every site that uses the // helper appends to modelLines (entity, read-only projection, and the flattened-VO member // block, which lands here as one OwnedTypeConfig string), and modelLines is complete by @@ -1788,6 +1790,36 @@ private string UsingEntityConfig(M2MNavigation nav, GenContext ctx) /// Name of the generated fail-fast helper the write converters end in. private const string UnmappedEnumMemberHelperName = "UnmappedEnumMember"; + /// rc.21 — the read/write helpers a @stringValueMap enum's converters end in. + private const string UnmappedEnumStoredValueHelperName = "UnmappedEnumStoredValue"; + private const string UnmappedEnumStoredMemberHelperName = "UnmappedEnumStoredMember"; + + /// + /// rc.21 — the fail-fast helpers a @stringValueMap enum's converters end in, emitted only + /// when a converter references them (so a model with none is byte-identical). + /// + private static void EmitUnmappedStoredEnumHelper(StringBuilder sb) + { + sb.AppendLine(); + sb.AppendLine(" /// "); + sb.AppendLine(" /// A field.enum column with @stringValueMap held a string that maps to no member: the"); + sb.AppendLine(" /// database holds data the model says is impossible."); + sb.AppendLine(" /// "); + sb.AppendLine($" private static T {UnmappedEnumStoredValueHelperName}(string stored, string field) =>"); + sb.AppendLine(" throw new global::System.InvalidOperationException("); + sb.AppendLine(" $\"field.enum '{field}' read stored value '{stored}' with no member in \" +"); + sb.AppendLine(" \"@stringValueMap — the database holds a value the model does not describe.\");"); + sb.AppendLine(); + sb.AppendLine(" /// "); + sb.AppendLine(" /// A field.enum property with @stringValueMap held a value outside @values: it has no"); + sb.AppendLine(" /// declared stored string, and writing another member's would corrupt the row silently."); + sb.AppendLine(" /// "); + sb.AppendLine($" private static string {UnmappedEnumStoredMemberHelperName}(object? value, string field) =>"); + sb.AppendLine(" throw new global::System.InvalidOperationException("); + sb.AppendLine(" $\"field.enum '{field}' cannot write {value}: it has no stored string in \" +"); + sb.AppendLine(" \"@stringValueMap — the value is not one of the members the model declares.\");"); + } + /// /// Emits the fail-fast helper every int-backed enum's provider→model converter ends /// in. Emitted only when at least one such converter was generated, so a model with @@ -2054,16 +2086,18 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met { var config = ctx.Config; var intMap = IntValueMapOf(f); + var stringMap = f.ResolvedIsArray() ? null : EnumStorage.StringValueMapOf(f); // A string-backed enum's column length (EnumLength.ResolveMaxLength: its @maxLength, else // the project's enums.maxLength) is the VARCHAR(n) `meta migrate` creates. An array enum // is a text[] column, whose elements carry no length. - if (intMap is null) - return !f.ResolvedIsArray() && EnumLength.ResolveMaxLength(f) is { } length - ? $"HasConversion().HasMaxLength({length})" - : "HasConversion()"; + var maxLength = !f.ResolvedIsArray() && intMap is null && EnumLength.ResolveMaxLength(f) is { } length + ? $".HasMaxLength({length})" + : ""; + if (intMap is null && stringMap is null) + return $"HasConversion(){maxLength}"; var members = f.EffectiveEnumValues ?? new List(); - if (members.Count == 0) return "HasConversion()"; + if (members.Count == 0) return $"HasConversion(){maxLength}"; // FR-019: a SHARED (root-level abstract) or @provided enum is NOT nested inside the // entity class — EntityGenerator references it instead (see its EnumPropertyTypeName) @@ -2081,12 +2115,27 @@ private static bool NeedsUnmappedEnumHelper(IEnumerable objects, Met var type = Fr019SharedEnum.SharedEnumForField(f) is { } shared ? Fr019SharedEnum.SharedEnumTypeReference(shared, config) : $"{CSharpNaming.QualifiedOwnerTypeRef(owner, entity, config)}.{CSharpNaming.EnumTypeName(entity, f)}"; + // rc.21: a @stringValueMap enum stores each member's string. The same per-member chains as + // the int-backed pair below, over string literals, each ending in its throwing helper. + if (stringMap is not null) + { + var toStored = new System.Text.StringBuilder("v => "); + var fromStored = new System.Text.StringBuilder("v => "); + foreach (var m in members) + toStored.Append($"v == {type}.{m} ? \"{CSharpNaming.CSharpStringLiteral(EnumStorage.StoredValue(f, m))}\" : "); + toStored.Append($"{UnmappedEnumStoredMemberHelperName}(v, \"{f.Name}\")"); + foreach (var m in members) + fromStored.Append($"v == \"{CSharpNaming.CSharpStringLiteral(EnumStorage.StoredValue(f, m))}\" ? {type}.{m} : "); + fromStored.Append($"{UnmappedEnumStoredValueHelperName}<{type}>(v, \"{f.Name}\")"); + return $"HasConversion({toStored}, {fromStored}){maxLength}"; + } + // Read the ints THROUGH the map, keyed by member, so @values stays the SSOT and a // member with no mapping cannot silently vanish from the conversion. var ints = new List(members.Count); foreach (var m in members) { - if (!intMap.TryGetValue(m, out var raw) || raw is null) + if (!intMap!.TryGetValue(m, out var raw) || raw is null) throw new InvalidOperationException( $"field.enum '{f.Name}' @{FIELD_ATTR_INT_VALUE_MAP} has no integer for member '{m}' — " + "cannot build the EF value conversion."); diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index fa2cb72817..311abb9d7f 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -169,6 +169,37 @@ public void An_entity_derived_field_is_no_column_of_the_entity() Assert.Null(patient.ClrType.GetProperty("HasConsent")); } + // ── rc.21: @stringValueMap — a member's stored string ──────────────────────────────────── + + private const string StoredStringModel = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Upload", "children": [ + { "source.rdb": { "@table": "uploads" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["Pending", "Delivered"], "@default": "Pending", "@maxLength": 12, + "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } } }, + { "identity.primary": { "@fields": "id" } } + ]}} + ]}} + """; + + [Fact] + public void A_string_value_map_enum_converts_member_and_stored_string_both_ways() + { + var gen = GeneratedEfModel.Compile(StoredStringModel, "Acme.Stored"); + using var db = gen.ModelOnlyContext(); + var status = EntityType(db, "Upload").FindProperty("Status")!; + var converter = status.GetValueConverter()!; + var enumType = Nullable.GetUnderlyingType(status.ClrType) ?? status.ClrType; + var delivered = Enum.Parse(enumType, "Delivered"); + Assert.Equal("delivered", converter.ConvertToProvider(delivered)); + Assert.Equal(delivered, converter.ConvertFromProvider("delivered")); + Assert.Throws(() => converter.ConvertFromProvider("lost")); + Assert.Equal(12, status.GetMaxLength()); + // The column default is the member; EF writes it through the converter, as 'pending'. + Assert.Equal("pending", converter.ConvertToProvider(status.GetDefaultValue())); + } + // ── G6 (reference half): an identity.reference over a flattened value-object member ────── private const string FlattenedReferenceModel = """ diff --git a/server/csharp/MetaObjects/Core/Field/FieldConstants.cs b/server/csharp/MetaObjects/Core/Field/FieldConstants.cs index 22c891a0df..9cb274e7bb 100644 --- a/server/csharp/MetaObjects/Core/Field/FieldConstants.cs +++ b/server/csharp/MetaObjects/Core/Field/FieldConstants.cs @@ -241,6 +241,14 @@ public static class FieldConstants /// public const string FIELD_ATTR_INT_VALUE_MAP = "intValueMap"; + /// + /// field.enum (rc.21) — optional per-member stored strings ({ member: string }), the string + /// twin of , for a string-stored enum whose database spelling + /// differs from its member symbols. Keys must exactly match @values; values are unique non-empty + /// strings. Refused with @intValueMap and on an array enum. + /// + public const string FIELD_ATTR_STRING_VALUE_MAP = "stringValueMap"; + /// /// Regex pattern each enum member symbol must satisfy: must start with /// a letter or underscore, followed by letters, digits, or underscores. diff --git a/server/csharp/MetaObjects/Core/Field/FieldSchema.cs b/server/csharp/MetaObjects/Core/Field/FieldSchema.cs index afb721f810..20ac6a1579 100644 --- a/server/csharp/MetaObjects/Core/Field/FieldSchema.cs +++ b/server/csharp/MetaObjects/Core/Field/FieldSchema.cs @@ -214,6 +214,13 @@ public static class FieldSchema Required: false, Description: "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers."); + /// rc.21 — the @stringValueMap attr — only on field.enum. Optional object of strings. + public static readonly AttrSchema StringValueMapAttr = new AttrSchema( + Name: FieldConstants.FIELD_ATTR_STRING_VALUE_MAP, + ValueType: AttrConstants.ATTR_SUBTYPE_PROPERTIES, + Required: false, + Description: "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols. Keys must exactly match @values; values must be unique non-empty strings."); + // FR-033 — the field.enum tolerant-extract overlays (@enumAlias / @enumDoc / // @coerceDefault / @normalize) and object.value's @normalize default are NO LONGER // declared here. They are re-homed to the metaobjects-prompt concern provider diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index d48be5a6ec..719cc683ed 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -368,7 +368,7 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) // tolerant-extract overlays (@enumAlias / @enumDoc / @coerceDefault / // @normalize) are re-homed to the metaobjects-prompt concern provider // (reads prompt.json's field.enum extends). - FIELD_SUBTYPE_ENUM => [.. FieldSchema.CommonFieldAttrs, FieldSchema.EnumValuesAttr, FieldSchema.ProvidedAttr, FieldSchema.IntValueMapAttr], + FIELD_SUBTYPE_ENUM => [.. FieldSchema.CommonFieldAttrs, FieldSchema.EnumValuesAttr, FieldSchema.ProvidedAttr, FieldSchema.IntValueMapAttr, FieldSchema.StringValueMapAttr], _ => FieldSchema.CommonFieldAttrs.ToList(), }; diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 506a9f4f64..2184610529 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -2607,7 +2607,7 @@ void Visit(MetaData node) } void CheckEnum(MetaField field) { - var declares = new[] { FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP } + var declares = new[] { FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, FIELD_ATTR_STRING_VALUE_MAP } .Any(a => field.OwnAttr(a) is not null); if (!declares || field.MaxLength is not { } maxLength) return; var owner = field.Parent; @@ -2620,14 +2620,15 @@ void CheckEnum(MetaField field) Envelope: field.Source)); return; } - var tooLong = (field.EffectiveEnumValues ?? []) + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + var tooLong = EnumStorage.StoredValues(field) .Where(v => v.Length > maxLength) .OrderByDescending(v => v.Length) .FirstOrDefault(); if (tooLong is not null) { errors.Add(new MetaError( - $"field.enum \"{label}\" @maxLength {maxLength} is shorter than its member \"{tooLong}\" ({tooLong.Length} characters). Raise @maxLength to at least {tooLong.Length}, or shorten the member.", + $"field.enum \"{label}\" @maxLength {maxLength} is shorter than its {(EnumStorage.StringValueMapOf(field) is null ? "member" : "stored value")} \"{tooLong}\" ({tooLong.Length} characters). Raise @maxLength to at least {tooLong.Length}, or shorten the member.", ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH, Envelope: field.Source)); } @@ -3264,6 +3265,60 @@ private static void WalkEnumValues(MetaData node, List errors) } } } + + // Rule 6 (rc.21): @stringValueMap content rules — the string twin of Rule 5, with its + // policies (own-only; a shared enum's backing owned by the shared declaration). Keys must + // exactly match @values; values are unique non-empty strings. An enum that is not + // string-stored refuses it: an @intValueMap enum stores integers, and an array enum + // stores its members as text[] elements, which no port maps through it. + if (field.OwnAttr(FIELD_ATTR_STRING_VALUE_MAP) is { } rawStringMap) + { + void Bad(string message, ErrorCode code = ErrorCode.ERR_BAD_ATTR_VALUE) => errors.Add(new MetaError( + $"field.enum '{field.Name}' attribute '@{FIELD_ATTR_STRING_VALUE_MAP}' {message}", code, Envelope: field.Source)); + if (SharedEnumSuper(field) is { } sharedStringSuper) + { + Bad($"is declared on a field extending shared abstract enum '{sharedStringSuper.Name}' — a shared enum's " + + $"stored strings are owned by the shared declaration; move it onto '{sharedStringSuper.Name}' to inherit it.", + ErrorCode.ERR_ENUM_EXTENDS_VALUES_CONFLICT); + } + else if (field.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null) + { + Bad($"is refused beside '@{FIELD_ATTR_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one."); + } + else if (field.ResolvedIsArray()) + { + Bad($"is refused on an array enum: its column holds the members as text[] elements, which no port maps through @{FIELD_ATTR_STRING_VALUE_MAP}."); + } + else if (rawStringMap is not IReadOnlyDictionary stringMap) + { + Bad("must be an object of { member: storedString }."); + } + else + { + var effective = field.EffectiveEnumValues ?? new List(); + var memberSet = new HashSet(effective, StringComparer.Ordinal); + var keySet = new HashSet(stringMap.Keys, StringComparer.Ordinal); + var missing = effective.Where(m => !keySet.Contains(m)).ToList(); + var extra = stringMap.Keys.Where(k => !memberSet.Contains(k)).ToList(); + if (missing.Count > 0 || extra.Count > 0) + Bad($"keys must exactly match '@{FIELD_ATTR_VALUES}' members" + + (missing.Count > 0 ? $" (missing: {string.Join(", ", missing)})" : "") + + (extra.Count > 0 ? $" (unknown: {string.Join(", ", extra)})" : "") + "."); + var seen = new Dictionary(StringComparer.Ordinal); + foreach (var (member, value) in stringMap) + { + if (value is not string { Length: > 0 } stored) + { + Bad($"member '{member}' must map to a non-empty string."); + continue; + } + if (seen.TryGetValue(stored, out var owner)) + Bad($"members '{owner}' and '{member}' share the stored string '{stored}'; every member must have a unique one."); + else + seen[stored] = member; + } + } + } } foreach (var child in node.OwnChildren()) diff --git a/server/csharp/MetaObjects/Meta/EnumLength.cs b/server/csharp/MetaObjects/Meta/EnumLength.cs index 9990ff980c..1e0bd30548 100644 --- a/server/csharp/MetaObjects/Meta/EnumLength.cs +++ b/server/csharp/MetaObjects/Meta/EnumLength.cs @@ -37,14 +37,15 @@ public static class EnumLength if (field.ResolvedIsArray()) return null; if (field.MaxLength is { } own) return own; if (EnumDefaults.Of(field).MaxLength is not { } fallback) return null; - var longest = (field.EffectiveEnumValues ?? []) + // rc.21: the column holds each member's STORED string (@stringValueMap), so that is what must fit. + var longest = EnumStorage.StoredValues(field) .OrderByDescending(v => v.Length).FirstOrDefault(); if (longest is not null && longest.Length > fallback) { var owner = field.Parent; var label = owner is not null && owner.Type == TYPE_OBJECT ? $"{owner.Name}.{field.Name}" : field.Name; throw new MetaModelException( - $"field.enum \"{label}\" has the member \"{longest}\" ({longest.Length} characters), longer than " + + $"field.enum \"{label}\" has the {(EnumStorage.StringValueMapOf(field) is null ? "member" : "stored value")} \"{longest}\" ({longest.Length} characters), longer than " + $"the project's enums.maxLength {fallback}. Give the field its own @maxLength of at least " + $"{longest.Length}, raise enums.maxLength, or shorten the member.", ErrorCode.ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH); diff --git a/server/csharp/MetaObjects/Meta/EnumStorage.cs b/server/csharp/MetaObjects/Meta/EnumStorage.cs new file mode 100644 index 0000000000..d38c9d94b5 --- /dev/null +++ b/server/csharp/MetaObjects/Meta/EnumStorage.cs @@ -0,0 +1,23 @@ +// rc.21 — the string a string-stored field.enum member is stored as: its @stringValueMap entry, +// else the member itself. ONE definition every consumer that writes a member into the database +// (a CHECK, a column length, a converter, a @condition literal) reads. Mirrors TypeScript's +// core/field/enum-storage.ts. + +using static MetaObjects.Core.Field.FieldConstants; + +namespace MetaObjects.Meta; + +public static class EnumStorage +{ + /// The effective (ADR-0039: resolving) @stringValueMap, or null. + public static IReadOnlyDictionary? StringValueMapOf(MetaData field) => + field.Attr(FIELD_ATTR_STRING_VALUE_MAP) as IReadOnlyDictionary; + + /// The string is stored as: its @stringValueMap entry, else the member. + public static string StoredValue(MetaData field, string member) => + StringValueMapOf(field) is { } map && map.TryGetValue(member, out var v) && v is string { Length: > 0 } s ? s : member; + + /// Every member of @values (resolving), as stored, in declaration order. + public static IReadOnlyList StoredValues(MetaField field) => + (field.EffectiveEnumValues ?? []).Select(m => StoredValue(field, m)).ToList(); +} diff --git a/server/typescript/packages/metadata/src/enum-length.ts b/server/typescript/packages/metadata/src/enum-length.ts index 7cfdf1b795..86dc5c6fb7 100644 --- a/server/typescript/packages/metadata/src/enum-length.ts +++ b/server/typescript/packages/metadata/src/enum-length.ts @@ -11,7 +11,7 @@ import { FIELD_SUBTYPE_ENUM, } from "./core/field/field-constants.js"; import { TYPE_OBJECT } from "./shared/base-types.js"; -import { storedEnumValues } from "./core/field/enum-storage.js"; +import { storedEnumValues, stringValueMapOf } from "./core/field/enum-storage.js"; /** The `enums` block in `.metaobjects/config.json`. */ export const ENUMS_KEY_MAX_LENGTH = "maxLength"; @@ -56,7 +56,7 @@ export function resolveEnumMaxLength(field: MetaData): number | undefined { const owner = field.parent; const label = owner !== undefined && owner.type === TYPE_OBJECT ? `${owner.name}.${field.name}` : field.name; throw new MetaModelError( - `field.enum "${label}" has the stored value "${longest}" (${longest.length} characters), longer than ` + + `field.enum "${label}" has the ${stringValueMapOf(field) === undefined ? "member" : "stored value"} "${longest}" (${longest.length} characters), longer than ` + `the project's enums.maxLength ${fallback}. Give the field its own @maxLength of at least ` + `${longest.length}, raise enums.maxLength, or shorten the member.`, { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH" }, diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 06d1f0ff2b..4844b376a3 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -26,7 +26,7 @@ import { import type { MetaData } from "../shared/meta-data.js"; import type { MetaObject } from "../core/object/meta-object.js"; import { findReverseReferenceHops, reverseHopHint } from "../core/relationship/find-reference.js"; -import { storedEnumValues } from "../core/field/enum-storage.js"; +import { storedEnumValues, stringValueMapOf } from "../core/field/enum-storage.js"; import { resolveFlattenedMember } from "../core/field/flattened-member.js"; import { resolveFilterPath } from "../core/relationship/filter-path.js"; import { effectiveProjectionFilter } from "../core/object/effective-projection-filter.js"; @@ -2146,7 +2146,7 @@ export function validateEnumMaxLength(root: MetaData): ParseError[] { .sort((a, b) => b.length - a.length); if (tooLong.length > 0) { errors.push(new ParseError( - `field.enum "${label}" @maxLength ${maxLength} is shorter than its stored value "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, + `field.enum "${label}" @maxLength ${maxLength} is shorter than its ${stringValueMapOf(field) === undefined ? "member" : "stored value"} "${tooLong[0]}" (${tooLong[0]!.length} characters). Raise @maxLength to at least ${tooLong[0]!.length}, or shorten the member.`, { code: "ERR_ENUM_VALUE_EXCEEDS_MAX_LENGTH", source: field.source }, )); } From ded252de29c5ef667713eb3836d5d39317a9a164 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 15:02:32 -0500 Subject: [PATCH 179/267] feat(enum): @stringValueMap in Java, Kotlin and Python Every JVM and Python loader validates it with the TypeScript rules. The OMDB codec binds the stored string and reads the member back (an unmapped stored string throws); the Kotlin Exposed table maps it with a VARCHAR customEnumeration; the generated Spring enum carries dbValue() and fromDbValue(String) for a hand-written repository; the Python ObjectManager encodes and decodes it. The CHANGELOG and the field-types page document the attribute for every port. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 22 +++++- docs/features/field-types.md | 20 ++++++ .../kotlin/KotlinExposedTableGenerator.kt | 29 +++++++- ...otlinExposedTableStringValueMapEnumTest.kt | 60 +++++++++++++++++ .../enum-string-value-map/meta.shop.json | 24 +++++++ .../generator/spring/SpringDtoGenerator.java | 2 +- .../generator/spring/SpringTypeMapper.java | 41 ++++++++++++ .../spring/SpringValueObjectGenerator.java | 2 +- .../com/metaobjects/database/EnumLength.java | 3 +- .../java/com/metaobjects/field/EnumField.java | 20 ++++++ .../metaobjects/loader/ValidationPhase.java | 67 +++++++++++++++++++ .../manager/db/codec/JdbcCodecs.java | 45 +++++++++++-- server/python/src/metaobjects/core_types.py | 11 +++ .../metaobjects/loader/validation_passes.py | 52 ++++++++++++++ .../meta/core/field/field_constants.py | 4 ++ .../src/metaobjects/runtime/object_manager.py | 24 +++++++ .../test_object_manager_string_value_map.py | 39 +++++++++++ 17 files changed, 456 insertions(+), 9 deletions(-) create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt create mode 100644 server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json create mode 100644 server/python/tests/runtime/test_object_manager_string_value_map.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f00261cf75..a4cb8b86e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ here.** ## [Unreleased] **`metamodelVersion` moves to `1.3`.** This release adds vocabulary (`field.duration`, -`@constraintName`, `@dbCheck`, `@condition`, `atLeastOne @max`, `@sequenceStart`, `@sequenceName`, +`@constraintName`, `@dbCheck`, `@stringValueMap`, `@condition`, `atLeastOne @max`, `@sequenceStart`, `@sequenceName`, `@flattenedColumnPrefix`, the `pascal` column rule, and `@dbSetName`, a C#-only attr) and nothing that loaded before stops loading. The registry gains two fields on a type or attr entry, carried into the registry manifest: `implementedIn` (kind 1: cross-port vocabulary only the named ports @@ -23,6 +23,26 @@ vocabulary; upgrade every port together. ### Added +- **`@stringValueMap`: a field.enum member's stored string (rc.21).** A string-stored enum may + declare the string each member is stored as, `{ member: string }`, for a legacy column whose + spelling differs from the member symbols (`pending`, `Key_File_Path`). The generated native + type and the wire keep the members; the column, its CHECK, its length, a `@default` and a + `@condition` or `@equals` literal hold the stored strings. It is the string twin of + `@intValueMap` (attr subtype `properties`): keys must match `@values` exactly, values are + unique non-empty strings, a shared enum declares it on the shared declaration + (`ERR_ENUM_EXTENDS_VALUES_CONFLICT`), and it is refused beside `@intValueMap` and on an array + enum (`ERR_BAD_ATTR_VALUE`; no port maps a text[] element through it). Every port registers + and validates it. It is honoured by the C# EF converter (a per-member chain ending in a + throwing helper, as the int-backed pair) and CHECK; by `meta migrate`, `meta verify --db`, the + Drizzle column (a member/stored-string codec), the TypeScript runtime ObjectManager (write, + read, filter) and the view, report and Cube lowerings; by the Java OMDB codec; by the Kotlin + Exposed table (a VARCHAR `customEnumeration`); by the generated Spring enum (`dbValue()` / + `fromDbValue(String)`, for a hand-written repository); and by the Python ObjectManager. A + stored string that maps to no member throws on read in every port. `metamodelVersion` stays + `1.3`: the addition lands in the same unreleased minor. Fixtures + `fixtures/conformance/enum-string-value-map` and four `error-enum-stringvaluemap-*`; the shared + CHECK corpus gains `input/meta.stored.json`. + - **`@dbCheck: false`: a validator or enum with no database CHECK (rc.20).** A CHECK-generating validator (`numeric`, `length`, `regex`, `comparison`, `requiredWhen`, `presentIff`, `atLeastOne`) or a `field.enum` takes an optional db-provider boolean `@dbCheck`, default `true`. diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 5637334286..776b49ac2f 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -247,6 +247,26 @@ Two rules follow from int-backing being a **persistence-layer codec**: to the database: an unmapped symbol binds unchanged, so the column type and its `CHECK` reject it. +**A stored spelling per member (rc.21):** `@stringValueMap` gives each member of a +string-stored enum the string its column holds, when the database's spelling is not the +member symbol — a legacy column holding `pending`, or `Key_File_Path`: + +```json +{ "field.enum": { "name": "status", "@values": ["Pending", "Delivered"], + "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } } } +``` + +The generated enum type and the wire keep the members (`Pending`); the column, its `CHECK`, +its length (`@maxLength` must fit the longest stored string), a `@default` and a `@condition` +or `@equals` literal hold the stored strings. It is the string twin of `@intValueMap`, with its +rules: keys must match `@values` exactly, values are unique non-empty strings, and a shared +enum declares it on the shared declaration. It is refused beside `@intValueMap` and on an array +enum (`ERR_BAD_ATTR_VALUE`). A stored string that maps to no member throws on read, as an +unmapped integer does. Where each port maps it: the C# EF converter and `CHECK`; `meta migrate`, +the Drizzle column codec, the runtime ObjectManager and the view, report and Cube lowerings +(TypeScript); the OMDB codec (Java); the Exposed `customEnumeration` (Kotlin); the generated +Spring enum's `dbValue()` (for a hand-written repository); the Python ObjectManager. + ### Sharing one enum — abstract `field.enum` + `extends` Reuse a constraint set across entities by declaring one **abstract** `field.enum` diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt index f33f4022ee..d8d135a247 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableGenerator.kt @@ -2645,7 +2645,18 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase stored-string mapping inlined, as below. + val stored = readStringValueMap(field) + ?: return "enumerationByName($colExpr, ${KotlinTypeMapper.enumVarcharLength(field)}, $simple::class)" + val fromDb = stored.entries.joinToString("; ") { (sym, s) -> "${kotlinString(s)} -> $simple.$sym" } + val toDb = stored.entries.joinToString("; ") { (sym, s) -> "$simple.$sym -> ${kotlinString(s)}" } + return "customEnumeration($colExpr, \"VARCHAR(${KotlinTypeMapper.enumVarcharLength(field)})\", " + + "{ v -> when (v as String) { $fromDb; " + + "else -> error(\"unmapped stored value \$v for $simple\") } }, " + + "{ e -> when (e) { $toDb } })" + } // `; ` separates the branches: this is a one-line `when`, and space-separated // branches do not parse (`Foo.DRAFT 5 -> ...`). @@ -2661,6 +2672,22 @@ open class KotlinExposedTableGenerator : MultiFileDirectGeneratorBase when (e) { $toDb } })" } + /** rc.21 — the declared member→stored-string map (`@stringValueMap`, resolving), or null. */ + private fun readStringValueMap(field: EnumField): Map? { + if (!field.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)) return null + val raw = runCatching { field.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).value }.getOrNull() + val m = (raw as? Map<*, *>) ?: return null + // In @values order, so the emitted `when` is deterministic (a Properties map is unordered). + val out = LinkedHashMap() + val members = (runCatching { field.getMetaAttr(EnumField.ATTR_VALUES).value }.getOrNull() as? List<*>) + ?.map { it.toString() } ?: emptyList() + for (member in members) { + val s = m[member] as? String ?: continue + out[member] = s + } + return out.ifEmpty { null } + } + /** The declared symbol→int map (`@intValueMap`), or null when the enum is string-backed. */ private fun readIntValueMap(field: EnumField): Map? { if (!field.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt new file mode 100644 index 0000000000..ba3bd373d9 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt @@ -0,0 +1,60 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.metadata.ktx.loadDirectory +import com.tschuchort.compiletesting.KotlinCompilation +import com.tschuchort.compiletesting.SourceFile +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.isRegularFile +import kotlin.io.path.readText +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * rc.21 — a string-stored `field.enum` with `@stringValueMap` on the Exposed table generator: a + * VARCHAR `customEnumeration` mapping member <-> stored string in both directions, compiled + * against the real Exposed API. + */ +@OptIn(org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi::class) +class KotlinExposedTableStringValueMapEnumTest { + + private val models: Path = run { + var p: Path? = Path.of(System.getProperty("user.dir")).toAbsolutePath() + while (p != null && !Files.exists(p.resolve("src/test/resources/models"))) { + p = p.parent + } + assertTrue(p != null, "could not locate src/test/resources/models from user.dir") + p!!.resolve("src/test/resources/models") + } + + private fun compile(outDir: Path): KotlinCompilation.Result { + val sources = Files.walk(outDir).filter { it.isRegularFile() }.sorted().toList() + .map { path -> SourceFile.kotlin(path.parent.relativize(path).toString().replace('/', '_'), path.readText()) } + return KotlinCompilation().apply { + this.sources = sources + inheritClassPath = true + messageOutputStream = System.out + }.compile() + } + + @Test fun `stringValueMap enum emits customEnumeration over VARCHAR and still compiles`() { + val outDir = Files.createTempDirectory("ktbl-stored-enum-") + try { + val loader = loadDirectory("enum-string-value-map", models.resolve("enum-string-value-map")) + for (gen in listOf(KotlinEntityGenerator(), KotlinExposedTableGenerator())) { + gen.setArgs(mapOf("outputDir" to outDir.toString())) + gen.execute(loader) + } + val src = outDir.resolve("acme/shop/UploadTable.kt").readText() + assertTrue("customEnumeration(\"status\", \"VARCHAR(${KotlinTypeMapper.ENUM_VARCHAR_LEN})\"" in src, + "status must use customEnumeration over VARCHAR; saw:\n$src") + assertTrue("\"pending\" -> UploadStatus.Pending" in src && "UploadStatus.Delivered -> \"delivered\"" in src, + "both lambdas must carry the stored strings; saw:\n$src") + val result = compile(outDir) + assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode, result.messages) + } finally { + outDir.toFile().deleteRecursively() + } + } +} diff --git a/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json b/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json new file mode 100644 index 0000000000..5c5410726e --- /dev/null +++ b/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json @@ -0,0 +1,24 @@ +{ + "metadata.root": { + "package": "acme::shop", + "children": [ + { + "object.entity": { + "name": "Upload", + "children": [ + { "source.rdb": { "name": "src", "@table": "uploads", "@kind": "table" } }, + { "field.long": { "name": "id" } }, + { + "field.enum": { + "name": "status", + "@values": ["Pending", "Delivered"], + "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } + } + }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] + } + } + ] + } +} diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java index 77cec51c70..d0555788f8 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringDtoGenerator.java @@ -1007,7 +1007,7 @@ private static List collectEnumDecls(MetaObject owner, List f String typeName = SpringTypeMapper.enumTypeName(owner, ef); if (!seen.add(typeName)) continue; // dedup shared abstract-enum types List values = SpringTypeMapper.effectiveEnumValues(ef); - decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef))); + decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef), SpringTypeMapper.stringValueMap(ef))); } return decls; } diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java index e9a2efb61a..9c8f9f263f 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringTypeMapper.java @@ -428,6 +428,36 @@ public static java.util.Map intValueMap(EnumField field) { * other port agrees with. */ public static String enumDeclaration(String typeName, List values, java.util.Map intValueMap) { + return enumDeclaration(typeName, values, intValueMap, null); + } + + /** + * rc.21 — as {@link #enumDeclaration(String, List, java.util.Map)}, and with a + * {@code @stringValueMap} the enum carries each member's stored STRING ({@code dbValue()}) + * and the reverse lookup ({@code fromDbValue(String)}), which throws on an unmapped one. + */ + public static String enumDeclaration(String typeName, List values, java.util.Map intValueMap, + java.util.Map stringValueMap) { + if (intValueMap == null && stringValueMap != null) { + StringBuilder sb = new StringBuilder("public enum ").append(typeName).append(" {\n"); + List members = new java.util.ArrayList<>(); + for (String v : values) { + String stored = stringValueMap.getOrDefault(v, v).replace("\\", "\\\\").replace("\"", "\\\""); + members.add(" " + v + "(\"" + stored + "\")"); + } + sb.append(String.join(",\n", members)).append(";\n\n"); + sb.append(" private final String dbValue;\n\n"); + sb.append(" ").append(typeName).append("(String dbValue) { this.dbValue = dbValue; }\n\n"); + sb.append(" /** The stored string this member maps to, from the declared @stringValueMap. */\n"); + sb.append(" public String dbValue() { return dbValue; }\n\n"); + sb.append(" /** The member a stored string maps to; throws on a value the map does not declare. */\n"); + sb.append(" public static ").append(typeName).append(" fromDbValue(String value) {\n"); + sb.append(" for (").append(typeName).append(" e : values()) if (e.dbValue.equals(value)) return e;\n"); + sb.append(" throw new IllegalArgumentException(\"unmapped stored value \" + value + \" for ") + .append(typeName).append("\");\n"); + sb.append(" }\n}"); + return sb.toString(); + } if (intValueMap == null) { return "public enum " + typeName + " { " + String.join(", ", values) + " }"; } @@ -448,6 +478,17 @@ public static String enumDeclaration(String typeName, List values, java. return sb.toString(); } + /** rc.21 — the declared member → stored string ({@code @stringValueMap}, resolving), or null. */ + public static java.util.Map stringValueMap(EnumField field) { + if (!field.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)) return null; + Object raw = field.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).getValue(); + if (!(raw instanceof java.util.Map m)) return null; + java.util.Map out = new java.util.LinkedHashMap<>(); + for (java.util.Map.Entry e : m.entrySet()) + if (e.getKey() != null && e.getValue() instanceof String s) out.put(String.valueOf(e.getKey()), s); + return out.isEmpty() ? null : out; + } + public static List effectiveEnumValues(EnumField field) { if (!field.hasMetaAttr(EnumField.ATTR_VALUES)) return List.of(); Object raw = field.getMetaAttr(EnumField.ATTR_VALUES).getValue(); diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java index ab1f0af308..d38b337cb5 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringValueObjectGenerator.java @@ -264,7 +264,7 @@ private static List collectEnumDecls(MetaObject owner, List f if (values.isEmpty()) continue; String typeName = SpringTypeMapper.enumTypeName(owner, ef); if (!seen.add(typeName)) continue; - decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef))); + decls.add(SpringTypeMapper.enumDeclaration(typeName, values, SpringTypeMapper.intValueMap(ef), SpringTypeMapper.stringValueMap(ef))); } return decls; } diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java index 8867237376..d4bc455988 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/EnumLength.java @@ -45,7 +45,8 @@ public static Long resolveMaxLength(MetaField field) { ? field.getMetaAttr(EnumField.ATTR_VALUES).getValue() : null; if (raw instanceof List values) { for (Object o : values) { - String v = String.valueOf(o); + // rc.21: the column holds each member's STORED string (@stringValueMap). + String v = EnumField.storedValue(field, String.valueOf(o)); if (longest == null || v.length() > longest.length()) longest = v; } } diff --git a/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java b/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java index 6693bbc236..6f1fb44283 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java +++ b/server/java/metadata/src/main/java/com/metaobjects/field/EnumField.java @@ -99,6 +99,20 @@ public class EnumField extends PrimitiveField { */ public static final String ATTR_INT_VALUE_MAP = "intValueMap"; + /** + * rc.21 — optional per-member stored strings ({member: string}) of a string-stored enum, the + * string twin of {@link #ATTR_INT_VALUE_MAP}. Keys must match {@code @values}; values are unique + * non-empty strings; refused with {@code @intValueMap} and on an array enum (ValidationPhase). + */ + public static final String ATTR_STRING_VALUE_MAP = "stringValueMap"; + + /** rc.21 — the string {@code member} is stored as: its {@code @stringValueMap} entry (resolving), else the member. */ + public static String storedValue(MetaField field, String member) { + if (!field.hasMetaAttr(ATTR_STRING_VALUE_MAP)) return member; + Object raw = field.getMetaAttr(ATTR_STRING_VALUE_MAP).getValue(); + return raw instanceof java.util.Map map && map.get(member) instanceof String s && !s.isEmpty() ? s : member; + } + /** * Name of the optional per-member description map (properties). * Each key is an enum member symbol from {@code @values}; the value is a @@ -226,6 +240,12 @@ public static void registerTypes(MetaDataRegistry registry) { .ofType(com.metaobjects.attr.IntMapAttribute.SUBTYPE_INT_MAP) .asSingle(); + // rc.21 — optional @stringValueMap ({member: string}); content rules in + // ValidationPhase.validateEnumStringValueMap. + def.optionalAttributeWithConstraints(ATTR_STRING_VALUE_MAP) + .ofType(com.metaobjects.attr.PropertiesAttribute.SUBTYPE_PROPERTIES) + .asSingle(); + // Optional @maxLength — the column length of a string-stored enum (VARCHAR(n)). // Every member must fit, and it is refused beside @intValueMap; both checked // post-load in ValidationPhase.validateEnumMaxLength. diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 9c5fd64d6c..2ac2ef2b0a 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -823,6 +823,7 @@ private static void validateEnumNode(MetaData node) { // owned by this node is validated here against the node's EFFECTIVE @values // (own or inherited via extends), mirroring the TS/C# port structure exactly. validateEnumIntValueMap(node); + validateEnumStringValueMap(node); // --- Own @values content check --- if (node.hasMetaAttr(EnumField.ATTR_VALUES, false)) { @@ -973,6 +974,72 @@ private static void validateEnumIntValueMap(MetaData node) { } } + /** + * rc.21 — {@code @stringValueMap} content rules: the string twin of + * {@link #validateEnumIntValueMap}, with its policies (own-only; a shared enum's backing owned by + * the shared declaration). Keys must exactly match the effective {@code @values}; values are + * unique non-empty strings. Refused beside {@code @intValueMap} and on an array enum. Mirrors + * TypeScript {@code attr-schema-validate} Check 5c. + */ + private static void validateEnumStringValueMap(MetaData node) { + if (!node.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP, false)) { + return; + } + String prefix = ": field.enum '" + node.getName() + "' attribute '@" + EnumField.ATTR_STRING_VALUE_MAP + "' "; + MetaData sharedSuper = sharedEnumSuper(node); + if (sharedSuper != null) { + throw new MetaDataException(ErrorMessageConstants.ERR_ENUM_EXTENDS_VALUES_CONFLICT + prefix + + "is declared on a field extending shared abstract enum '" + sharedSuper.getName() + + "' - a shared enum's stored strings are owned by the shared declaration; move it onto '" + + sharedSuper.getName() + "' to inherit it.", + ErrorCode.ERR_ENUM_EXTENDS_VALUES_CONFLICT, node.getSource()); + } + if (node.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "is refused beside '@" + EnumField.ATTR_INT_VALUE_MAP + + "': an @intValueMap enum is stored as integers, not strings. Keep one.", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + if (node instanceof MetaField field && field.isArrayType()) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "is refused on an array enum: its column holds the members as text[] elements, which no port maps through @" + + EnumField.ATTR_STRING_VALUE_MAP + ".", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + Object raw = node.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP, false).getValue(); + if (!(raw instanceof Map map)) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "must be an object of { member: storedString }.", ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + List effective = effectiveEnumValues(node); + Set memberSet = new HashSet<>(effective); + Set keySet = new HashSet<>(); + for (Object k : map.keySet()) keySet.add(String.valueOf(k)); + List missing = effective.stream().filter(m -> !keySet.contains(m)).toList(); + List extra = keySet.stream().filter(k -> !memberSet.contains(k)).sorted().toList(); + if (!missing.isEmpty() || !extra.isEmpty()) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "keys must exactly match '@" + EnumField.ATTR_VALUES + "' members" + + (missing.isEmpty() ? "" : " (missing: " + String.join(", ", missing) + ")") + + (extra.isEmpty() ? "" : " (unknown: " + String.join(", ", extra) + ")") + ".", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + Map seen = new HashMap<>(); + for (String member : effective) { + Object value = map.get(member); + if (!(value instanceof String stored) || stored.isEmpty()) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "member '" + member + "' must map to a non-empty string.", ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + String owner = seen.putIfAbsent(stored, member); + if (owner != null) { + throw new MetaDataException(ErrorMessageConstants.ERR_BAD_ATTR_VALUE + prefix + + "members '" + owner + "' and '" + member + "' share the stored string '" + stored + + "'; every member must have a unique one.", ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + } + } + /** * FR-011 own-attr validation for a {@code field.enum} node: *
      diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java index 755f771e55..c48f5718a9 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java @@ -441,8 +441,25 @@ static final class EnumCodec implements JdbcFieldCodec { @Override public void readInto(Object o, MetaField f, ResultSet rs, int j) throws SQLException { Map intMap = intValueMap(f); if (intMap == null) { - f.setString(o, rs.getString(j)); - return; + String raw = rs.getString(j); + Map storedMap = stringValueMap(f); + if (storedMap == null || raw == null) { + f.setString(o, raw); + return; + } + // rc.21: a @stringValueMap enum holds the member's stored string; the caller gets + // the member. An unmapped stored string throws, as an unmapped int does. + for (Map.Entry e : storedMap.entrySet()) { + if (raw.equals(e.getValue())) { + f.setString(o, e.getKey()); + return; + } + } + throw new SQLException( + "field.enum '" + f.getName() + "' read stored value '" + raw + + "' with no member in @" + EnumField.ATTR_STRING_VALUE_MAP + + " (declared: " + storedMap + ") — the database holds a value the model " + + "does not describe."); } refuseArray(f); int stored = rs.getInt(j); @@ -472,8 +489,15 @@ static final class EnumCodec implements JdbcFieldCodec { @Override public void write(PreparedStatement s, MetaField f, int j, Object v) throws SQLException { Map intMap = intValueMap(f); if (intMap == null) { - if (v == null) s.setNull(j, Types.VARCHAR); - else s.setString(j, v.toString()); + if (v == null) { + s.setNull(j, Types.VARCHAR); + return; + } + // rc.21: a @stringValueMap enum binds the member's stored string; an unmapped + // member is bound unchanged, so the column's CHECK rejects it. + Map storedMap = stringValueMap(f); + String member = v.toString(); + s.setString(j, storedMap == null ? member : storedMap.getOrDefault(member, member)); return; } refuseArray(f); @@ -501,6 +525,19 @@ private static void refuseArray(MetaField f) throws SQLException { + "the member symbols or read a member nobody stored."); } + /** rc.21 — the declared member→stored-string map ({@code @stringValueMap}, resolving), or null. */ + private static Map stringValueMap(MetaField f) { + if (!f.hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)) return null; + Object raw = f.getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).getValue(); + if (!(raw instanceof Map)) return null; + Map out = new LinkedHashMap<>(); + for (Map.Entry e : ((Map) raw).entrySet()) { + if (e.getKey() == null || !(e.getValue() instanceof String)) continue; + out.put(String.valueOf(e.getKey()), (String) e.getValue()); + } + return out.isEmpty() ? null : out; + } + /** The declared symbol→int map, or null when the enum is string-backed. */ private static Map intValueMap(MetaField f) { if (!f.hasMetaAttr(EnumField.ATTR_INT_VALUE_MAP)) return null; diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index c5e8644180..336e49d7ed 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -10,6 +10,7 @@ ATTR_SUBTYPE_FILTER, ATTR_SUBTYPE_INT, ATTR_SUBTYPE_INT_MAP, + ATTR_SUBTYPE_PROPERTIES, ATTR_SUBTYPE_STRING, ATTR_SUBTYPES, ) @@ -21,6 +22,7 @@ FIELD_ATTR_CURRENCY, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_PROVIDED, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, @@ -656,6 +658,15 @@ def _register_subtypes( value_type=ATTR_SUBTYPE_INT_MAP, required=False, ), + # rc.21 — @stringValueMap: optional per-member stored strings ({member: str}) of a + # string-stored enum (the string twin of @intValueMap). Content rules in + # _validate_enum_values (Rule 5). Python persists no string enum through it yet: + # the ObjectManager refuses an entity carrying one (see object_manager.py). + AttrSchema( + name=FIELD_ATTR_STRING_VALUE_MAP, + value_type=ATTR_SUBTYPE_PROPERTIES, + required=False, + ), # FR-033 — the field.enum tolerant-extract overlays (@enumAlias / @enumDoc / # @coerceDefault / @normalize) are NO LONGER declared here; they are re-homed # to the prompt domain provider (`prompt_provider`, metaobjects-prompt) via diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index b422522a9f..1e091d26d5 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -29,6 +29,7 @@ FIELD_ATTR_COERCE_DEFAULT, FIELD_ATTR_DEFAULT, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_REQUIRED, @@ -652,6 +653,7 @@ def _validate_enum_values( # continue` gate below so a concrete field.enum that inherits @values via # `extends` but declares its own @intValueMap is still validated. _validate_enum_int_value_map(node, errors) + _validate_enum_string_value_map(node, errors) # ADR-0039 sanctioned own: validates the AUTHORED @values membership on THIS # node (mirrors the TS attr-schema-validate `node.ownAttrs()`); an inherited @@ -801,6 +803,56 @@ def _validate_enum_int_value_map(node: MetaData, errors: list[MetaError]) -> Non seen_values[value] = member +def _validate_enum_string_value_map(node: MetaData, errors: list[MetaError]) -> None: + """rc.21 — ``@stringValueMap`` content rules: the string twin of + :func:`_validate_enum_int_value_map`, with its policies (own-only; a shared enum's + backing owned by the shared declaration). Keys must exactly match the EFFECTIVE + ``@values``; values are unique non-empty strings. Refused beside ``@intValueMap`` and + on an array enum (ERR_BAD_ATTR_VALUE). Mirrors TS ``attr-schema-validate`` Check 5c. + """ + # ADR-0039 sanctioned own: validates the map DECLARED on this node. + raw = node.attr(FIELD_ATTR_STRING_VALUE_MAP) + if raw is None: + return + label = _node_label(node) + prefix = f"{label} attribute '@{FIELD_ATTR_STRING_VALUE_MAP}'" + + def bad(message: str, code: ErrorCode = ErrorCode.ERR_BAD_ATTR_VALUE) -> None: + errors.append(MetaError(f"{prefix} {message}", code, envelope=node.source)) + + if node.super_data is not None and is_shared_enum_declaration(node.super_data): + bad("is declared on a field extending a shared abstract enum — a shared enum's stored " + "strings are owned by the shared declaration; move it onto the shared declaration.", + ErrorCode.ERR_ENUM_EXTENDS_VALUES_CONFLICT) + return + if node.attrs().get(FIELD_ATTR_INT_VALUE_MAP) is not None: + bad(f"is refused beside '@{FIELD_ATTR_INT_VALUE_MAP}': an @intValueMap enum is stored as integers, not strings. Keep one.") + return + if node.resolved_is_array(): + bad(f"is refused on an array enum: its column holds the members as text[] elements, which no port maps through @{FIELD_ATTR_STRING_VALUE_MAP}.") + return + if not isinstance(raw, dict): + bad("must be an object of { member: storedString }.") + return + effective_values = _effective_enum_values(node) + member_set = set(effective_values) + missing = [m for m in effective_values if m not in raw] + extra = [k for k in raw if k not in member_set] + if missing or extra: + parts = ([f"missing: {', '.join(missing)}"] if missing else []) + ([f"unknown: {', '.join(extra)}"] if extra else []) + bad(f"keys must exactly match '@{FIELD_ATTR_VALUES}' members ({'; '.join(parts)}).") + seen: dict[str, str] = {} + for member, value in raw.items(): + if not isinstance(value, str) or value == "": + bad(f"member {member!r} must map to a non-empty string.") + continue + owner = seen.get(value) + if owner is not None: + bad(f"members {owner!r} and {member!r} share the stored string {value!r}; every member must have a unique one.") + else: + seen[value] = member + + def _effective_enum_values(node: MetaData) -> list[str]: """The effective ``@values`` members of an enum node (own or inherited via ``extends:``). Empty list when absent. Mirrors Java ``effectiveEnumValues``.""" diff --git a/server/python/src/metaobjects/meta/core/field/field_constants.py b/server/python/src/metaobjects/meta/core/field/field_constants.py index 6cf388650b..9557a3cc22 100644 --- a/server/python/src/metaobjects/meta/core/field/field_constants.py +++ b/server/python/src/metaobjects/meta/core/field/field_constants.py @@ -189,3 +189,7 @@ # @values; values must be unique integers. The generated native type and wire # format are unchanged in every language. Mirrors TS FIELD_ATTR_INT_VALUE_MAP. FIELD_ATTR_INT_VALUE_MAP = "intValueMap" +# rc.21 — per-member stored strings ({member: str}) of a string-stored enum; the string twin of +# @intValueMap. Keys must match @values; values unique non-empty strings; refused with @intValueMap +# and on an array enum. +FIELD_ATTR_STRING_VALUE_MAP = "stringValueMap" diff --git a/server/python/src/metaobjects/runtime/object_manager.py b/server/python/src/metaobjects/runtime/object_manager.py index 5c384a64d0..eba3361c5a 100644 --- a/server/python/src/metaobjects/runtime/object_manager.py +++ b/server/python/src/metaobjects/runtime/object_manager.py @@ -1221,6 +1221,11 @@ def _coerce_write_value(field: MetaField, value: Any) -> Any: if _field_is_array(field) and isinstance(value, list): return [_encode_enum_member(int_map, v) for v in value] return _encode_enum_member(int_map, value) + # rc.21: a @stringValueMap enum stores the member's string (scalar only; the + # loader refuses it on an array). An unmapped member passes through, as above. + stored_map = _string_value_map(field) + if stored_map is not None and isinstance(value, str): + return stored_map.get(value, value) # Everything else (string / int / long / double / float / boolean / enum) # is already the native type pg8000 binds directly. @@ -1325,6 +1330,13 @@ def _int_value_map(field: MetaField) -> dict[Any, Any] | None: return m if isinstance(m, dict) else None +def _string_value_map(field: MetaField) -> dict[str, str] | None: + """rc.21 — the declared ``@stringValueMap`` (member → stored string), or ``None``. + ADR-0039 resolving, as :func:`_int_value_map`.""" + m = field.get_meta_attr(fc.FIELD_ATTR_STRING_VALUE_MAP) + return m if isinstance(m, dict) else None + + def _decode_read_value(field: MetaField, value: Any) -> Any: """Decode a stored value back to its authoring form on read. @@ -1370,6 +1382,18 @@ def _decode_read_value(field: MetaField, value: Any) -> Any: return value int_map = _int_value_map(field) if int_map is None: + stored_map = _string_value_map(field) + if stored_map is not None and isinstance(value, str): + # rc.21: the stored string back to its member; an unmapped one RAISES, as an + # unmapped int does. + for member, stored in stored_map.items(): + if stored == value: + return member + raise ValueError( + f"field.enum '{field.name}' read stored value {value!r} with no member in " + f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} (declared: {stored_map}) — the database holds " + f"a value the model does not describe." + ) return value if isinstance(value, list): # isArray=true (``integer[]``): decode element-wise; a null element stays null. diff --git a/server/python/tests/runtime/test_object_manager_string_value_map.py b/server/python/tests/runtime/test_object_manager_string_value_map.py new file mode 100644 index 0000000000..1c308cc26b --- /dev/null +++ b/server/python/tests/runtime/test_object_manager_string_value_map.py @@ -0,0 +1,39 @@ +"""rc.21 — a string-stored ``field.enum`` with ``@stringValueMap``: the ObjectManager writes +the member's stored string and reads the member back; an unmapped stored string raises.""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest + +from metaobjects import load_string +from metaobjects.runtime.object_manager import _coerce_write_value, _decode_read_value + +_META = {"metadata.root": {"package": "acme", "children": [ + {"object.entity": {"name": "Upload", "children": [ + {"source.rdb": {"@table": "uploads"}}, + {"field.long": {"name": "id"}}, + {"field.enum": {"name": "status", "@values": ["Pending", "Delivered"], + "@stringValueMap": {"Pending": "pending", "Delivered": "delivered"}}}, + {"identity.primary": {"name": "id", "@fields": "id"}}, + ]}}, +]}} + + +def _status() -> Any: + result = load_string(json.dumps(_META)) + assert not result.errors, result.errors + return next(f for f in result.root.children()[0].fields() if f.name == "status") + + +def test_writes_the_stored_string_and_reads_the_member() -> None: + field = _status() + assert _coerce_write_value(field, "Delivered") == "delivered" + assert _decode_read_value(field, "delivered") == "Delivered" + + +def test_an_unmapped_stored_string_raises() -> None: + with pytest.raises(ValueError, match="no member in @stringValueMap"): + _decode_read_value(_status(), "lost") From 5c92688a6ca316d8a7a1e3ce7df6523ba6daa325 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 15:45:13 -0500 Subject: [PATCH 180/267] chore(templates): resync the owned enum-int-codec copies (@stringValueMap) Co-Authored-By: Claude Opus 5.5 --- .../codegen/templates/enum-int-codec.ts | 28 +++++++++++++++++++ .../codegen/templates/enum-int-codec.ts | 28 +++++++++++++++++++ .../src/templates/enum-int-codec.ts | 28 +++++++++++++++++++ 3 files changed, 84 insertions(+) diff --git a/examples/advanced-modeling/codegen/templates/enum-int-codec.ts b/examples/advanced-modeling/codegen/templates/enum-int-codec.ts index c02b3dc950..b002b88a05 100644 --- a/examples/advanced-modeling/codegen/templates/enum-int-codec.ts +++ b/examples/advanced-modeling/codegen/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,30 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does. + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => ${t.toIntConstName}[value], + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/examples/showcase/codegen/templates/enum-int-codec.ts b/examples/showcase/codegen/templates/enum-int-codec.ts index c02b3dc950..b002b88a05 100644 --- a/examples/showcase/codegen/templates/enum-int-codec.ts +++ b/examples/showcase/codegen/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,30 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does. + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => ${t.toIntConstName}[value], + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} diff --git a/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts b/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts index c02b3dc950..b002b88a05 100644 --- a/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts +++ b/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts @@ -43,6 +43,7 @@ import type { EnumIntCustomType } from "@metaobjectsdev/codegen-ts/engine"; export function renderEnumIntCustomType(t: EnumIntCustomType, importModule: string): Code { const customTypeSym = imp(`customType@${importModule}`); const union = t.members.map((m) => JSON.stringify(m)).join(" | "); + if (t.storedByMember !== undefined) return renderStoredStringCodec(t, t.storedByMember, customTypeSym, union); const toEntries = t.members .map((m) => `${JSON.stringify(m)}: ${t.intByMember[m]}`) .join(", "); @@ -141,3 +142,30 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri }); `; } + +/** + * rc.21 — the codec of a string-stored enum with `@stringValueMap`: the column (text, or the + * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. + * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter + * comparison binds the stored string too. An unmapped stored string throws on read, for the reason + * the int codec's does. + */ +function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { + const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); + const fromEntries = t.members.map((m) => `${JSON.stringify(stored[m])}: ${JSON.stringify(m)}`).join(", "); + return code` +const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, string>; +const ${t.fromIntConstName}: Record = { ${fromEntries} }; +const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ + dataType: () => ${JSON.stringify(t.dataType)}, + toDriver: (value) => ${t.toIntConstName}[value], + fromDriver: (value) => { + const member = ${t.fromIntConstName}[value]; + if (member === undefined) { + throw new Error(\`unmapped ${t.fnConstName} value: \${value}\`); + } + return member; + }, +}); +`; +} From b2be4d2e26745a40dcb9df7021cf3de52cdad0d4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Fri, 13 Nov 2026 15:46:09 -0500 Subject: [PATCH 181/267] fix: generated create routes drop server-owned input across ports (1.2.x security) (#568) * fix: generated create routes store only client-settable fields (1.2.x security) Python 1.2.1 stopped its generated routes from handing raw request input to the repository. The same audit found related create-path holes in 1.2.0 in the other four ports; this closes each in its own idiom. Server-owned values are dropped silently, never answered with 400. - Java (codegen-spring): create strips a generated id, readOnly and derived fields; a TPH per-subtype create also strips the body discriminator and sibling-subtype fields. - Kotlin (codegen-kotlin): create skips readOnly/derived columns; a TPH per-subtype create writes only the route subtype's own columns. - C# (MetaObjects.Codegen): every readOnly property shape gets a private setter; create resets a generated id, the TPH discriminator and M:N navigations before Add. - TypeScript (codegen-ts): the update schema omits primary-key fields, so PUT/PATCH can no longer re-key a row with an assigned key. Proof: new shared api-contract scenarios (core + TPH input-server-owned, TPH foreign discriminator) and a readOnly `role` field in secret-fields, run in every port's generated lane and the reference lanes; a new `unset` assertion key in all five harnesses. In-memory test repositories now store what they are handed, so the scenarios fail on the 1.2.0 generators. Proposed versions (not published): npm 1.2.2, NuGet 1.2.2, Maven 8.2.2; PyPI unchanged at 1.2.1. metamodelVersion unchanged. * fix: keep a @required readOnly field creatable in C# and Java generated create Pre-gate review follow-ups to the 1.2.x create-input patch: - C#: the required-key check skips readOnly fields (the private setter never binds them), and create validation ignores a violation naming only a @required readOnly member, as Java's SERVER_OWNED_ON_CREATE does. - Java: the create-validation server-owned set covers every DTO component, so a nulled readOnly or derived value-object column no longer 400s. - TypeScript: drop the now-dead PK guard in the update-schema nullable arm and list the PK rule in updateSchemaFields' doc comment. * no-mistakes(review): apply reviewer inline fixes * no-mistakes(review): Kotlin readOnly create fix + C# reset skip * no-mistakes(document): docs: finish stale corpus counts from input fix --- CHANGELOG.md | 46 ++++ bun.lock | 28 +-- client/web/packages/react/package.json | 2 +- client/web/packages/runtime-web/package.json | 2 +- client/web/packages/tanstack/package.json | 2 +- docs/CONFORMANCE.md | 14 +- docs/features/generated-mutations.md | 15 ++ docs/llms/llms-full.txt | 20 +- docs/llms/llms.txt | 16 +- .../codegen/templates/zod-validators.ts | 16 +- .../.metaobjects/.gen-state/.hashes.json | 2 +- .../codegen/templates/zod-validators.ts | 16 +- .../generated/csharp/SubscriberRoutes.g.cs | 2 + examples/showcase/jvm/pom.xml | 2 +- examples/showcase/site-payload.json | 6 +- fixtures/api-contract-conformance/README.md | 8 +- .../scenarios/input-server-owned-dropped.yaml | 85 +++++++ .../secret-fields/README.md | 5 +- .../secret-fields/meta.json | 1 + .../scenarios/read-omits-credential.yaml | 3 + .../scenarios/write-ignores-excluded.yaml | 15 +- .../secret-fields/seed.json | 4 +- .../api-contract-conformance/tph/README.md | 4 +- ...h-input-foreign-discriminator-dropped.yaml | 44 ++++ .../tph-input-server-owned-dropped.yaml | 72 ++++++ server/csharp/Directory.Build.props | 2 +- .../ServerOwnedCreateInputTests.cs | 236 ++++++++++++++++++ .../Generators/EntityGenerator.cs | 42 ++-- .../Generators/RoutesGenerator.cs | 96 ++++++- .../Api/ApiContractAssertions.cs | 13 + .../ApiContractSecretFieldsConformanceTest.cs | 5 +- .../Api/SecretFieldsFixture.cs | 3 +- .../Api/TphReferenceServer.cs | 7 + server/java/codegen-base/pom.xml | 2 +- .../codegen-kotlin-exposed1x-check/pom.xml | 2 +- server/java/codegen-kotlin/pom.xml | 2 +- .../generator/kotlin/KotlinGenUtil.kt | 17 +- .../kotlin/KotlinSpringControllerGenerator.kt | 12 +- .../kotlin/KotlinServerOwnedCreateBindTest.kt | 84 +++++++ .../kotlin/KotlinServerOwnedInputTest.kt | 89 +++++++ .../acme/auth/AuthController.kt | 6 - server/java/codegen-mustache/pom.xml | 2 +- server/java/codegen-plantuml/pom.xml | 2 +- server/java/codegen-spring/pom.xml | 2 +- .../spring/SpringControllerGenerator.java | 66 ++++- .../spring/SpringSecretFieldsCodegenTest.java | 7 +- .../SpringServerOwnedInputCodegenTest.java | 133 ++++++++++ server/java/core-spring/pom.xml | 2 +- server/java/integration-tests-kotlin/pom.xml | 2 +- .../kotlin/api/ApiContractAssertions.kt | 11 +- .../GeneratedAuthorControllerHarness.kt | 3 + .../GeneratedSecretFieldsControllerHarness.kt | 9 +- .../GeneratedTphControllerHarness.kt | 3 + server/java/integration-tests/pom.xml | 2 +- .../api/ApiContractAssertions.java | 13 +- .../GeneratedAccountControllerHarness.java | 5 +- .../GeneratedAuthorControllerHarness.java | 5 +- .../InMemoryAccountRepositorySource.java | 11 +- .../InMemoryAuthorRepositorySource.java | 6 +- .../GeneratedTphControllerHarness.java | 5 +- .../InMemoryAuthRepositorySource.java | 11 +- server/java/maven-plugin/pom.xml | 2 +- server/java/metadata-ktx/pom.xml | 2 +- server/java/metadata/pom.xml | 2 +- server/java/om/pom.xml | 2 +- server/java/omdb-ktx/pom.xml | 2 +- server/java/omdb/pom.xml | 2 +- server/java/pom.xml | 2 +- server/java/render/pom.xml | 2 +- server/java/spring-boot-starter/pom.xml | 2 +- .../src/metaobjects/codegen/KNOWN_GAPS.md | 12 + .../integration/api_contract_assertions.py | 15 +- .../generated_secret_fields_app.py | 2 +- .../test_api_contract_tph_generated.py | 12 + .../packages/ai-runtime/package.json | 2 +- server/typescript/packages/cli/package.json | 2 +- .../packages/codegen-ts-react/package.json | 2 +- .../packages/codegen-ts-tanstack/package.json | 2 +- .../packages/codegen-ts/package.json | 2 +- .../src/templates/zod-validators.ts | 16 +- .../__snapshots__/reporting-docs.test.ts.snap | 66 ++--- .../test/templates/zod-validators.test.ts | 16 ++ .../packages/docs-site/package.json | 2 +- .../src/api-contract-scenario.ts | 12 + ...contract-secret-fields-generated-server.ts | 7 +- .../src/api-contract-server.ts | 19 +- .../typescript/packages/metadata/package.json | 2 +- .../packages/migrate-ts/package.json | 2 +- .../typescript/packages/render/package.json | 2 +- .../packages/runtime-ts/package.json | 2 +- server/typescript/packages/sdk/package.json | 2 +- .../src/templates/zod-validators.ts | 16 +- 92 files changed, 1359 insertions(+), 222 deletions(-) create mode 100644 fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml create mode 100644 fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml create mode 100644 fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml create mode 100644 server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedCreateBindTest.kt create mode 100644 server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt create mode 100644 server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fe7ecc774..b81c89d1cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,52 @@ here.** ## [Unreleased] +_Proposed as npm `1.2.2` (all 14 `@metaobjectsdev/*` packages), NuGet `1.2.2` and Maven Central +`8.2.2`; `1.2.1` was spent by the Python-only release. PyPI stays at `1.2.1`: no Python product +file changes. No vocabulary or `metamodelVersion` change._ + +### Security + +- **Generated create routes in Java, Kotlin and C#, and TypeScript updates, let a client write + fields it must never set.** The same class of hole the Python 1.2.1 patch closed, found by an + audit of the other four ports after it. Every adopter serving these generated routes should + upgrade and regenerate; an ejected (owned) generator needs the same change made by hand. + + - **Java (`codegen-spring`).** The create route passed the bound DTO to the repository as + sent, so a client `id` on a generated key and a `@mutability: readOnly` or derived field + reached it. On a TPH per-subtype route the body's discriminator and a sibling subtype's + columns did too. The route now rebuilds the DTO with each of those components set to null + before the repository call; the route's subtype still comes from the URL. A `@required` + `readOnly` or derived value-object column no longer fails create validation once nulled. + - **Kotlin (`codegen-kotlin`).** The create route wrote `readOnly` and derived columns from the + body, and a TPH per-subtype route wrote a sibling subtype's columns. It now writes only the + route subtype's own settable columns. + - **C# (`MetaObjects.Codegen`).** The create route bound the EF Core entity from the body, so a + client `id` on a generated key was inserted, a TPH create stored the body's discriminator (a + POST to the Bridge route could create a Copay row), and a TPH subtype's `readOnly` field and + an M:N navigation graph were written. The route now resets the generated key and the + discriminator to their defaults and empties the M:N navigations before `Add`, and a + `readOnly` property of every shape, a TPH subtype's included, has a private setter, which + System.Text.Json does not bind. A `@required` `readOnly` field is therefore neither demanded + of the create body nor held to its `[Required]` there, so such an entity stays creatable. + - **TypeScript (`codegen-ts`).** The `UpdateSchema` kept an assigned (non-generated) + primary key, so a PUT or PATCH could re-key the row. The update schema now leaves out every + primary-key field; the insert schema still takes an assigned key, which is the caller's on + create. + + Each of these values is dropped silently, never answered with a 400. A key the model does not + declare is dropped silently in TypeScript, C# and Python. In Java and Kotlin the answer to an + undeclared key is the host's Jackson `ObjectMapper`'s: Spring Boot's default ignores it, and a + plain `ObjectMapper` (`FAIL_ON_UNKNOWN_PROPERTIES` on) answers 400. This patch leaves that as + it was. + + Gated by the shared api-contract scenarios `input-server-owned-dropped`, + `tph-input-server-owned-dropped` and `tph-input-foreign-discriminator-dropped`, and a `readOnly` + `role` on the `secret-fields` corpus, in every port's generated lane and in the reference lanes. + Python's generated TPH routes answer a foreign body discriminator with a 400 rather than + dropping it (nothing is stored); its runner skips that one scenario, recorded in the Python + codegen `KNOWN_GAPS.md`. + ## [1.2.1] — Python only _PyPI `1.2.1` only. npm, NuGet and Maven Central stay at `1.2.0` (`8.2.0`): none of them has a diff --git a/bun.lock b/bun.lock index 195e182cb8..9def0b0bbb 100644 --- a/bun.lock +++ b/bun.lock @@ -43,7 +43,7 @@ }, "client/web/packages/react": { "name": "@metaobjectsdev/react", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/runtime-web": "workspace:*", "react-easy-crop": "^6.2.3", @@ -73,7 +73,7 @@ }, "client/web/packages/runtime-web": { "name": "@metaobjectsdev/runtime-web", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "qs": "^6.13.0", @@ -86,7 +86,7 @@ }, "client/web/packages/tanstack": { "name": "@metaobjectsdev/tanstack", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/runtime-web": "workspace:*", }, @@ -113,7 +113,7 @@ }, "server/typescript/packages/ai-runtime": { "name": "@metaobjectsdev/ai-runtime", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", @@ -134,7 +134,7 @@ }, "server/typescript/packages/cli": { "name": "@metaobjectsdev/cli", - "version": "1.2.0", + "version": "1.2.2", "bin": { "meta": "./dist/bin/meta.js", }, @@ -179,7 +179,7 @@ }, "server/typescript/packages/codegen-ts": { "name": "@metaobjectsdev/codegen-ts", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@biomejs/js-api": "^0.7.0", "@biomejs/wasm-nodejs": "^1.9.4", @@ -224,7 +224,7 @@ }, "server/typescript/packages/codegen-ts-react": { "name": "@metaobjectsdev/codegen-ts-react", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", @@ -242,7 +242,7 @@ }, "server/typescript/packages/codegen-ts-tanstack": { "name": "@metaobjectsdev/codegen-ts-tanstack", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/codegen-ts": "workspace:*", "@metaobjectsdev/metadata": "workspace:*", @@ -274,7 +274,7 @@ }, "server/typescript/packages/docs-site": { "name": "@metaobjectsdev/docs-site", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", @@ -326,7 +326,7 @@ }, "server/typescript/packages/metadata": { "name": "@metaobjectsdev/metadata", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "yaml": "^2.9.0", }, @@ -339,7 +339,7 @@ }, "server/typescript/packages/migrate-ts": { "name": "@metaobjectsdev/migrate-ts", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@iarna/toml": "^2.2.5", "@metaobjectsdev/metadata": "workspace:*", @@ -366,7 +366,7 @@ }, "server/typescript/packages/render": { "name": "@metaobjectsdev/render", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "mustache": "^4.2.0", "nunjucks": "^3.2.4", @@ -380,7 +380,7 @@ }, "server/typescript/packages/runtime-ts": { "name": "@metaobjectsdev/runtime-ts", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "@metaobjectsdev/render": "workspace:*", @@ -419,7 +419,7 @@ }, "server/typescript/packages/sdk": { "name": "@metaobjectsdev/sdk", - "version": "1.2.0", + "version": "1.2.2", "dependencies": { "@metaobjectsdev/metadata": "workspace:*", "yaml": "^2.9.0", diff --git a/client/web/packages/react/package.json b/client/web/packages/react/package.json index 389f907df0..5ccfeff21f 100644 --- a/client/web/packages/react/package.json +++ b/client/web/packages/react/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/react", - "version": "1.2.0", + "version": "1.2.2", "description": "React runtime for metaobjects: useEntityForm hook and CurrencyInput component.", "type": "module", "main": "./dist/index.js", diff --git a/client/web/packages/runtime-web/package.json b/client/web/packages/runtime-web/package.json index 0ba383763c..ae0c6e4348 100644 --- a/client/web/packages/runtime-web/package.json +++ b/client/web/packages/runtime-web/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/runtime-web", - "version": "1.2.0", + "version": "1.2.2", "description": "Pure framework-agnostic browser core for metaobjects: currency, filter URL serialization, fetcher contract types.", "type": "module", "main": "./dist/index.js", diff --git a/client/web/packages/tanstack/package.json b/client/web/packages/tanstack/package.json index a1fb67dd6e..b524804714 100644 --- a/client/web/packages/tanstack/package.json +++ b/client/web/packages/tanstack/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/tanstack", - "version": "1.2.0", + "version": "1.2.2", "description": "TanStack runtime for metaobjects: EntityFetcherProvider, EntityGrid, default cell renderers.", "type": "module", "main": "./dist/index.js", diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 36834aadbc..b464a464a5 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 59 (53 query + 6 migration) | all 59; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` also on MySQL (a scenario's `engines:` key is exact) | 53 query (migrations TS-only, ADR-0015); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (via Exposed); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query; the `report-*` and `engines:` scenarios also on SQLite and MySQL | 53 query (pg8000); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 119 (31 core + 10 tph + 9 m2m + 5 jsonb + 2 write-through + 2 secret-fields + 12 projection + 37 report + 11 decimal) | ✓ (Fastify reference + generated lane); `report/` and `decimal/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/` and `decimal/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/` and `decimal/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/` and `decimal/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/` and `decimal/` also on SQLite and MySQL | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 122 (32 core + 12 tph + 9 m2m + 5 jsonb + 2 write-through + 2 secret-fields + 12 projection + 37 report + 11 decimal) | ✓ (Fastify reference + generated lane); `report/` and `decimal/` also on SQLite, MySQL and D1 | ✓ (embedded HTTP + JDBC); `report/` and `decimal/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/` and `decimal/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/` and `decimal/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/` and `decimal/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | | [`fixtures/registry-conformance/`](../fixtures/registry-conformance/) | 1 canonical manifest | ✓ (reference emitter) | ✓ | ✓ | ✓ | ✓ | @@ -366,9 +366,9 @@ REAL, a MySQL `DECIMAL` keeps its scale, a MySQL `DATETIME` is the UTC wall cloc `report-relative-date` carries a per-engine seed (`seed-data-engine`). `op: relate` and the write ops stay Postgres-only. See [features/reporting.md](features/reporting.md#what-the-corpus-gates). -### `fixtures/api-contract-conformance/` (119) +### `fixtures/api-contract-conformance/` (122) -All 119 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port +All 122 scenarios → [features/api-contract.md](features/api-contract.md) (cross-port REST API URL grammar + JSON wire format). Verifies every backend's emitted CRUD routes answer identically over HTTP — list / get / create / patch+put / delete, plus pagination (`limit`/`offset`), sort (`sort=field:dir`), the `withCount=1` @@ -378,12 +378,12 @@ status codes. The corpus also covers the 9 cross-port filter operators (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `like`, `isNull`) plus the implicit-AND combinator and 2 error shapes (`invalid_filter_field` / `invalid_filter_op`) under the -URL grammar `?filter[][]=` (FR-009). On top of the 31 core -scenarios the corpus carries eight sub-corpora — `tph/` (10, single-table +URL grammar `?filter[][]=` (FR-009). On top of the 32 core +scenarios the corpus carries eight sub-corpora — `tph/` (12, single-table inheritance; a subtype decimal filters and refuses extra digits), `m2m/` (9 — 3 plain, 5 gating TPH x M:N together, the combination each corpus alone could not reach, and 1 pinning the collection-URL spelling), `jsonb/` (5, typed value-object columns; numbers inside them: a double stays a JSON number, a decimal is the canonical string), -`write-through/` (2, table-write + view-read entities), `secret-fields/` (2, #484: a `@formExclude` or credential `view.password` field is ignored on create, PATCH and PUT, and a credential is never returned), `projection/` (12, a +`write-through/` (2, table-write + view-read entities), `secret-fields/` (2, #484 + the 1.2.x input gate: a `@formExclude` or credential `view.password` field is ignored on create, PATCH and PUT, a credential is never returned, and a `@mutability: readOnly` field is ignored on write too), `projection/` (12, a read-only view answers reads and refuses writes with 405; a projection with no declared identity has no item route; a projection keyed on a field not named `id` is addressed by it, whether its identity names `@fields` or derives them; decimal and float fields filter), `decimal/` (11, ADR-0019 Amendment 1: a decimal, array element and undeclared-precision column included, is one @@ -611,7 +611,7 @@ files into a real Cube. ## Orphaned fixtures (tested but not yet documented) The fixtures in the nine corpora mapped above (metamodel 421 + yaml 16 + verify 45 -+ render 18 + persistence 59 + api-contract 119 + source-resolution 25 + scope 10 + ++ render 18 + persistence 59 + api-contract 122 + source-resolution 25 + scope 10 + dependency 37) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance` and the `cube-model` corpus, whose case lists live in their own READMEs. None are orphaned today. The remaining corpora in the totals table gate tooling contracts (registry manifests, provider diff --git a/docs/features/generated-mutations.md b/docs/features/generated-mutations.md index 3a367bbb6f..ef3f4a2684 100644 --- a/docs/features/generated-mutations.md +++ b/docs/features/generated-mutations.md @@ -66,6 +66,21 @@ but the semantics are one contract — call them **PATCH-1..7** (FR-035): - **PATCH-7 (verbs).** At the HTTP tier both `PATCH` and `PUT` route to the update handler with partial-merge semantics. True PUT-as-full-replace is out of scope. +**Create stores only what a client may set, in every port.** A generated create route +never writes a client-sent value for a server-generated primary key (`@generation` +`increment` or `uuid`), a `@mutability: "readOnly"` or `origin.*`-derived field, the TPH +discriminator (a per-subtype route takes the subtype from the URL), a column only a +sibling subtype declares, or (C#) an M:N navigation graph. Each is dropped silently, not +answered with a 400. An assigned key (no `@generation`) is the caller's on create in +TypeScript, C#, Java and Python, and on update it is the primary key like any other, so it +is left out of the TypeScript `UpdateSchema` too. (Kotlin's generated create is the +exception: it never binds a declared key, assigned or not — `increment` is left to the +column and a `uuid` key is minted app-side.) A key the entity does not declare is dropped in TypeScript, +C# and Python; in Java and Kotlin that answer belongs to the host's Jackson +`ObjectMapper` (Spring Boot's default ignores it, a plain `ObjectMapper` answers 400). +Gated cross-port by `fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml` +and the `tph/` and `secret-fields/` input scenarios. + The generated update does **not** guard against a concurrent write: two callers patching the same row both succeed, and the last one wins. Adding that guard is adopter-owned — see [Optimistic concurrency](#optimistic-concurrency-adopter-owned). diff --git a/docs/llms/llms-full.txt b/docs/llms/llms-full.txt index 69e45e8a2c..a7db61dfcb 100644 --- a/docs/llms/llms-full.txt +++ b/docs/llms/llms-full.txt @@ -1,6 +1,6 @@ # MetaObjects -- Full Reference Corpus -> Coding agents get context — rules files, memories, MCP servers — and context is advisory: nothing fails when the code stops matching it. MetaObjects gives your agent one typed model of your application — data, API, UI, prompt payloads, and what the software is supposed to do — generates each layer's code from it in TypeScript, Java, Kotlin, C# and Python with no proprietary runtime in the output, and fails your build when generated code, a prompt, or a claimed capability drifts from that model. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.0` on npm and `8.2.0` on Maven Central. +> Coding agents get context — rules files, memories, MCP servers — and context is advisory: nothing fails when the code stops matching it. MetaObjects gives your agent one typed model of your application — data, API, UI, prompt payloads, and what the software is supposed to do — generates each layer's code from it in TypeScript, Java, Kotlin, C# and Python with no proprietary runtime in the output, and fails your build when generated code, a prompt, or a claimed capability drifts from that model. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.2` on npm and `8.2.2` on Maven Central. **Note for AI assistants:** This file is the concatenated reference material for MetaObjects, intended to be loaded as LLM context. For the short index, see [llms.txt](https://metaobjects.dev/llms.txt). For the canonical spec and source, see the [GitHub repo](https://github.com/metaobjectsdev/metaobjects). When this file is out of date relative to the GitHub source, the GitHub source wins. @@ -39,7 +39,7 @@ If you are an AI assistant helping someone adopt MetaObjects, do this **first** 1. **Install the port's package:** - TypeScript / Node: `npm i -D @metaobjectsdev/cli @metaobjectsdev/codegen-ts @metaobjectsdev/metadata typescript @types/better-sqlite3`, then `npm i @metaobjectsdev/runtime-ts drizzle-orm zod fastify better-sqlite3` (SQLite; use `pg` and `@types/pg` for Postgres). The generated files import `drizzle-orm`, `zod`, `fastify` and a driver, and `npm` does not add them for you. - - Java / Kotlin: add `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.0`. + - Java / Kotlin: add `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.2`. - Python: `pip install metaobjects` - C#: install the MetaObjects .NET tool (invoked as `dotnet meta`). 2. **Run `meta init`** (the Node `meta` CLI). It works in any project that has Node — including a JVM or Python project with a TypeScript frontend. It scaffolds a slim always-on `.metaobjects/AGENTS.md` + `.metaobjects/CLAUDE.md` (auto-wired via an `@.metaobjects/AGENTS.md` import line into the project's root `CLAUDE.md`/`AGENTS.md`, so it loads automatically) plus six `metaobjects-*` Claude Code skills under `.claude/skills/`, carrying only the project's language reference fragments. Re-run `meta init --refresh-docs` to update the agent docs after a CLI upgrade. (The Node `meta` CLI is the single agent-context scaffolder for every backend, by design — ADR-0033; the JVM/Python/C# CLIs deliberately redirect to it. For a non-Node project, scaffold just the agent context with `npx meta agent-docs --server `.) @@ -125,13 +125,13 @@ Today the TypeScript toolchain publishes and TypeScript and Python projects cons | Language | Status | Notes | |---|---|---| -| TypeScript | Reference implementation, npm `1.2.0` | All six pillars, and the only port that prints the requirements authoring lint and publishes shared models. 2500+ tests passing. Owns the canonical schema-migration toolchain used by every port (ADR-0015). Bun-first dev. | -| Java | Maven Central `8.2.0` | Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx. Fully green across all conformance corpora. | -| Kotlin | Maven Central `8.2.0` | KotlinPoet codegen + Exposed runtime + `metadata-ktx` facade. Ships via the Java reactor. | -| C# | NuGet `1.2.0` (.NET tool) | Loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. `dotnet meta` tool. | -| Python | PyPI `1.2.0` | Loader + serializer + render + verify + codegen + `ObjectManager` runtime. Fully green across all corpora. | +| TypeScript | Reference implementation, npm `1.2.2` | All six pillars, and the only port that prints the requirements authoring lint and publishes shared models. 2500+ tests passing. Owns the canonical schema-migration toolchain used by every port (ADR-0015). Bun-first dev. | +| Java | Maven Central `8.2.2` | Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx. Fully green across all conformance corpora. | +| Kotlin | Maven Central `8.2.2` | KotlinPoet codegen + Exposed runtime + `metadata-ktx` facade. Ships via the Java reactor. | +| C# | NuGet `1.2.2` (.NET tool) | Loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. `dotnet meta` tool. | +| Python | PyPI `1.2.1` | Loader + serializer + render + verify + codegen + `ObjectManager` runtime. Fully green across all corpora. | -Conformance fixtures live at [`fixtures/`](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures). Every port runs the shared corpus byte-identically: metamodel (`conformance/`, 314 fixtures), render, persistence (Testcontainers Postgres, with an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), api-contract (41 scenarios — 26 core plus TPH / M:N / jsonb / write-through — two lanes: a reference server AND each port's generated API booted over HTTP), registry (byte-matched metamodel-vocabulary manifest, live + green in all five ports), and yaml/verify. +Conformance fixtures live at [`fixtures/`](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures). Every port runs the shared corpus byte-identically: metamodel (`conformance/`, 314 fixtures), render, persistence (Testcontainers Postgres, with an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), api-contract (core REST contract + filter operators, plus TPH / M:N / jsonb / write-through and the other sub-corpora — two lanes: a reference server AND each port's generated API booted over HTTP), registry (byte-matched metamodel-vocabulary manifest, live + green in all five ports), and yaml/verify. --- @@ -182,7 +182,7 @@ Universal web client (`client/web/packages/`): `@metaobjectsdev/runtime-web`, `@ ## Java / Kotlin Maven coordinates -All published to Maven Central under `com.metaobjects:*` at `8.2.0`: +All published to Maven Central under `com.metaobjects:*` at `8.2.2`: - `metaobjects-metadata`, `metaobjects-metadata-ktx` - `metaobjects-codegen-base`, `metaobjects-codegen-mustache`, `metaobjects-codegen-spring`, `metaobjects-codegen-kotlin`, `metaobjects-codegen-plantuml` @@ -219,7 +219,7 @@ Project marker directory: `.metaobjects/`. ## Quickstart (Java / Kotlin) -Add the Maven coordinates above at `8.2.0`. Run codegen with `mvn metaobjects:generate` and codegen-drift checks with `mvn metaobjects:verify`. Configure generators (including Kotlin generators, which run through the same goal) on the `metaobjects-maven-plugin`. See [`server/java/`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java) and [`server/java/codegen-kotlin/README.md`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java/codegen-kotlin). +Add the Maven coordinates above at `8.2.2`. Run codegen with `mvn metaobjects:generate` and codegen-drift checks with `mvn metaobjects:verify`. Configure generators (including Kotlin generators, which run through the same goal) on the `metaobjects-maven-plugin`. See [`server/java/`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java) and [`server/java/codegen-kotlin/README.md`](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java/codegen-kotlin). --- diff --git a/docs/llms/llms.txt b/docs/llms/llms.txt index 60e67dfb70..cd6e4a15ec 100644 --- a/docs/llms/llms.txt +++ b/docs/llms/llms.txt @@ -1,6 +1,6 @@ # MetaObjects -> MetaObjects gives your coding agent one typed model of your application: data, API, UI, prompt payloads, and what the software is supposed to do. It generates each layer's code from that model in TypeScript, Java, Kotlin, C# and Python, with no proprietary runtime in the output. Your build fails when generated code, a prompt or a claimed capability stops matching the model. Rules files and memories are only advice, because nothing fails when the code drifts from them. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.0` on npm and `8.2.0` on Maven Central. +> MetaObjects gives your coding agent one typed model of your application: data, API, UI, prompt payloads, and what the software is supposed to do. It generates each layer's code from that model in TypeScript, Java, Kotlin, C# and Python, with no proprietary runtime in the output. Your build fails when generated code, a prompt or a claimed capability stops matching the model. Rules files and memories are only advice, because nothing fails when the code drifts from them. Your hand-written logic stays yours. Apache 2.0. Shipping at `1.2.2` on npm and `8.2.2` on Maven Central. **One typed model of your app** — data, API, UI, prompt payloads, and what it is supposed to do — that your agent reads and writes. Two things happen to it. @@ -26,7 +26,7 @@ If you are an AI assistant helping someone adopt MetaObjects in their project, d 1. **Install the port's package** for the project's stack: - **TypeScript / Node**: `npm i -D @metaobjectsdev/cli @metaobjectsdev/codegen-ts @metaobjectsdev/metadata typescript @types/better-sqlite3`, then `npm i @metaobjectsdev/runtime-ts drizzle-orm zod fastify better-sqlite3` (SQLite; use `pg` and `@types/pg` for Postgres). The generated files import `drizzle-orm`, `zod`, `fastify` and a driver, and `npm` does not add them for you. - - **Java / Kotlin**: add the Maven dependencies `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and the `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.0`. + - **Java / Kotlin**: add the Maven dependencies `com.metaobjects:metaobjects-metadata`, `com.metaobjects:metaobjects-codegen-spring` (Java) or `com.metaobjects:metaobjects-codegen-kotlin` (Kotlin), and the `com.metaobjects:metaobjects-maven-plugin`, all at `8.2.2`. - **Python**: `pip install metaobjects` - **C#**: install the MetaObjects .NET tool (`dotnet tool install` the MetaObjects CLI tool; invoked as `dotnet meta`). @@ -45,7 +45,7 @@ This `llms.txt` is the short index; the deep, version-matched how-to is the scaf ## Spec and standard - [Specification (canonical, target-agnostic)](https://github.com/metaobjectsdev/metaobjects/tree/main/spec): the normative metadata schema and semantics that every implementation must conform to. -- [Conformance fixtures](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures): cross-port corpora — `conformance/` (metamodel, 314 fixtures), `render-conformance/`, `persistence-conformance/` (against Testcontainers Postgres, including an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), `api-contract-conformance/` (41 scenarios — 26 core REST contract + filter operators, plus TPH / M:N / jsonb / write-through — run in two lanes: a reference server AND each port's generated API booted over HTTP), `registry-conformance/` (byte-matched metamodel-vocabulary manifest, live + green in all five ports), and `yaml-conformance/` / `verify-conformance/`. Every port runs the shared corpus byte-identically. +- [Conformance fixtures](https://github.com/metaobjectsdev/metaobjects/tree/main/fixtures): cross-port corpora — `conformance/` (metamodel, 314 fixtures), `render-conformance/`, `persistence-conformance/` (against Testcontainers Postgres, including an `op: roundtrip` gate so every `field.*` subtype write+read round-trips on every port), `api-contract-conformance/` (core REST contract + filter operators, plus TPH / M:N / jsonb / write-through and the other sub-corpora — run in two lanes: a reference server AND each port's generated API booted over HTTP), `registry-conformance/` (byte-matched metamodel-vocabulary manifest, live + green in all five ports), and `yaml-conformance/` / `verify-conformance/`. Every port runs the shared corpus byte-identically. - [Roadmap](https://github.com/metaobjectsdev/metaobjects/issues?q=is%3Aissue+label%3AFR): current + planned work, tracked as GitHub issues labelled `FR` with milestones per release; [spec/roadmap.md](https://github.com/metaobjectsdev/metaobjects/blob/main/spec/roadmap.md) holds the direction and the index of feature specs. ## The six pillars @@ -65,10 +65,10 @@ MetaObjects pillars are capabilities of one metadata model, not separate product **Sharing a model across your own projects** — today the TypeScript toolchain publishes and TypeScript and Python projects consume, from an installed npm or Python package or over a `path` dependency (a sibling checkout or submodule); Java, Kotlin and C# arrive in Phase 2. One project publishes part of its model with the `sharedModelFile()` generator; another declares it under `dependencies` in `.metaobjects/config.json`, runs `meta deps sync` to commit a hash-locked snapshot, and builds on it with `extends` and references. When the publisher's model moves, `meta verify --deps` reports it instead of two copies drifting apart. -## Implementations (npm `1.2.0` / Maven Central `8.2.0`) +## Implementations (npm `1.2.2` / Maven Central `8.2.2`) -- [TypeScript](https://github.com/metaobjectsdev/metaobjects/tree/main/server/typescript): the reference implementation. Published to npm at `1.2.0` across 14 `@metaobjectsdev/*` packages on the `latest` tag. 2500+ tests passing across the workspace. Bun-first dev workflow. Owns the canonical schema-migration toolchain used by every port (ADR-0015). -- [Java](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java): 14 publishable Maven modules under `com.metaobjects:*` at `8.2.0` on Maven Central (15 artifacts with the parent POM). Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx, full FR-003 + FR-006 + FR-010/011 + FR-018 + FR5 family. Fully green across all conformance corpora. +- [TypeScript](https://github.com/metaobjectsdev/metaobjects/tree/main/server/typescript): the reference implementation. Published to npm at `1.2.2` across 14 `@metaobjectsdev/*` packages on the `latest` tag. 2500+ tests passing across the workspace. Bun-first dev workflow. Owns the canonical schema-migration toolchain used by every port (ADR-0015). +- [Java](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java): 14 publishable Maven modules under `com.metaobjects:*` at `8.2.2` on Maven Central (15 artifacts with the parent POM). Spring REST + DTO + repository-interface codegen, OMDB runtime persistence (pure data-access) with Spring-tx, full FR-003 + FR-006 + FR-010/011 + FR-018 + FR5 family. Fully green across all conformance corpora. - [Kotlin](https://github.com/metaobjectsdev/metaobjects/tree/main/server/java/codegen-kotlin): a Kotlin codegen pipeline on KotlinPoet plus `metadata-ktx` — a Kotlin facade over the Java MetaObjects core. Ships via the Java reactor (`metaobjects-metadata-ktx`, `metaobjects-codegen-kotlin`). Persistence-conformance runs against Testcontainers Postgres through Exposed. - [C#](https://github.com/metaobjectsdev/metaobjects/tree/main/server/csharp): loader + canonical serializer + EF Core + ASP.NET codegen + render/verify. The `dotnet meta` tool ships `gen` and the codegen-side `verify` subverbs (`--codegen`, `--templates`); schema migration is Node `meta` only (ADR-0015). - [Python](https://github.com/metaobjectsdev/metaobjects/tree/main/server/python): loader + canonical serializer + conformance + render + verify + codegen + an `ObjectManager` runtime layer. The `metaobjects` console-script ships `gen` and codegen-side `verify`. Fully green across all conformance corpora. @@ -82,7 +82,7 @@ MetaObjects deliberately does **not** ship one universal binary. Schema operatio - Codegen is **opt-in**: no port ships a default generator suite, `meta init` scaffolds `generators: []`, and `meta gen --list` is the catalog (`--probe` reports how many files each generator would emit for your model) - Project marker directory: `.metaobjects/` - Install (TypeScript reference): `npm install -D @metaobjectsdev/cli` (or `bun add @metaobjectsdev/cli`) -- Install (Java): `com.metaobjectsmetaobjects-metadata8.2.0` plus per-concern artifacts (`metaobjects-codegen-spring`, `metaobjects-omdb`, `metaobjects-maven-plugin`, etc.) +- Install (Java): `com.metaobjectsmetaobjects-metadata8.2.2` plus per-concern artifacts (`metaobjects-codegen-spring`, `metaobjects-omdb`, `metaobjects-maven-plugin`, etc.) - Install (Kotlin): same Maven coordinates — add `metaobjects-metadata-ktx` and `metaobjects-codegen-kotlin` to a JVM/Kotlin project. - Install (Python): `pip install metaobjects` - Install (C#): the MetaObjects .NET tool, invoked as `dotnet meta`. @@ -128,7 +128,7 @@ Universal web-client under `client/web/packages/`: ## Java / Kotlin Maven coordinates -All published to Maven Central under `com.metaobjects:*` at `8.2.0`: +All published to Maven Central under `com.metaobjects:*` at `8.2.2`: - `metaobjects-metadata`, `metaobjects-metadata-ktx` - `metaobjects-codegen-base`, `metaobjects-codegen-mustache`, `metaobjects-codegen-spring`, `metaobjects-codegen-kotlin`, `metaobjects-codegen-plantuml` diff --git a/examples/advanced-modeling/codegen/templates/zod-validators.ts b/examples/advanced-modeling/codegen/templates/zod-validators.ts index ea4945feae..1aafe1a916 100644 --- a/examples/advanced-modeling/codegen/templates/zod-validators.ts +++ b/examples/advanced-modeling/codegen/templates/zod-validators.ts @@ -386,6 +386,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); @@ -393,6 +394,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { */ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { const autoGenPkFields = autoGenPkFieldNames(obj); + const pkFields = primaryKeyFieldNames(obj); const tphPin = tphDiscriminatorPin(obj); const out: SchemaFieldShape[] = []; for (const child of obj.fields()) { @@ -408,6 +410,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { // edit form for an entity carrying one. Clearing counts as a write, so the // FR-035 present-null arm never reaches it either. if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): a primary-key field is the row's identity, which the URL names. An + // ASSIGNED key leaves the update shape exactly like a generated one, so a client-sent + // key is stripped and can never re-key the row. + if (pkFields.has(child.name)) continue; // TPH subtype discriminator: omitted from the update schema entirely. if (tphPin !== undefined && child.name === tphPin.fieldName) continue; const autoSet = child.attr(FIELD_ATTR_AUTO_SET); @@ -491,6 +497,10 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // below; a value presented on PATCH is stripped, not 400'd (see // updateSchemaFields for the grounding). if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): the row's identity is the URL's. An ASSIGNED primary key leaves the + // update shape too (a generated one never entered it), so a client-sent key is stripped + // on PUT/PATCH and can never re-key the row. Mirrors updateSchemaFields. + if (pkFields.has(child.name)) continue; // Update schema: @autoSet onCreate → omit entirely; onUpdate → transform if (autoSet === AUTO_SET_ON_CREATE) { @@ -515,10 +525,8 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // null — a present null CLEARS the column (`.set({field: null})` writes NULL). // Keyed on required-ness, NOT fieldWillBeOptional: a required-with-@default // field stays non-nullable so an explicit null on it is a 400 (validation), - // never a silent clear. PK fields are excluded: their Drizzle column is - // always not-null, so a nullable Zod type would fail `.set()`'s typecheck - // (and NOT NULL at runtime) — see primaryKeyFieldNames. - if (!isRequired(child) && !pkFields.has(child.name)) expr = code`${expr}.nullable()`; + // never a silent clear. PK fields never reach this branch (skipped above). + if (!isRequired(child)) expr = code`${expr}.nullable()`; updateFieldLines.push(code` ${child.name}: ${expr}`); } } diff --git a/examples/showcase/.metaobjects/.gen-state/.hashes.json b/examples/showcase/.metaobjects/.gen-state/.hashes.json index 131a0265b9..84023e786a 100644 --- a/examples/showcase/.metaobjects/.gen-state/.hashes.json +++ b/examples/showcase/.metaobjects/.gen-state/.hashes.json @@ -4,7 +4,7 @@ "generated/csharp/SubscriberBlurbPayload.g.cs": "29eb3a6ce64496ffe734cba55d0213994316b4281d3fa6791917393bae36c9ed", "generated/csharp/SubscriberFilterAllowlist.g.cs": "3839b04884e4e393d4f7d7bf4c7d4fe5b3852bd3a92b1ecb282cb8935a3c98e5", "generated/csharp/SubscriberNames.g.cs": "c2cf0248c2ecde155ec2623604771e39bed23783603d6f18a2ed82967227a732", - "generated/csharp/SubscriberRoutes.g.cs": "15450e230d396a739d789340c42488da354c22265193b5ac61b074b0ba6fb1ff", + "generated/csharp/SubscriberRoutes.g.cs": "d05912d0a76b52334857796a42b2919be8709997d6c073c11d2c44590fe686a9", "generated/python/Subscriber.py": "9dd4c0acea47f99d1daf79930f9de2e400f30780ebce6c63f023be528a72b762", "generated/python/SubscriberBlurbPayload.py": "a5ef8a08e63efbe0f73e39a21a368cff5150c68cc8beeea6e8aab0c755f8bbdd", "generated/python/__init__.py": "daa04cec586768866d0996c779f62073e6773fe63750ff668327991fac2fd0f5", diff --git a/examples/showcase/codegen/templates/zod-validators.ts b/examples/showcase/codegen/templates/zod-validators.ts index ea4945feae..1aafe1a916 100644 --- a/examples/showcase/codegen/templates/zod-validators.ts +++ b/examples/showcase/codegen/templates/zod-validators.ts @@ -386,6 +386,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); @@ -393,6 +394,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { */ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { const autoGenPkFields = autoGenPkFieldNames(obj); + const pkFields = primaryKeyFieldNames(obj); const tphPin = tphDiscriminatorPin(obj); const out: SchemaFieldShape[] = []; for (const child of obj.fields()) { @@ -408,6 +410,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { // edit form for an entity carrying one. Clearing counts as a write, so the // FR-035 present-null arm never reaches it either. if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): a primary-key field is the row's identity, which the URL names. An + // ASSIGNED key leaves the update shape exactly like a generated one, so a client-sent + // key is stripped and can never re-key the row. + if (pkFields.has(child.name)) continue; // TPH subtype discriminator: omitted from the update schema entirely. if (tphPin !== undefined && child.name === tphPin.fieldName) continue; const autoSet = child.attr(FIELD_ATTR_AUTO_SET); @@ -491,6 +497,10 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // below; a value presented on PATCH is stripped, not 400'd (see // updateSchemaFields for the grounding). if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): the row's identity is the URL's. An ASSIGNED primary key leaves the + // update shape too (a generated one never entered it), so a client-sent key is stripped + // on PUT/PATCH and can never re-key the row. Mirrors updateSchemaFields. + if (pkFields.has(child.name)) continue; // Update schema: @autoSet onCreate → omit entirely; onUpdate → transform if (autoSet === AUTO_SET_ON_CREATE) { @@ -515,10 +525,8 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // null — a present null CLEARS the column (`.set({field: null})` writes NULL). // Keyed on required-ness, NOT fieldWillBeOptional: a required-with-@default // field stays non-nullable so an explicit null on it is a 400 (validation), - // never a silent clear. PK fields are excluded: their Drizzle column is - // always not-null, so a nullable Zod type would fail `.set()`'s typecheck - // (and NOT NULL at runtime) — see primaryKeyFieldNames. - if (!isRequired(child) && !pkFields.has(child.name)) expr = code`${expr}.nullable()`; + // never a silent clear. PK fields never reach this branch (skipped above). + if (!isRequired(child)) expr = code`${expr}.nullable()`; updateFieldLines.push(code` ${child.name}: ${expr}`); } } diff --git a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs index ffb1ed369c..9987f12b3c 100644 --- a/examples/showcase/generated/csharp/SubscriberRoutes.g.cs +++ b/examples/showcase/generated/csharp/SubscriberRoutes.g.cs @@ -100,6 +100,8 @@ await db.Subscribers.FindAsync(id) is { } found try { input = System.Text.Json.JsonSerializer.Deserialize(__body.RootElement.GetRawText(), jsonOpts); } catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = "validation" }); } if (input is null) return Results.BadRequest(new { error = "validation" }); + // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored. + input.Id = default!; var __vr = new System.Collections.Generic.List(); if (!System.ComponentModel.DataAnnotations.Validator.TryValidateObject( input, new System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true)) diff --git a/examples/showcase/jvm/pom.xml b/examples/showcase/jvm/pom.xml index f41163da7d..6dcd77e740 100644 --- a/examples/showcase/jvm/pom.xml +++ b/examples/showcase/jvm/pom.xml @@ -23,7 +23,7 @@ - 8.2.0 + 8.2.2 UTF-8 diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 237e16a881..6667d82a4f 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -1,9 +1,9 @@ { "registries": { - "npm": "1.2.0", + "npm": "1.2.2", "pypi": "1.2.1", - "nuget": "1.2.0", - "maven": "8.2.0", + "nuget": "1.2.2", + "maven": "8.2.2", "metamodel": "1.2" }, "counts": { diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 7574beeab5..da4c8f44e1 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -35,6 +35,7 @@ fixtures/api-contract-conformance/ ├── patch-empty-noop.yaml # FR-037 PATCH-5 a patch stripping to zero assignments is a no-op read-back ├── writeonce-patch-stripped.yaml # FR-037 R1 @mutability:"writeOnce" — stripped on PATCH, never rejected ├── autoset-patch.yaml # #203 @autoSet — PATCH bumps onUpdate, leaves onCreate alone + ├── input-server-owned-dropped.yaml # 1.2.x security: a client id / undeclared key never reaches storage ├── delete-204-and-404.yaml ├── invalid-sort-400.yaml ├── filter-eq.yaml # FR-009 filter operators @@ -52,13 +53,13 @@ fixtures/api-contract-conformance/ └── filter-invalid-value.yaml # uncoercible value → 400; the fourth envelope, previously ungated ``` -Beside the 31 core scenarios above sit eight **sub-corpora**, each a directory with its -own `meta.json`, `seed.json`, `scenarios/` and `README.md` (88 scenarios in all, 119 with the +Beside the 32 core scenarios above sit eight **sub-corpora**, each a directory with its +own `meta.json`, `seed.json`, `scenarios/` and `README.md` (90 scenarios in all, 122 with the core): | Directory | Scenarios | Gates | Lanes | |---|---|---|---| -| `tph/` | 10 | single-table inheritance | both | +| `tph/` | 12 | single-table inheritance | both | | `m2m/` | 9 | M:N traversal, and TPH x M:N together | both | | `jsonb/` | 5 | typed value-object columns, and the numbers inside them (a double stays a JSON number; a decimal is a canonical string, option A of the 1.1.0 review) | both | | `write-through/` | 2 | an entity that writes a table and reads a view | generated only | @@ -121,6 +122,7 @@ requests: | `empty` | the response body is empty / null (204 No Content) | | `fieldsEqual`| the response body is an object; assert the listed field names are all equal to **each other** (raw, field-vs-field — no literal, so timestamp non-determinism is a non-issue). Used by the `@autoSet` gate (#203/ADR-0045). | | `fieldsNotEqual`| the response body is an object; assert the two listed fields **differ** from each other. Used by the `@autoSet` gate (e.g. after a PATCH, `autoCreatedAt` (onCreate, preserved) != `autoUpdatedAt` (onUpdate, bumped)). | +| `unset` | the response body is an object; each listed key is **missing or `null`** on it. Used by the input scenarios (`input-server-owned-dropped`, `tph-input-server-owned-dropped`): a value the client was not allowed to set never reached storage, so it never comes back in the echo. Missing and `null` are both accepted because a port's row shape decides whether an unset column is present as `null`. | Runners are responsible for normalizing `createdAt` (and any other non-deterministic fields) before comparison. The keys listed above are diff --git a/fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml b/fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml new file mode 100644 index 0000000000..597ed1b0cc --- /dev/null +++ b/fixtures/api-contract-conformance/scenarios/input-server-owned-dropped.yaml @@ -0,0 +1,85 @@ +name: input-server-owned-dropped +description: > + A write route hands storage only what the client may set (the 1.2.x security fix). A + client-sent `id` on a server-generated key, a key the entity does not declare (`isAdmin`) + and, on update, a `writeOnce` field are all DROPPED SILENTLY: the request answers as if the + key were absent (201/200, never 400), and none of them reaches storage. This is the rule + TypeScript has always followed and Python adopted in 1.2.1. + + Each body carries an ordinary settable field DELIBERATELY: it is applied, and that pairing + is what makes the assertion about the server-owned keys and not about the request being + ignored whole. `unset` asserts the undeclared key is not echoed back (a stored key would + be), and the GETs of the client's ids prove no row was written or re-keyed under them. +requests: + - id: r1 + method: POST + path: /api/authors + body: + id: 999 + name: "Barbara Liskov" + createdAt: "2026-02-01T10:00:00" + isAdmin: true + expect: + status: 201 + body: + row: + name: "Barbara Liskov" + hasId: true + unset: [isAdmin] + - id: r2 + method: GET + path: /api/authors/999 + expect: + status: 404 + - id: r3 + method: PATCH + path: /api/authors/1 + body: + id: 998 + name: "Ada L. (input probe)" + isAdmin: true + expect: + status: 200 + body: + row: + id: 1 + name: "Ada L. (input probe)" + unset: [isAdmin] + - id: r4 + method: PUT + path: /api/authors/2 + body: + id: 997 + name: "Alan T. (input probe)" + createdAt: "2026-01-02T10:00:00" + issuedCurrency: "JPY" + isAdmin: true + expect: + status: 200 + body: + row: + id: 2 + name: "Alan T. (input probe)" + # writeOnce: frozen after create, so the PUT's value never lands. + issuedCurrency: "GBP" + unset: [isAdmin] + - id: r5 + method: GET + path: /api/authors/998 + expect: + status: 404 + - id: r6 + method: GET + path: /api/authors/997 + expect: + status: 404 + - id: r7 + method: GET + path: /api/authors/1 + expect: + status: 200 + body: + row: + id: 1 + name: "Ada L. (input probe)" + unset: [isAdmin] diff --git a/fixtures/api-contract-conformance/secret-fields/README.md b/fixtures/api-contract-conformance/secret-fields/README.md index 29bc632038..ef23edf18d 100644 --- a/fixtures/api-contract-conformance/secret-fields/README.md +++ b/fixtures/api-contract-conformance/secret-fields/README.md @@ -1,8 +1,8 @@ # `api-contract-conformance/secret-fields/` — #484 credentials and excluded fields Cross-port REST contract for the fields a generated API must not expose or accept: a -field excluded from forms (`@formExclude`) and a credential (a field that declares a -`view.password`). +field excluded from forms (`@formExclude`), a credential (a field that declares a +`view.password`) and a server-owned `@mutability: readOnly` field. The model is one `Account`: @@ -11,6 +11,7 @@ The model is one `Account`: | `name` | (nothing) | accepted | returned | | `tokenHash` | `@formExclude: true` | **ignored** | returned | | `pinHash` | child `view.password` | **ignored** | **never returned** | +| `role` | `@mutability: readOnly` | **ignored** | returned | ## The contract diff --git a/fixtures/api-contract-conformance/secret-fields/meta.json b/fixtures/api-contract-conformance/secret-fields/meta.json index d47906d8ad..d000a949a6 100644 --- a/fixtures/api-contract-conformance/secret-fields/meta.json +++ b/fixtures/api-contract-conformance/secret-fields/meta.json @@ -10,6 +10,7 @@ { "field.string": { "name": "name", "@required": true, "@maxLength": 100, "@filterable": true, "@sortable": true } }, { "field.string": { "name": "tokenHash", "@maxLength": 100, "@formExclude": true } }, { "field.string": { "name": "pinHash", "@maxLength": 100, "children": [ { "view.password": {} } ] } }, + { "field.string": { "name": "role", "@maxLength": 20, "@mutability": "readOnly" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] }} diff --git a/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml b/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml index 92f48eb50f..f62e03a4dc 100644 --- a/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml +++ b/fixtures/api-contract-conformance/secret-fields/scenarios/read-omits-credential.yaml @@ -18,6 +18,7 @@ requests: id: 1 name: "Ada Lovelace" tokenHash: "token-hash-1" + role: "member" - id: r2 method: GET path: /api/accounts?sort=id @@ -28,6 +29,8 @@ requests: - id: 1 name: "Ada Lovelace" tokenHash: "token-hash-1" + role: "member" - id: 2 name: "Alan Turing" tokenHash: "token-hash-2" + role: "owner" diff --git a/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml b/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml index 05f5e36306..d0c81f9a47 100644 --- a/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml +++ b/fixtures/api-contract-conformance/secret-fields/scenarios/write-ignores-excluded.yaml @@ -1,8 +1,8 @@ name: write-ignores-excluded description: > - A field excluded from forms (`@formExclude`) or marked as a credential (`view.password`) - is not writable through the generated routes: create, PATCH and PUT all leave it as it - was. The value is IGNORED, never rejected (HTTP 200/201, not 400), the same rule as + A field excluded from forms (`@formExclude`), marked as a credential (`view.password`) or + declared `@mutability: readOnly` (`role`) is not writable through the generated routes: + create, PATCH and PUT all leave it as it was. The value is IGNORED, never rejected (HTTP 200/201, not 400), the same rule as `@mutability: writeOnce` on PATCH (`writeonce-patch-stripped`), because a generated edit form submits every field it was given. @@ -19,6 +19,7 @@ requests: name: "Ada L. (probe)" tokenHash: "forged" pinHash: "forged" + role: "admin" expect: status: 200 body: @@ -26,6 +27,7 @@ requests: id: 1 name: "Ada L. (probe)" tokenHash: "token-hash-1" + role: "member" - id: r2 method: PUT path: /api/accounts/2 @@ -33,6 +35,7 @@ requests: name: "Alan T. (probe)" tokenHash: "forged" pinHash: "forged" + role: "admin" expect: status: 200 body: @@ -40,6 +43,7 @@ requests: id: 2 name: "Alan T. (probe)" tokenHash: "token-hash-2" + role: "owner" - id: r3 method: POST path: /api/accounts @@ -47,6 +51,7 @@ requests: name: "Grace Hopper" tokenHash: "forged" pinHash: "forged" + role: "admin" expect: status: 201 body: @@ -54,6 +59,8 @@ requests: name: "Grace Hopper" # Never written: the column stays null, and `forged` never landed. tokenHash: null + # readOnly is server-owned: a create cannot set it either (1.2.x security fix). + role: null hasId: true - id: r4 method: PATCH @@ -63,6 +70,7 @@ requests: name: "Ada L. (probe 2)" tokenHash: null pinHash: null + role: null expect: status: 200 body: @@ -70,3 +78,4 @@ requests: id: 1 name: "Ada L. (probe 2)" tokenHash: "token-hash-1" + role: "member" diff --git a/fixtures/api-contract-conformance/secret-fields/seed.json b/fixtures/api-contract-conformance/secret-fields/seed.json index 6697ba1fcb..13b7225941 100644 --- a/fixtures/api-contract-conformance/secret-fields/seed.json +++ b/fixtures/api-contract-conformance/secret-fields/seed.json @@ -1,6 +1,6 @@ { "rows": [ - { "id": 1, "name": "Ada Lovelace", "tokenHash": "token-hash-1", "pinHash": "pin-hash-1" }, - { "id": 2, "name": "Alan Turing", "tokenHash": "token-hash-2", "pinHash": "pin-hash-2" } + { "id": 1, "name": "Ada Lovelace", "tokenHash": "token-hash-1", "pinHash": "pin-hash-1", "role": "member" }, + { "id": 2, "name": "Alan Turing", "tokenHash": "token-hash-2", "pinHash": "pin-hash-2", "role": "owner" } ] } diff --git a/fixtures/api-contract-conformance/tph/README.md b/fixtures/api-contract-conformance/tph/README.md index 5c45a2231f..86a18dbb4e 100644 --- a/fixtures/api-contract-conformance/tph/README.md +++ b/fixtures/api-contract-conformance/tph/README.md @@ -49,7 +49,9 @@ tph/ ├── tph-writeonce-patch-stripped.yaml # FR-037: inherited @mutability "writeOnce" stripped on the per-subtype PATCH ├── tph-update-explicit-null-clears.yaml # FR-035 tristate: present null clears; omitted @required untouched; null on @required → 400 ├── tph-create-constraint-violation.yaml # FR-036: per-subtype CREATE validates against the annotated Dto - └── tph-update-constraint-violation.yaml # FR-036: per-subtype PATCH validates each PRESENT value + ├── tph-update-constraint-violation.yaml # FR-036: per-subtype PATCH validates each PRESENT value + ├── tph-input-server-owned-dropped.yaml # 1.2.x security: client id, sibling column, undeclared key never stored + └── tph-input-foreign-discriminator-dropped.yaml # 1.2.x security: the subtype comes from the URL, never the body ``` `meta.json` declares the `acme::auth` package: diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml new file mode 100644 index 0000000000..e4290f706d --- /dev/null +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-input-foreign-discriminator-dropped.yaml @@ -0,0 +1,44 @@ +name: tph-input-foreign-discriminator-dropped +description: > + A per-subtype route takes the row's subtype from the URL, never from the body (the 1.2.x + security fix). A `type` naming a different subtype, sent to the Bridge route, is DROPPED + SILENTLY on create and on update: the created row is a Bridge, no Copay row appears, and an + updated Bridge stays a Bridge. Python's generated TPH routes answer this body with 400 rather + than dropping it; that runner skips this scenario (see the Python codegen KNOWN_GAPS.md). +requests: + - id: r1 + method: POST + path: /api/auths/bridge + body: + type: "Copay" + reference: "REF-DISC" + quantity: 4 + expect: + status: 201 + body: + row: { type: "Bridge", reference: "REF-DISC", quantity: 4 } + hasId: true + - id: r2 + method: GET + path: /api/auths/copay?filter[reference][eq]=REF-DISC + expect: + status: 200 + body: + length: 0 + - id: r3 + method: PATCH + path: /api/auths/bridge/1 + body: + type: "Copay" + reference: "REF-1-DISC" + expect: + status: 200 + body: + row: { id: 1, type: "Bridge", reference: "REF-1-DISC" } + - id: r4 + method: GET + path: /api/auths/copay?filter[reference][eq]=REF-1-DISC + expect: + status: 200 + body: + length: 0 diff --git a/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml b/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml new file mode 100644 index 0000000000..f70f85e341 --- /dev/null +++ b/fixtures/api-contract-conformance/tph/scenarios/tph-input-server-owned-dropped.yaml @@ -0,0 +1,72 @@ +name: tph-input-server-owned-dropped +description: > + The per-subtype write routes hand storage only what the client may set, the same rule as + `input-server-owned-dropped` in the core corpus (the 1.2.x security fix). A client-sent `id` + on the generated key, a key the hierarchy does not declare (`isAdmin`), a column only a + SIBLING subtype declares (`copayAmount` sent to the Bridge route) and, on update, a + `writeOnce` field are all DROPPED SILENTLY (201/200, never 400): the row keeps its + server-assigned id and nothing it may not set is echoed back. A body discriminator is + `tph-input-foreign-discriminator-dropped`. +requests: + - id: r1 + method: POST + path: /api/auths/bridge + body: + id: 999 + reference: "REF-INPUT" + quantity: 3 + copayAmount: "7.77" + isAdmin: true + expect: + status: 201 + body: + row: { type: "Bridge", reference: "REF-INPUT", quantity: 3 } + hasId: true + unset: [isAdmin, copayAmount] + - id: r2 + method: GET + path: /api/auths/999 + expect: + status: 404 + - id: r3 + method: GET + path: /api/auths/copay?filter[copayAmount][eq]=7.77 + expect: + status: 200 + body: + length: 0 + - id: r4 + method: PATCH + path: /api/auths/bridge/1 + body: + id: 998 + reference: "REF-1-INPUT" + issuedCurrency: "JPY" + isAdmin: true + expect: + status: 200 + body: + row: { id: 1, type: "Bridge", reference: "REF-1-INPUT", issuedCurrency: "USD" } + unset: [isAdmin] + - id: r5 + method: PUT + path: /api/auths/copay/2 + body: + id: 997 + reference: "REF-2-INPUT" + isAdmin: true + expect: + status: 200 + body: + row: { id: 2, type: "Copay", reference: "REF-2-INPUT" } + unset: [isAdmin] + - id: r6 + method: GET + path: /api/auths/998 + expect: + status: 404 + - id: r7 + method: GET + path: /api/auths/997 + expect: + status: 404 diff --git a/server/csharp/Directory.Build.props b/server/csharp/Directory.Build.props index 64e1f7c16b..9c9c41a6c0 100644 --- a/server/csharp/Directory.Build.props +++ b/server/csharp/Directory.Build.props @@ -8,7 +8,7 @@ --> - 1.2.0 + 1.2.2 Doug Mealing Doug Mealing LLC MetaObjects diff --git a/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs new file mode 100644 index 0000000000..aba045fa26 --- /dev/null +++ b/server/csharp/MetaObjects.Codegen.Tests/ServerOwnedCreateInputTests.cs @@ -0,0 +1,236 @@ +// ServerOwnedCreateInputTests — a generated create hands storage ONLY what the client may set. +// The HTTP behaviour is gated by the api-contract corpus (`input-server-owned-dropped`, +// `tph-input-server-owned-dropped`, secret-fields); this pins the emission: the generated key, +// the TPH discriminator and the M:N navigations are reset before `Add`, and a readOnly field of +// EVERY shape (including a TPH subtype's own) is declared with a private setter. + +using MetaObjects.Codegen; +using MetaObjects.Codegen.Generators; +using MetaObjects.Loader; +using MetaObjects.Meta; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Xunit; + +namespace MetaObjects.Codegen.Tests; + +public class ServerOwnedCreateInputTests +{ + private const string PlainModel = """ + { "metadata.root": { "package": "acme::input", "children": [ + { "object.entity": { "name": "Post", "children": [ + { "source.rdb": { "@table": "posts" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@maxLength": 100 } }, + { "field.string": { "name": "role", "@maxLength": 20, "@mutability": "readOnly" } }, + { "field.enum": { "name": "stage", "@values": ["Draft", "Live"], "@mutability": "readOnly" } }, + { "relationship.association": { "name": "tags", "@cardinality": "many", "@objectRef": "Tag", "@through": "PostTag" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "PostTag", "children": [ + { "source.rdb": { "@table": "post_tags" } }, + { "field.long": { "name": "postId" } }, + { "field.long": { "name": "tagId" } }, + { "identity.primary": { "@fields": ["postId", "tagId"] } }, + { "identity.reference": { "name": "fkPost", "@fields": "postId", "@references": "Post" } }, + { "identity.reference": { "name": "fkTag", "@fields": "tagId", "@references": "Tag" } } + ]}} + ]}} + """; + + private const string AssignedKeyModel = """ + { "metadata.root": { "package": "acme::input", "children": [ + { "object.entity": { "name": "Code", "children": [ + { "source.rdb": { "@table": "codes" } }, + { "field.string": { "name": "id", "@maxLength": 20 } }, + { "identity.primary": { "@fields": "id", "@generation": "assigned" } } + ]}} + ]}} + """; + + private const string TphModel = """ + { "metadata.root": { "package": "acme::input", "children": [ + { "object.entity": { "name": "Thing", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "things" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "AThing", "extends": "Thing", "@discriminatorValue": "A", "children": [ + { "field.string": { "name": "note", "@maxLength": 20 } }, + { "field.string": { "name": "grade", "@maxLength": 20, "@mutability": "readOnly" } } + ]}}, + { "object.entity": { "name": "BThing", "extends": "Thing", "@discriminatorValue": "B", "children": [ + { "field.int": { "name": "qty" } } + ]}} + ]}} + """; + + private const string RequiredReadOnlyModel = """ + { "metadata.root": { "package": "acme::input", "children": [ + { "object.entity": { "name": "Member", "children": [ + { "source.rdb": { "@table": "members" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@required": true, "@maxLength": 100 } }, + { "field.string": { "name": "role", "@required": true, "@maxLength": 20, "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}} + ]}} + """; + + // A legal way to say "the server owns this": the generated increment key and the TPH + // discriminator are themselves @mutability: readOnly. The entity then declares both with + // PRIVATE setters (A_readOnly_field_of_every_shape_has_a_private_setter), so a create that + // reset them (`input.Id = default!;`) would not compile in the adopter's build — CS0122. + private const string ReadOnlyKeyAndDiscriminatorModel = """ + { "metadata.root": { "package": "acme::input", "children": [ + { "object.entity": { "name": "Seal", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "seals" } }, + { "field.long": { "name": "id", "@mutability": "readOnly" } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"], "@mutability": "readOnly" } }, + { "field.string": { "name": "label", "@maxLength": 40 } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ]}}, + { "object.entity": { "name": "ASeal", "extends": "Seal", "@discriminatorValue": "A", "children": [ + { "field.int": { "name": "qty" } } + ]}}, + { "object.entity": { "name": "BSeal", "extends": "Seal", "@discriminatorValue": "B", "children": [ + { "field.string": { "name": "note", "@maxLength": 40 } } + ]}} + ]}} + """; + + private static string Emit(string model, string generator, string file) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "input.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), + Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal }, + }; + IGenerator g = generator == "routes" ? new RoutesGenerator() : new EntityGenerator(); + return g.Generate(ctx).Single(f => f.Path == file).Content; + } + + [Fact] + public void Create_resets_a_generated_key_and_empties_navigations_before_Add() + { + var src = Emit(PlainModel, "routes", "PostRoutes.g.cs"); + var post = src[src.IndexOf("app.MapPost(", StringComparison.Ordinal)..]; + var reset = post.IndexOf("input.Id = default!;", StringComparison.Ordinal); + var tags = post.IndexOf("input.Tags = new System.Collections.Generic.List();", StringComparison.Ordinal); + var add = post.IndexOf("db.Posts.Add(input);", StringComparison.Ordinal); + Assert.True(reset >= 0 && tags >= 0 && add > reset && add > tags, post); + } + + [Fact] + public void An_assigned_key_is_the_callers_and_is_not_reset() + { + var src = Emit(AssignedKeyModel, "routes", "CodeRoutes.g.cs"); + Assert.DoesNotContain("input.Id = default!;", src); + Assert.DoesNotContain("Server-owned", src); + } + + [Fact] + public void A_readOnly_field_of_every_shape_has_a_private_setter() + { + var src = Emit(PlainModel, "entity", "Post.g.cs"); + Assert.Contains("Role { get; private set; }", src); + Assert.Contains("Stage { get; private set; }", src); + Assert.Contains("Title { get; set; }", src); + } + + [Fact] + public void A_tph_subtype_readOnly_field_has_a_private_setter() + { + var src = Emit(TphModel, "entity", "AThing.g.cs"); + Assert.Contains("Grade { get; private set; }", src); + Assert.Contains("Note { get; set; }", src); + } + + [Fact] + public void A_required_readOnly_field_is_not_demanded_of_the_create_body() + { + // The client cannot set `role` (private setter), so the create must neither require its + // key nor reject the body over its [Required]: otherwise the entity could not be created. + var src = Emit(RequiredReadOnlyModel, "routes", "MemberRoutes.g.cs"); + var post = src[src.IndexOf("app.MapPost(", StringComparison.Ordinal)..]; + var req = post[post.IndexOf("foreach (var __req in", StringComparison.Ordinal)..]; + req = req[..req.IndexOf('\n')]; + Assert.Contains("\"title\"", req); + Assert.DoesNotContain("\"role\"", req); + Assert.Contains("System.Array.IndexOf(new[] { \"Role\" }, m) < 0", post); + var syntaxErrors = CSharpSyntaxTree.ParseText(src).GetDiagnostics() + .Where(d => d.Severity == DiagnosticSeverity.Error).Select(d => d.ToString()).ToList(); + Assert.True(syntaxErrors.Count == 0, string.Join("\n", syntaxErrors)); + } + + [Fact] + public void Tph_subtype_create_resets_the_key_and_pins_the_discriminator_to_the_route_subtype() + { + var src = Emit(TphModel, "routes", "ThingRoutes.g.cs"); + var start = src.IndexOf("app.MapPost(prefix + \"/things/a\"", StringComparison.Ordinal); + var end = src.IndexOf("app.MapPost(prefix + \"/things/b\"", StringComparison.Ordinal); + Assert.True(start >= 0 && end > start, src); + var a = src[start..end]; + Assert.Contains("input.Id = default!;", a); + Assert.Contains("input.Kind = default!;", a); + Assert.True(a.IndexOf("input.Kind = default!;", StringComparison.Ordinal) < a.IndexOf(".Add(input);", StringComparison.Ordinal), a); + } + + [Fact] + public void A_readOnly_key_and_readOnly_discriminator_get_no_reset_and_the_model_compiles() + { + // System.Text.Json never binds a private setter, so the resets would be redundant — + // and CS0122. Oracle: the Roslyn compile of the generated tree (the adopter's build); + // the wrong behavior rejected is `input.Id = default!;` / `input.Kind = default!;` + // assigning private-setter properties. + var r = new MetaDataLoader().Load([new InMemoryStringSource(ReadOnlyKeyAndDiscriminatorModel, id: "ro-key.json")]); + Assert.Empty(r.Errors); + var ctx = new GenContext + { + Entities = r.Root.Objects(), + Root = r.Root, + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", ColumnNamingStrategy = ColumnNamingStrategy.Literal }, + }; + var sources = new EntityGenerator().Generate(ctx) + .Concat(new DbContextGenerator().Generate(ctx)) + .Concat(new FilterAllowlistGenerator().Generate(ctx)) + .Concat(new RoutesGenerator().Generate(ctx)) + .ToList(); + var routes = sources.Single(f => f.Path == "SealRoutes.g.cs").Content; + var post = routes[routes.IndexOf("app.MapPost(", StringComparison.Ordinal)..]; + Assert.DoesNotContain("input.Id = default!;", post); + Assert.DoesNotContain("input.Kind = default!;", post); + + var trees = sources + .Select(f => CSharpSyntaxTree.ParseText(f.Content, new CSharpParseOptions(LanguageVersion.CSharp12), path: f.Path)) + .ToList(); + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + var tpa = (string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!; + foreach (var p in tpa.Split(Path.PathSeparator)) if (p.Length > 0) paths.Add(p); + paths.Add(typeof(Microsoft.EntityFrameworkCore.DbContext).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.ModelBuilder).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions).Assembly.Location); + paths.Add(typeof(Microsoft.EntityFrameworkCore.PrimaryKeyAttribute).Assembly.Location); + paths.Add(typeof(MetaObjects.Codegen.Runtime.FilterParser).Assembly.Location); + var refs = paths.Where(File.Exists) + .Select(p => (MetadataReference)MetadataReference.CreateFromFile(p)).ToList(); + var comp = CSharpCompilation.Create( + "ro_key_disc_compile_" + Guid.NewGuid().ToString("N"), trees, refs, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + var errors = comp.GetDiagnostics() + .Where(d => d.Severity == DiagnosticSeverity.Error) + .Select(d => $"{d.Id}: {d.GetMessage()} @ {d.Location}") + .ToList(); + Assert.True(errors.Count == 0, + "readOnly key + readOnly discriminator model must compile:\n" + string.Join("\n", errors)); + } +} diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 810c3c78e7..b278fac020 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -626,9 +626,9 @@ protected virtual string TphSubtypeScalarProperty( // A NON-required decimal array is nullable (no initializer) so PATCH null / an omitted // POST value stays a NULL column instead of failing as a required collection. if (IsDecimalWireField(field) && !CSharpNaming.IsRequired(entity, field)) - arr.Append($" public IList<{baseType}>? {propName} {{ get; set; }}"); + arr.Append($" public IList<{baseType}>? {propName} {{ {SetterFor(field)} }}"); else - arr.Append($" public IList<{baseType}> {propName} {{ get; set; }} = new List<{baseType}>();"); + arr.Append($" public IList<{baseType}> {propName} {{ {SetterFor(field)} }} = new List<{baseType}>();"); return arr.ToString(); } @@ -653,7 +653,7 @@ protected virtual string TphSubtypeScalarProperty( var init = defaultInit.Length > 0 ? defaultInit : (required && !isValue ? " = default!;" : string.Empty); - sb.Append($" public {baseType}{nullable} {propName} {{ get; set; }}{init}"); + sb.Append($" public {baseType}{nullable} {propName} {{ {SetterFor(field)} }}{init}"); return sb.ToString(); } @@ -665,9 +665,9 @@ protected virtual string TphSubtypeEnumProperty(MetaObject entity, MetaField fie var propName = PropertyName(field); var colAttr = $" [Column({CSharpNaming.ColumnRef(entity, field, strategy, config.IncludeNames)})]\n"; if (field.ResolvedIsArray()) // ADR-0039: resolving — array-ness inheritable via extends - return $"{colAttr} public IList<{typeName}> {propName} {{ get; set; }} = new List<{typeName}>();"; + return $"{colAttr} public IList<{typeName}> {propName} {{ {SetterFor(field)} }} = new List<{typeName}>();"; var nullable = CSharpNaming.IsRequired(entity, field) ? "" : "?"; - return $"{colAttr} public {typeName}{nullable} {propName} {{ get; set; }}"; + return $"{colAttr} public {typeName}{nullable} {propName} {{ {SetterFor(field)} }}"; } // The directly-extended entity (the metadata `extends` target) of a TPH subtype — the @@ -1528,10 +1528,10 @@ protected virtual string EnumProperty( var propName = PropertyName(field); var colAttr = withAttributes ? $" [Column({CSharpNaming.ColumnRef(entity, field, strategy, config.IncludeNames)})]\n" : ""; if (field.ResolvedIsArray()) // ADR-0039: resolving — array-ness inheritable via extends - return $"{colAttr} public IList<{typeName}> {propName} {{ get; set; }} = new List<{typeName}>();"; + return $"{colAttr} public IList<{typeName}> {propName} {{ {SetterFor(field)} }} = new List<{typeName}>();"; var required = CSharpNaming.IsRequired(entity, field); var type = required ? typeName : typeName + "?"; - return $"{colAttr} public {type} {propName} {{ get; set; }}"; + return $"{colAttr} public {type} {propName} {{ {SetterFor(field)} }}"; } // A scalar property. withAttributes adds the EF-mapping annotations ([Key] for a @@ -1589,9 +1589,9 @@ protected virtual string ScalarProperty( // NON-required value-object array is nullable so a null member is omitted on the wire. var omittable = valueObject && _wire.NullMembers == NullMemberForm.Omit; if ((IsDecimalWireField(field) || omittable) && !CSharpNaming.IsRequired(owner, field)) - arr.Append($" public IList<{baseType}>? {propName} {{ get; set; }}"); + arr.Append($" public IList<{baseType}>? {propName} {{ {SetterFor(field)} }}"); else - arr.Append($" public IList<{baseType}> {propName} {{ get; set; }} = new List<{baseType}>();"); + arr.Append($" public IList<{baseType}> {propName} {{ {SetterFor(field)} }} = new List<{baseType}>();"); return arr.ToString(); } @@ -1660,11 +1660,21 @@ protected virtual string ScalarProperty( // the column from UPDATE). `writeOnce` keeps a PUBLIC setter on purpose — the caller // must be able to supply it on insert; freezing it afterwards is the DbContext's // SetAfterSaveBehavior(Ignore), not the property's job. - var setter = field.IsReadOnlyMutability ? "get; private set;" : "get; set;"; + var setter = SetterFor(field); sb.Append($" public {type} {propName} {{ {setter} }}{init}"); return sb.ToString(); } + // FR-037 R1 / SECURITY (1.2.x) — the accessor pair of a mapped property. A `readOnly` field + // takes a PRIVATE setter on EVERY property shape (scalar, enum, array, value object, map; plain + // entity or TPH subtype): EF materializes it on read and application code cannot write it, so + // the generated create route's body binding (System.Text.Json skips a non-public setter) can + // never hand a client-supplied value to storage. Before 1.2.x only the plain scalar shape did, + // so a readOnly enum, array, value-object, map or TPH-subtype field was writable on create. + // `writeOnce` keeps a PUBLIC setter on purpose (the caller supplies it on insert). + private static string SetterFor(MetaField field) => + field.IsReadOnlyMutability ? "get; private set;" : "get; set;"; + // String length + pattern DataAnnotations for a string scalar, combining the field // @maxLength attr with validator.length (@min/@max) and validator.regex (@pattern). // @@ -1889,11 +1899,11 @@ protected static string EscapeAttrString(string s) // null-vs-empty distinction (EF re-serializes the empty list to `[]` on write). if (field.ResolvedIsArray()) // ADR-0039: resolving — array-ness inheritable via extends return required - ? $" public ICollection<{typeName}> {propName} {{ get; set; }} = new List<{typeName}>();" - : $" public ICollection<{typeName}>? {propName} {{ get; set; }}"; + ? $" public ICollection<{typeName}> {propName} {{ {SetterFor(field)} }} = new List<{typeName}>();" + : $" public ICollection<{typeName}>? {propName} {{ {SetterFor(field)} }}"; return required - ? $" public {typeName} {propName} {{ get; set; }} = default!;" - : $" public {typeName}? {propName} {{ get; set; }}"; + ? $" public {typeName} {propName} {{ {SetterFor(field)} }} = default!;" + : $" public {typeName}? {propName} {{ {SetterFor(field)} }}"; } // A property for a field.map (an open-keyed map). Emits a single @@ -1922,8 +1932,8 @@ protected string MapProperty(MetaObject owner, MetaField field, GenContext ctx, var required = CSharpNaming.IsRequired(owner, field); var colAttr = withAttributes ? $" [Column({CSharpNaming.ColumnRef(owner, field, ctx.Config.ColumnNamingStrategy, ctx.Config.IncludeNames)})]\n" : ""; return required - ? $"{colAttr} public Dictionary {propName} {{ get; set; }} = new();" - : $"{colAttr} public Dictionary? {propName} {{ get; set; }}"; + ? $"{colAttr} public Dictionary {propName} {{ {SetterFor(field)} }} = new();" + : $"{colAttr} public Dictionary? {propName} {{ {SetterFor(field)} }}"; } // The CLR scalar type for a projection field whose value is a MIN/MAX aggregate: diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index f254e8ec63..067bcf96cf 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -418,7 +418,8 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte AppendCreateHandler(sb, "/" + route, cls, dbSet, requiredKeys, CreatedResult("prefix + \"/" + route + "\"", "input", credentials), voFields, mapVoFields, autoSetFields, writeThrough ? (readDbSet, pkProp!, route) : null, parseBody: HasDecimalField(entity), - deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials); + deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials, + ServerOwnedCreateResets(entity, ctx.Root), RequiredReadOnlyProps(entity)); // PATCH + PUT share the same handler — TS reference exposes both verbs, and both // return the updated row (HTTP 200), matching the cross-port api-contract. @@ -595,6 +596,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t bool hasItem = pkType is not null; var discProp = CSharpNaming.Pascal(tph.DiscriminatorField); + var discField = baseEntity.FindField(tph.DiscriminatorField); // #484 — the polymorphic base rows carry every subtype's columns, so a credential declared // on the base OR on any subtype is omitted from them. var baseCredentials = CredentialNames(baseEntity) @@ -706,7 +708,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t // --- Per-subtype CRUD sets --- var hierarchy = tph.Subtypes.Select(s => s.Entity).Prepend(baseEntity).ToList(); foreach (var st in tph.Subtypes) - AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, ctx.Warn); + AppendTphSubtypeRoutes(sb, st, hierarchy, ctx.Root, baseRoute, baseCls, dbSet, pkType!, pkProp!, discProp, discField, ctx.Warn); } sb.AppendLine(); @@ -756,10 +758,23 @@ private static List RequiredCreateKeys(MetaObject obj, Func f.IsRequired && f.AutoSet is null && !f.IsDerived() && !isPkOrDisc(f)) + // 1.2.x security — a readOnly field is never bound from the body (private setter), + // so demanding its key would make a @required readOnly entity uncreatable. + .Where(f => f.IsRequired && f.AutoSet is null && !f.IsDerived() && !f.IsReadOnlyMutability + && !isPkOrDisc(f)) .Select(f => f.Name) .ToList(); + // 1.2.x security — the CLR properties of the @required readOnly fields. The client cannot + // set them (private setter), so their [Required] describes the stored row, not the create + // body: the create validation ignores a violation that names only these members, as Java's + // SERVER_OWNED_ON_CREATE filter does. Empty for nearly every model → byte-identical output. + private static List RequiredReadOnlyProps(MetaObject obj) => + obj.Fields() + .Where(f => f.IsRequired && f.IsReadOnlyMutability && !f.IsDerived()) + .Select(f => CSharpNaming.Pascal(f.Name)) + .ToList(); + // Issue #203 — one @autoSet timestamp column the generated CRUD stamps with now(). // Nav is the PascalCase CLR property; NowExpr is the now() literal keyed off the // COLUMN's temporal CLR type (generalizes beyond DateTimeOffset). OnUpdate columns @@ -988,7 +1003,9 @@ private static void AppendCreateHandler( (string ReadDbSet, string PkProp, string Route)? reRead = null, bool parseBody = false, IReadOnlyList? deniedNavs = null, - IReadOnlyList? credentials = null) + IReadOnlyList? credentials = null, + IReadOnlyList? serverOwned = null, + IReadOnlyList? readOnlyRequired = null) { // A decimal field can refuse its value while the body is bound (out of declared range, not a // number). The framework's own binding answers that with a bare 400 and no body, so an entity @@ -997,8 +1014,9 @@ private static void AppendCreateHandler( { sb.AppendLine($" app.MapPost(prefix + \"{mapPath}\", async ({cls} input, AppDbContext db) =>"); sb.AppendLine(" {"); + AppendCreateServerOwned(sb, serverOwned); AppendCreateIgnoreDenied(sb, deniedNavs); - AppendCreateValidation(sb); + AppendCreateValidation(sb, readOnlyRequired); AppendCreateVoValidation(sb, voFields, mapVoFields); AppendCreateAutoSet(sb, autoSetFields); AppendCreatePersist(sb, dbSet, createdExpr, reRead, credentials ?? []); @@ -1033,8 +1051,9 @@ private static void AppendCreateHandler( sb.AppendLine(" try { input = System.Text.Json.JsonSerializer.Deserialize<" + cls + ">(__body.RootElement.GetRawText(), jsonOpts); }"); sb.AppendLine(" catch (System.Text.Json.JsonException) { return Results.BadRequest(new { error = \"validation\" }); }"); sb.AppendLine(" if (input is null) return Results.BadRequest(new { error = \"validation\" });"); + AppendCreateServerOwned(sb, serverOwned); AppendCreateIgnoreDenied(sb, deniedNavs); - AppendCreateValidation(sb); + AppendCreateValidation(sb, readOnlyRequired); AppendCreateVoValidation(sb, voFields, mapVoFields); AppendCreateAutoSet(sb, autoSetFields); AppendCreatePersist(sb, dbSet, createdExpr, reRead, credentials ?? []); @@ -1067,6 +1086,49 @@ private static void AppendCreatePersist( } } + // SECURITY (1.2.x) — a generated create hands storage ONLY what the client may set. The body is + // bound straight onto the EF entity, so every member the server owns is reset before validation + // and `Add`, and the request answers as if the key were absent (never a 400): + // - a server-generated primary key (@generation increment|uuid): default, so EF generates it; + // - the TPH discriminator on a per-subtype route: default, so EF's discriminator value + // generator stamps the route subtype's own @discriminatorValue (the route is its only source); + // - M:N navigation collections: emptied, else `Add` would insert a client-sent related graph. + // A readOnly field needs no line here: the entity declares it with a private setter, which + // System.Text.Json never binds (EntityGenerator.SetterFor). + private static void AppendCreateServerOwned(StringBuilder sb, IReadOnlyList? statements) + { + if (statements is null || statements.Count == 0) return; + sb.AppendLine(" // Server-owned: a generated key, the TPH discriminator and M:N navigations are not settable by the client; the value is ignored."); + foreach (var st in statements) sb.AppendLine(" " + st); + } + + // The reset statements AppendCreateServerOwned emits for one entity (empty when it has none, so an + // entity with an assigned key, no navigation and no discriminator keeps its output byte-identical). + // A TPH subtype class declares no M:N property of its own — the navigations it carries are its + // discriminator base class's — so a subtype route passes that base as navOwner. The key and + // discriminator resets are SKIPPED when that field is itself @mutability: readOnly: the entity + // declares it with a private setter (EntityGenerator.SetterFor), so the assignment would be + // CS0122 — and it is redundant, because System.Text.Json never binds a private setter. + private static List ServerOwnedCreateResets(MetaObject entity, MetaRoot root, MetaField? discField = null, MetaObject? navOwner = null) + { + var list = new List(); + if (entity.PrimaryIdentity() is MetaPrimaryIdentity pk + && pk.Generation is MetaObjects.Core.Identity.IdentityConstants.GENERATION_INCREMENT + or MetaObjects.Core.Identity.IdentityConstants.GENERATION_UUID + && pk.Fields is [var keyName] + && entity.Fields().FirstOrDefault(f => f.Name == keyName) is { } keyField + && !keyField.IsReadOnlyMutability) + list.Add($"input.{CSharpNaming.Pascal(keyField.Name)} = default!;"); + if (discField is not null && !discField.IsReadOnlyMutability) + list.Add($"input.{CSharpNaming.Pascal(discField.Name)} = default!;"); + foreach (var nav in M2MNavigationBuilder.For(navOwner ?? entity, root, _ => { })) + { + var target = CSharpNaming.Pascal(nav.Target.Name); + list.Add($"input.{CSharpNaming.Pascal(nav.Name)} = new System.Collections.Generic.List<{target}>();"); + } + return list; + } + // #484 — a write-denied key (@formExclude or credential) on a create body is IGNORED, never // rejected: the bound value is reset to the CLR default (unset / null) before validation. private static void AppendCreateIgnoreDenied(StringBuilder sb, IReadOnlyList? deniedNavs) @@ -1214,11 +1276,23 @@ private static void AppendJsonOptsLocal(StringBuilder sb) // bound `input` and rejects a violating body with the cross-port {error:"validation"} // envelope BEFORE the row is persisted (ASP.NET minimal-API model binding never runs // DataAnnotations on its own). Assumes the bound local `input` is in scope. - private static void AppendCreateValidation(StringBuilder sb) + // A violation naming only a @required readOnly member () + // is ignored: the client cannot set that member, so it cannot satisfy the rule. + private static void AppendCreateValidation(StringBuilder sb, IReadOnlyList? readOnlyRequired = null) { sb.AppendLine(" var __vr = new System.Collections.Generic.List();"); sb.AppendLine(" if (!System.ComponentModel.DataAnnotations.Validator.TryValidateObject("); - sb.AppendLine(" input, new System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true))"); + if (readOnlyRequired is null || readOnlyRequired.Count == 0) + { + sb.AppendLine(" input, new System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true))"); + } + else + { + var names = string.Join(", ", readOnlyRequired.Select(n => "\"" + n + "\"")); + sb.AppendLine(" input, new System.ComponentModel.DataAnnotations.ValidationContext(input), __vr, true)"); + sb.AppendLine($" && __vr.Exists(r => !System.Linq.Enumerable.Any(r.MemberNames)"); + sb.AppendLine($" || System.Linq.Enumerable.Any(r.MemberNames, m => System.Array.IndexOf(new[] {{ {names} }}, m) < 0)))"); + } sb.AppendLine(" return Results.BadRequest(new { error = \"validation\" });"); } @@ -1376,7 +1450,7 @@ private static void AppendPartialMergeLoop( // that never touches the PK or the discriminator. private static void AppendTphSubtypeRoutes( StringBuilder sb, TphSubtypePlan st, IReadOnlyList hierarchy, MetaRoot root, string baseRoute, string baseCls, string dbSet, - string pkType, string pkProp, string discProp, Action onWarn) + string pkType, string pkProp, string discProp, MetaField? discField, Action onWarn) { // #362 — field.object columns on a TPH subtype stay out of scope (Program D §6), but a // field.map @objectRef is NOT: it reaches the settable set, so its value objects reach @@ -1448,7 +1522,9 @@ private static void AppendTphSubtypeRoutes( AppendCreateHandler(sb, "/" + subRoute, subCls, dbSet, requiredKeys, CreatedResult("prefix + \"/" + subRoute + "/\" + input." + pkProp, "input", credentials), [], mapVoFields, autoSetFields, parseBody: HasDecimalField(st.Entity), - deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials); + deniedNavs: deniedFields.Select(f => CSharpNaming.Pascal(f.Name)).ToList(), credentials: credentials, + serverOwned: ServerOwnedCreateResets(st.Entity, root, discField, hierarchy[0]), + readOnlyRequired: RequiredReadOnlyProps(st.Entity)); // Per-subtype update (PATCH + PUT): partial merge of the JSON body onto the scoped // entity, NEVER touching the PK or the discriminator. Cross-subtype id → 404. diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs index e6bc127b54..13ca20b229 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractAssertions.cs @@ -151,6 +151,19 @@ public static void AssertResponse(string scenarioName, ApiRequest request, int s $"{scenarioName} / {request.Id}: expected row.{kvp.Key}={Render(kvp.Value)}, got {Render(actual)}"); } } + // Each listed key is missing or null: a value the client may not set never reached storage. + // (Missing-or-null, not strictly missing: ports differ on echoing an unset column as null.) + if (want.TryGetValue("unset", out var unsetObj) && unsetObj is List unsetKeys) + { + if (body is not Dictionary unsetRow) + throw new Xunit.Sdk.XunitException( + $"{scenarioName} / {request.Id}: expected object for unset, got: {Render(body)}"); + var stored = unsetKeys.Select(k => k?.ToString() ?? "") + .Where(k => unsetRow.TryGetValue(k, out var v) && v is not null).ToList(); + if (stored.Count > 0) + throw new Xunit.Sdk.XunitException( + $"{scenarioName} / {request.Id}: expected {string.Join(", ", stored)} unset, got: {Render(body)}"); + } if (want.TryGetValue("hasId", out var hasIdObj) && hasIdObj is bool hi && hi) { if (body is not Dictionary row) diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsConformanceTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsConformanceTest.cs index 9314afaa29..09066f09e7 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsConformanceTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractSecretFieldsConformanceTest.cs @@ -37,7 +37,7 @@ private static async Task AssertStoredSecretsUntouchedAsync(string connString) await using var c = new Npgsql.NpgsqlConnection(connString); await c.OpenAsync(); await using var cmd = c.CreateCommand(); - cmd.CommandText = "SELECT \"id\", \"tokenHash\", \"pinHash\" FROM \"accounts\" ORDER BY \"id\""; + cmd.CommandText = "SELECT \"id\", \"tokenHash\", \"pinHash\", \"role\" FROM \"accounts\" ORDER BY \"id\""; await using var reader = await cmd.ExecuteReaderAsync(); var seen = new HashSet(); while (await reader.ReadAsync()) @@ -45,16 +45,19 @@ private static async Task AssertStoredSecretsUntouchedAsync(string connString) long id = reader.GetInt64(0); string? token = reader.IsDBNull(1) ? null : reader.GetString(1); string? pin = reader.IsDBNull(2) ? null : reader.GetString(2); + string? role = reader.IsDBNull(3) ? null : reader.GetString(3); seen.Add(id); if (seed.TryGetValue(id, out var row)) { Assert.Equal(row["tokenHash"]!.GetValue(), token); Assert.Equal(row["pinHash"]!.GetValue(), pin); + Assert.Equal(row["role"]!.GetValue(), role); // readOnly: no write path reaches it } else { Assert.Null(token); Assert.Null(pin); + Assert.Null(role); } } Assert.True(seed.Keys.All(seen.Contains), "a seeded row went missing"); diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs index 2aaf7d81ca..7818486b16 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/SecretFieldsFixture.cs @@ -12,6 +12,7 @@ internal static class SecretFieldsFixture "name" VARCHAR(100) NOT NULL, "tokenHash" VARCHAR(100) NULL, "pinHash" VARCHAR(100) NULL, + "role" VARCHAR(20) NULL, CONSTRAINT "accounts_pkey" PRIMARY KEY ("id") ); """; @@ -29,7 +30,7 @@ public static async Task ApplySeedAsync(string connString, string seedPath) { var root = JsonNode.Parse(File.ReadAllText(seedPath)) as JsonObject ?? throw new InvalidOperationException($"{seedPath}: top-level must be an object"); - var cols = new[] { "id", "name", "tokenHash", "pinHash" }; + var cols = new[] { "id", "name", "tokenHash", "pinHash", "role" }; await using var c = new NpgsqlConnection(connString); await c.OpenAsync(); foreach (var rowNode in root["rows"]!.AsArray()) diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs index 1d5955b386..b8a782435c 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/TphReferenceServer.cs @@ -44,6 +44,12 @@ internal sealed class TphReferenceServer : IAsyncDisposable // rather than rejected (the same treatment autoCreatedAt/autoUpdatedAt get by being // absent here). It IS written on create, explicitly, below. Do NOT add it here. private static readonly string[] AllCols = { "id", "type", "reference", "quantity", "copayAmount", "approver" }; + // The subtype-only columns, by discriminator value. A create stores only its own subtype's + // (1.2.x input contract: a sibling subtype's column in the body is dropped, not stored). + private static readonly Dictionary SubtypeCol = new() + { + ["Bridge"] = "quantity", ["Copay"] = "copayAmount", ["PriorAuth"] = "approver", + }; private readonly PostgresContainer _pg; private readonly WebApplication _app; @@ -340,6 +346,7 @@ private static (List Filters, string? Error, string? Field) ParseFil foreach (var col in AllCols) { if (col is "id" or "type") continue; + if (SubtypeCol.ContainsValue(col) && SubtypeCol[discriminator] != col) continue; if (body[col] is { } v && v.GetValueKind() != JsonValueKind.Null) { cols.Add(col); diff --git a/server/java/codegen-base/pom.xml b/server/java/codegen-base/pom.xml index f0d07409ea..8eb2cdebab 100644 --- a/server/java/codegen-base/pom.xml +++ b/server/java/codegen-base/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-codegen-base diff --git a/server/java/codegen-kotlin-exposed1x-check/pom.xml b/server/java/codegen-kotlin-exposed1x-check/pom.xml index 71efef9577..32c9755f0b 100644 --- a/server/java/codegen-kotlin-exposed1x-check/pom.xml +++ b/server/java/codegen-kotlin-exposed1x-check/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-codegen-kotlin-exposed1x-check diff --git a/server/java/codegen-kotlin/pom.xml b/server/java/codegen-kotlin/pom.xml index 5a5fe50e6a..b7f50c2b59 100644 --- a/server/java/codegen-kotlin/pom.xml +++ b/server/java/codegen-kotlin/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-codegen-kotlin diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt index 62b74b74fc..7c86b95c55 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinGenUtil.kt @@ -655,18 +655,23 @@ public object KotlinGenUtil { /** * True when [field] is SERVER-OWNED on create for [obj]: a component of [obj]'s - * `increment`/`uuid` primary key (the store generates it), or an `@autoSet` column (the - * CRUD path stamps it, issue #203). The caller never supplies either, so a create body - * that omits one is correct — the complement of [isAssignedPrimaryKeyField]. Judged - * against the entity being generated, not `field.parent`: a key idiomatically lives on - * an abstract base and is inherited through `extends`. + * `increment`/`uuid` primary key (the store generates it), an `@autoSet` column (the + * CRUD path stamps it, issue #203), or — on an object with a WRITABLE rest surface — + * a `readOnly` or derived column (the create SECURITY skip never binds it). The caller + * never supplies any of these, so a create body that omits one is correct — the + * complement of [isAssignedPrimaryKeyField]. Judged against the entity being + * generated, not `field.parent`: a key idiomatically lives on an abstract base and is + * inherited through `extends`. A read-only projection keeps its non-null read shape: + * it has no create body to relax for. * * Mirrors the Java port's `SERVER_OWNED_ON_CREATE` set (SpringControllerGenerator). */ fun isServerOwnedOnCreate(field: MetaField<*>, obj: MetaObject): Boolean { val pk = obj.primaryIdentity if (pk != null && pk.isAutoGenerated && pk.fields.contains(field.name)) return true - return autoSetPolicy(field) != null + if (autoSetPolicy(field) != null) return true + if (!com.metaobjects.generator.util.RestSurfaceGate.isWritable(obj)) return false + return isReadOnlyMutability(field) || isDerivedField(field) } /** diff --git a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt index c691f0b6f2..e351ae8ee7 100644 --- a/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt +++ b/server/java/codegen-kotlin/src/main/kotlin/com/metaobjects/generator/kotlin/KotlinSpringControllerGenerator.kt @@ -530,6 +530,10 @@ open class KotlinSpringControllerGenerator : MultiFileDirectGeneratorBase SourceFile.kotlin(path.parent.relativize(path).toString().replace('/', '_'), path.readText()) } + val compileResult = KotlinCompilation().apply { + this.sources = sources + inheritClassPath = true + messageOutputStream = System.out + }.compile() + assertEquals(KotlinCompilation.ExitCode.OK, compileResult.exitCode, + "generated Doc.kt failed to compile:\n${compileResult.messages}") + + val docClass = compileResult.classLoader.loadClass("acme.bind.Doc") + val mapper = ObjectMapper().registerKotlinModule() + val validator = Validation.buildDefaultValidatorFactory().validator + + // Omitted: pre-fix this cannot bind (non-null creator param, no default) → 400. + val omitted = mapper.readValue("""{"title":"t"}""", docClass) + assertTrue(validator.validate(omitted).isEmpty(), "omitted readOnly field must not be demanded") + + // Present: binds (client value never reaches the insert — api-contract scenario) + // and validates; pre-fix the column skip then hit the NOT NULL column → 500. + val present = mapper.readValue("""{"title":"t","role":"evil"}""", docClass) + assertTrue(validator.validate(present).isEmpty(), "present readOnly value must not be rejected") + + // The omitted binding relaxed the property: nullable, defaulted to null. + assertNull(docClass.getMethod("getRole").invoke(omitted)) + } finally { + out.toFile().deleteRecursively() + } + } +} diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt new file mode 100644 index 0000000000..d5b01f2083 --- /dev/null +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinServerOwnedInputTest.kt @@ -0,0 +1,89 @@ +package com.metaobjects.generator.kotlin + +import com.metaobjects.metadata.ktx.loadString +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * A generated create route writes only what a client may set: a server-generated key, a `readOnly` + * column and (TPH) the discriminator and a sibling subtype's column are never bound from the body + * (1.2.x security patch). Behaviour is gated by the api-contract `input-server-owned-dropped` + * scenarios; this pins the generated source, including the TPH subtype `readOnly` case. + */ +class KotlinServerOwnedInputTest { + + private val plain = """{ + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Doc", "children": [ + { "source.rdb": { "@table": "docs" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title", "@maxLength": 100 } }, + { "field.string": { "name": "role", "@maxLength": 20, "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ] } } + ] } + }""".trimIndent() + + private val tph = """{ + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Prior"] } }, + { "field.string": { "name": "reference", "@maxLength": 80 } }, + { "field.string": { "name": "grade", "@maxLength": 20, "@mutability": "readOnly" } }, + { "identity.primary": { "@fields": "id", "@generation": "increment" } } + ] } }, + { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ + { "field.int": { "name": "quantity" } } + ] } }, + { "object.entity": { "name": "PriorAuth", "extends": "Auth", "@discriminatorValue": "Prior", "children": [ + { "field.string": { "name": "approver", "@maxLength": 80 } } + ] } } + ] } + }""".trimIndent() + + private fun gen(name: String, json: String): java.nio.file.Path { + val out = Files.createTempDirectory("kowned-") + val loader = loadString(name, json) + KotlinEntityGenerator().apply { setArgs(mapOf("outputDir" to out.toString())) }.execute(loader) + KotlinSpringControllerGenerator().apply { setArgs(mapOf("outputDir" to out.toString())) }.execute(loader) + return out + } + + @Test + fun `plain create writes neither the generated key nor a readOnly column`() { + val out = gen("owned-plain", plain) + try { + val controller = Files.readString(out.resolve("acme/own/DocController.kt")) + val create = controller.substringAfter("fun create(").substringBefore("fun update(") + assertTrue("it[title] = dto.title" in create, create) + assertFalse("it[role]" in create, create) + assertFalse("it[id] = dto.id" in create, create) + } finally { + out.toFile().deleteRecursively() + } + } + + @Test + fun `TPH create writes only the route subtype's own settable columns`() { + val out = gen("owned-tph", tph) + try { + val controller = Files.readString(out.resolve("acme/own/AuthController.kt")) + val bridge = controller.substringAfter("fun createBridge(").substringBefore("@RequestMapping") + val prior = controller.substringAfter("fun createPrior(").substringBefore("@RequestMapping") + assertTrue("it[reference] = dto.reference" in bridge, bridge) + assertTrue("it[quantity] = dto.quantity" in bridge, bridge) + assertFalse("it[approver]" in bridge, bridge) + assertFalse("it[grade]" in bridge, bridge) + assertFalse("it[type] = dto.type" in bridge, bridge) + assertTrue("it[approver] = dto.approver" in prior, prior) + assertFalse("it[quantity]" in prior, prior) + assertFalse("it[grade]" in prior, prior) + } finally { + out.toFile().deleteRecursively() + } + } +} diff --git a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt index a796931a9a..00257684f0 100644 --- a/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt +++ b/server/java/codegen-kotlin/src/test/resources/snapshots/entity-with-tph/acme/auth/AuthController.kt @@ -425,8 +425,6 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat it[type] = AuthType.Bridge it[reference] = dto.reference!! it[quantity] = dto.quantity - it[copayAmount] = dto.copayAmount - it[priorAuthNumber] = dto.priorAuthNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) @@ -510,9 +508,7 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat val newId = AuthTable.insert { it[type] = AuthType.Copay it[reference] = dto.reference!! - it[quantity] = dto.quantity it[copayAmount] = dto.copayAmount - it[priorAuthNumber] = dto.priorAuthNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() ResponseEntity.status(HttpStatus.CREATED).body(rowToAuth(saved) as Any) @@ -596,8 +592,6 @@ class AuthController(private val objectMapper: ObjectMapper, private val validat val newId = AuthTable.insert { it[type] = AuthType.PriorAuth it[reference] = dto.reference!! - it[quantity] = dto.quantity - it[copayAmount] = dto.copayAmount it[priorAuthNumber] = dto.priorAuthNumber }[AuthTable.id] val saved = AuthTable.selectAll().where { AuthTable.id eq newId }.single() diff --git a/server/java/codegen-mustache/pom.xml b/server/java/codegen-mustache/pom.xml index 81119b2b02..6def4a6c9a 100644 --- a/server/java/codegen-mustache/pom.xml +++ b/server/java/codegen-mustache/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-codegen-mustache diff --git a/server/java/codegen-plantuml/pom.xml b/server/java/codegen-plantuml/pom.xml index 957fa15a4d..2d71c32ee1 100644 --- a/server/java/codegen-plantuml/pom.xml +++ b/server/java/codegen-plantuml/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-codegen-plantuml diff --git a/server/java/codegen-spring/pom.xml b/server/java/codegen-spring/pom.xml index 239418be3f..8a303818cc 100644 --- a/server/java/codegen-spring/pom.xml +++ b/server/java/codegen-spring/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-codegen-spring diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java index dac59eeff3..14c28fe19f 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/SpringControllerGenerator.java @@ -344,7 +344,10 @@ protected void emit(MetaObject entity, Path outRoot) { // #484: a @formExclude / credential value is IGNORED (never rejected): the DTO is rebuilt // without it, so the column is left to the repository's default. List components = SpringGeneratorSupport.dtoComponentFields(entity); - appendStripWriteDenied(src, dtoName, components, SpringGeneratorSupport.writeDeniedNames(components)); + // SECURITY (1.2.x): also dropped, never rejected — a server-generated primary key and a + // readOnly or derived field, none of which a client may set on create. The repository is + // handed only what the client may set. + appendStripWriteDenied(src, dtoName, components, createDeniedNames(entity, components)); // A caller does not supply server-owned columns, so a @NotNull on one must not reject // the request. The DTO is BOTH the request and the response body, so `id` carries // @NotNull because it is @required in the RESPONSE — while being identity.primary @@ -1373,7 +1376,11 @@ protected void emitTph(MetaObject base, TphPlan.Plan plan, Path outRoot) { // OWN @autoSet column is a documented non-goal (uniform with the Kotlin and Python // ports, both base-scoped): the column is simply never stamped, not a compile break. // #484: ignore (never reject) a @formExclude / credential value in the body. - appendStripWriteDenied(src, dtoName, unionFields, writeDenied); + // SECURITY (1.2.x): also dropped — the generated key, readOnly/derived columns, the + // discriminator (the route's subtype is its only source) and every column only a + // SIBLING subtype declares. + appendStripWriteDenied(src, dtoName, unionFields, + tphCreateDeniedNames(st.entity(), unionFields, writeDenied, TphPlan.discriminatorFieldOf(st.entity()))); String createArg = SpringGeneratorSupport.hasAutoSetFields(base) ? dtoName + ".stampForInsert(dto)" : "dto"; src.append(" try {\n"); @@ -1598,11 +1605,13 @@ private static List serverOwnedOnCreate(MetaObject entity) { java.util.Set denied = SpringGeneratorSupport.hierarchyWriteDeniedNames(entity); List out = new ArrayList<>(); - for (MetaField f : SpringGeneratorSupport.scalarFields(entity)) { + // Every DTO component, not only scalars: the create strip (createDeniedNames) nulls a + // readOnly / derived value-object jsonb component too, so its @NotNull must be ignored here. + for (MetaField f : SpringGeneratorSupport.dtoComponentFields(entity)) { // #484: a write-denied field is IGNORED on create, so a @NotNull on it describes the // response shape and must not reject a body that (necessarily) omits it. if (pkFields.contains(f.getName()) || AutoSetSupport.isAutoSet(f) - || denied.contains(f.getName())) { + || denied.contains(f.getName()) || isNonSettableOnCreate(f)) { String component = SpringNaming.recordComponentName(f.getName()); if (!out.contains(component)) out.add(component); } @@ -1649,6 +1658,55 @@ private static List targetCredentials(MetaObject source, SpringM2mSuppor return List.of(); } + /** A field no client may set on create, whatever the entity's key: readOnly or derived. */ + private static boolean isNonSettableOnCreate(MetaField f) { + return MetaField.MUTABILITY_READ_ONLY.equals(f.getMutability()) || f.isDerived(); + } + + /** The field names of {@code entity}'s primary key when the server generates it (increment / uuid). */ + private static Set generatedPkNames(MetaObject entity) { + return entity.getIdentities(true).stream() + .filter(com.metaobjects.identity.MetaIdentity::isPrimary) + .findFirst() + .filter(com.metaobjects.identity.MetaIdentity::isAutoGenerated) + .>map(pk -> new java.util.LinkedHashSet<>(pk.getFields())) + .orElse(Set.of()); + } + + /** + * The components a plain create drops from the bound body before it reaches the repository: + * write-denied ({@code @formExclude} / credential), a server-generated primary key (an assigned + * key is the caller's to choose), and {@code readOnly} and derived fields. + */ + private static Set createDeniedNames(MetaObject entity, List components) { + Set out = new java.util.LinkedHashSet<>(SpringGeneratorSupport.writeDeniedNames(components)); + Set pk = generatedPkNames(entity); + for (MetaField f : components) { + if (pk.contains(f.getName()) || isNonSettableOnCreate(f)) out.add(f.getName()); + } + return out; + } + + /** + * The union-DTO components a TPH per-subtype create drops: the hierarchy's write-denied names, + * the generated key, readOnly and derived columns, the discriminator, and every column the + * route's subtype does not itself have (a sibling subtype's, never this route's to write). + */ + private static Set tphCreateDeniedNames(MetaObject subtype, List union, + Set writeDenied, String discField) { + Set out = new java.util.LinkedHashSet<>(writeDenied); + Set pk = generatedPkNames(subtype); + java.util.Map own = new java.util.HashMap<>(); + for (MetaField f : SpringGeneratorSupport.scalarFields(subtype)) own.put(f.getName(), f); + for (MetaField u : union) { + MetaField f = own.get(u.getName()); + if (f == null || pk.contains(u.getName()) || u.getName().equals(discField) || isNonSettableOnCreate(f)) { + out.add(u.getName()); + } + } + return out; + } + /** The fields of a create body that a generated write route ignores (#484). */ private static void appendStripWriteDenied(StringBuilder src, String dtoName, List components, Set writeDenied) { diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringSecretFieldsCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringSecretFieldsCodegenTest.java index 4856d29870..0e49a1e098 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringSecretFieldsCodegenTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringSecretFieldsCodegenTest.java @@ -63,7 +63,7 @@ private static void run(com.metaobjects.generator.direct.MultiFileDirectGenerato public void createIgnoresBothDeniedFields_andPatchCarriesNeither() throws Exception { String controller = generate("marked", MARKED, "AccountController.java", true); assertTrue("create rebuilds the DTO without tokenHash and pinHash; saw:\n" + controller, - controller.contains("dto = new AccountDto(dto.id(), dto.name(), null, null);")); + controller.contains("dto = new AccountDto(null, dto.name(), null, null);")); Path gen = tmp.getRoot().toPath().resolve("gen-marked"); String patch = Files.readString(gen.resolve("acme/secrets/AccountPatch.java")); @@ -89,7 +89,8 @@ public void onlyTheCredentialIsHiddenOnRead() throws Exception { public void unmarkedModelEmitsNoRedactionAndNoStrip() throws Exception { String controller = generate("plain", PLAIN, "AccountController.java", false); assertFalse(controller.contains("redact")); - assertFalse(controller.contains("dto = new AccountDto(")); + // only the generated key is dropped: nothing here is a credential or @formExclude + assertTrue(controller.contains("dto = new AccountDto(null, dto.name(), dto.tokenHash(), dto.pinHash());")); } /** @@ -123,7 +124,7 @@ public void tphSharedColumnMarkedOnALaterSubtypeIsHiddenAndIgnored() throws Exce assertTrue("the union list hides the credential; saw:\n" + controller, controller.contains("redactAll(rows, \"token\")")); assertTrue("every subtype create ignores both marked columns; saw:\n" + controller, - controller.contains("dto = new ThingDto(dto.id(), dto.kind(), null, null);")); + controller.contains("dto = new ThingDto(null, null, null, null);")); assertFalse("memo (@formExclude only) is still returned", controller.contains("\"memo\")")); } diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java new file mode 100644 index 0000000000..781a28767f --- /dev/null +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringServerOwnedInputCodegenTest.java @@ -0,0 +1,133 @@ +package com.metaobjects.generator.spring; + +import com.metaobjects.loader.MetaDataLoader; +import com.metaobjects.registry.SharedRegistryTestBase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * A generated create route hands the repository only what a client may set: a server-generated + * key, a {@code readOnly} field and (TPH) the discriminator and a sibling subtype's column are + * dropped from the bound body before the repository sees it (1.2.x security patch). Behaviour is + * gated by the api-contract {@code input-server-owned-dropped} scenarios; this pins the generated + * source, including the TPH subtype {@code readOnly} case the shared TPH model does not declare. + */ +public class SpringServerOwnedInputCodegenTest extends SharedRegistryTestBase { + + @Rule + public TemporaryFolder tmp = new TemporaryFolder(); + + private static final String PLAIN = """ + { + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Doc", "children": [ + { "source.rdb": { "@table": "docs" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "title" } }, + { "field.string": { "name": "role", "@mutability": "readOnly" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } }, + { "object.entity": { "name": "Tag", "children": [ + { "source.rdb": { "@table": "tags" } }, + { "field.string": { "name": "code" } }, + { "field.string": { "name": "label" } }, + { "identity.primary": { "name": "pk", "@fields": ["code"] } } + ] } } + ] } + } + """; + + private static final String TPH = """ + { + "metadata.root": { "package": "acme::own", "children": [ + { "object.entity": { "name": "Auth", "@discriminator": "type", "children": [ + { "source.rdb": { "@table": "auths" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bridge", "Prior"] } }, + { "field.string": { "name": "reference" } }, + { "field.string": { "name": "grade", "@mutability": "readOnly" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } }, + { "object.entity": { "name": "BridgeAuth", "extends": "Auth", "@discriminatorValue": "Bridge", "children": [ + { "field.int": { "name": "quantity" } } + ] } }, + { "object.entity": { "name": "PriorAuth", "extends": "Auth", "@discriminatorValue": "Prior", "children": [ + { "field.string": { "name": "approver" } } + ] } } + ] } + } + """; + + private static final String VO = """ + { + "metadata.root": { "package": "acme::own", "children": [ + { "object.value": { "name": "Stamp", "children": [ + { "field.string": { "name": "by" } } + ] } }, + { "object.entity": { "name": "Note", "children": [ + { "source.rdb": { "@table": "notes" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "body" } }, + { "field.object": { "name": "stamp", "@objectRef": "Stamp", "@storage": "jsonb", + "@required": true, "@mutability": "readOnly" } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] } } + ] } + } + """; + + private Path generate(String name, String fixture) throws Exception { + Path gen = tmp.newFolder("gen-" + name).toPath(); + MetaDataLoader loader = SpringTestFixtures.loadFixture(tmp.newFolder("ws-" + name).toPath(), name, fixture); + for (var g : new com.metaobjects.generator.direct.MultiFileDirectGeneratorBase[] { + new SpringControllerGenerator(), new SpringDtoGenerator() }) { + Map args = new HashMap<>(); + args.put("outputDir", gen.toString()); + g.setArgs(args); + g.execute(loader); + } + return gen; + } + + @Test + public void plainCreateDropsTheGeneratedKeyAndReadOnlyField() throws Exception { + Path gen = generate("plain", PLAIN); + String controller = Files.readString(gen.resolve("acme/own/DocController.java")); + assertTrue("generated id and readOnly role are nulled; saw:\n" + controller, + controller.contains("dto = new DocDto(null, dto.title(), null);")); + // an assigned key (no @generation) is the caller's on create + String tag = Files.readString(gen.resolve("acme/own/TagController.java")); + assertFalse("assigned key must be kept; saw:\n" + tag, tag.contains("dto = new TagDto(")); + } + + @Test + public void aRequiredReadOnlyValueObjectIsNulledAndItsNotNullIgnored() throws Exception { + Path gen = generate("vo", VO); + String controller = Files.readString(gen.resolve("acme/own/NoteController.java")); + assertTrue("readOnly VO component is nulled on create; saw:\n" + controller, + controller.contains("dto = new NoteDto(null, dto.body(), null);")); + // the strip nulls `stamp`, so its @NotNull must not turn every POST into a 400 + assertTrue("stamp must be server-owned for create validation; saw:\n" + controller, + controller.matches("(?s).*SERVER_OWNED_ON_CREATE = Set\\.of\\([^)]*\"stamp\".*")); + } + + @Test + public void tphCreateDropsKeyDiscriminatorReadOnlyAndSiblingColumns() throws Exception { + Path gen = generate("tph", TPH); + String controller = Files.readString(gen.resolve("acme/own/AuthController.java")); + // union components: id, type, reference, grade, quantity, approver + assertTrue("Bridge route keeps reference and quantity only; saw:\n" + controller, + controller.contains("dto = new AuthDto(null, null, dto.reference(), null, dto.quantity(), null);")); + assertTrue("Prior route keeps reference and approver only; saw:\n" + controller, + controller.contains("dto = new AuthDto(null, null, dto.reference(), null, null, dto.approver());")); + } +} diff --git a/server/java/core-spring/pom.xml b/server/java/core-spring/pom.xml index 3dd35699a5..8799bf12f0 100644 --- a/server/java/core-spring/pom.xml +++ b/server/java/core-spring/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-core-spring diff --git a/server/java/integration-tests-kotlin/pom.xml b/server/java/integration-tests-kotlin/pom.xml index ba173e5891..cc386d3413 100644 --- a/server/java/integration-tests-kotlin/pom.xml +++ b/server/java/integration-tests-kotlin/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-integration-tests-kotlin diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/ApiContractAssertions.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/ApiContractAssertions.kt index 193959935d..499d718cff 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/ApiContractAssertions.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/ApiContractAssertions.kt @@ -4,7 +4,7 @@ import com.metaobjects.integration.kotlin.api.ApiContractScenarios.ApiRequest /** * Assertion engine for api-contract-conformance scenarios. The vocabulary - * (`equals` / `length` / `ids` / `names` / `row` / `hasId` / `envelope` / + * (`equals` / `length` / `ids` / `names` / `row` / `unset` / `hasId` / `envelope` / * `error` / `empty` / `fieldsEqual` / `fieldsNotEqual`) is the cross-port * contract — every per-port runner must implement these keys identically. * See `fixtures/api-contract-conformance/README.md`. @@ -152,6 +152,15 @@ object ApiContractAssertions { throw AssertionError("$scenarioName / ${request.id}: expected row.$k=$v, got $actual") } } + // Each listed key is missing or null: a value the client may not set never reached storage. + // (Missing-or-null, not strictly missing: ports differ on echoing an unset column as null.) + (want["unset"] as? List<*>)?.let { keys -> + val row = body as? Map<*, *> + ?: throw AssertionError("$scenarioName / ${request.id}: expected object for unset, got: $body") + val stored = keys.filter { row[it] != null } + if (stored.isNotEmpty()) + throw AssertionError("$scenarioName / ${request.id}: expected $stored unset, got: $body") + } if (want["hasId"] == true) { val row = body as? Map<*, *> ?: throw AssertionError("$scenarioName / ${request.id}: expected object, got: $body") diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/GeneratedAuthorControllerHarness.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/GeneratedAuthorControllerHarness.kt index e4d3886a42..60e0b787bf 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/GeneratedAuthorControllerHarness.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/generated/GeneratedAuthorControllerHarness.kt @@ -85,6 +85,9 @@ class GeneratedAuthorControllerHarness( */ private val mapper: ObjectMapper = ObjectMapper() .registerKotlinModule() + // Spring Boot's default: an undeclared request key is ignored, not a 400. The generated + // controller leaves this to the host's mapper; the corpus pins the Boot behaviour. + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(JavaTimeModule()) .registerModule( SimpleModule().addDeserializer(Instant::class.java, object : JsonDeserializer() { diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt index a0492ebdd7..1904580b41 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/secretfields/generated/GeneratedSecretFieldsControllerHarness.kt @@ -38,6 +38,9 @@ class GeneratedSecretFieldsControllerHarness( private val mapper: ObjectMapper = ObjectMapper() .registerKotlinModule() + // Spring Boot's default: an undeclared request key is ignored, not a 400. The generated + // controller leaves this to the host's mapper; the corpus pins the Boot behaviour. + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) @@ -112,7 +115,7 @@ class GeneratedSecretFieldsControllerHarness( // Ids are assigned by the identity column in seed order (1, 2), so a later POST does not collide. // Mixed-case columns are quoted (naming.columns: literal), as in the write-through harness. for (r in rows) { - exec("INSERT INTO accounts (\"name\", \"tokenHash\", \"pinHash\") VALUES (${sqlStr(r["name"])}, ${sqlStr(r["tokenHash"])}, ${sqlStr(r["pinHash"])})") + exec("INSERT INTO accounts (\"name\", \"tokenHash\", \"pinHash\", \"role\") VALUES (${sqlStr(r["name"])}, ${sqlStr(r["tokenHash"])}, ${sqlStr(r["pinHash"])}, ${sqlStr(r["role"])})") } } @@ -128,9 +131,9 @@ class GeneratedSecretFieldsControllerHarness( val database = db ?: error("reset() must be called before storedRows()") return transaction(database) { val out = mutableListOf>() - exec("SELECT id, \"tokenHash\", \"pinHash\" FROM accounts ORDER BY id") { rs -> + exec("SELECT id, \"tokenHash\", \"pinHash\", \"role\" FROM accounts ORDER BY id") { rs -> while (rs.next()) { - out += mapOf("id" to rs.getLong(1), "tokenHash" to rs.getString(2), "pinHash" to rs.getString(3)) + out += mapOf("id" to rs.getLong(1), "tokenHash" to rs.getString(2), "pinHash" to rs.getString(3), "role" to rs.getString(4)) } } out diff --git a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt index df760476b7..583e827ff5 100644 --- a/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt +++ b/server/java/integration-tests-kotlin/src/test/kotlin/com/metaobjects/integration/kotlin/api/tph/generated/GeneratedTphControllerHarness.kt @@ -56,6 +56,9 @@ class GeneratedTphControllerHarness( private val mapper: ObjectMapper = ObjectMapper() .registerKotlinModule() + // Spring Boot's default: an undeclared request key is ignored, not a 400. The generated + // controller leaves this to the host's mapper; the corpus pins the Boot behaviour. + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .registerModule(JavaTimeModule()) .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) diff --git a/server/java/integration-tests/pom.xml b/server/java/integration-tests/pom.xml index d3f49841ae..314dc75ed1 100644 --- a/server/java/integration-tests/pom.xml +++ b/server/java/integration-tests/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-integration-tests diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/ApiContractAssertions.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/ApiContractAssertions.java index b7ddbff70d..969f0e0ae6 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/ApiContractAssertions.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/ApiContractAssertions.java @@ -8,7 +8,7 @@ /** * Assertion engine for api-contract-conformance scenarios. The vocabulary * ({@code equals} / {@code length} / {@code ids} / {@code names} / - * {@code row} / {@code hasId} / {@code envelope} / {@code error} / + * {@code row} / {@code unset} / {@code hasId} / {@code envelope} / {@code error} / * {@code empty} / {@code fieldsEqual} / {@code fieldsNotEqual}) is the * cross-port contract — every per-port runner must implement these keys * identically. See {@code fixtures/api-contract-conformance/README.md}. @@ -177,6 +177,17 @@ static void assertResponse(String scenarioName, ApiRequest request, int status, + ": expected row." + e.getKey() + "=" + e.getValue() + ", got " + actual); } } + // Each listed key is missing or null: a value the client may not set never reached storage. + // (Missing-or-null, not strictly missing: ports differ on echoing an unset column as null.) + if (want.get("unset") instanceof List unsetKeys) { + if (!(body instanceof Map row)) + throw new AssertionError(scenarioName + " / " + request.id() + + ": expected object for unset, got: " + body); + List stored = unsetKeys.stream().filter(k -> row.get(k) != null).toList(); + if (!stored.isEmpty()) + throw new AssertionError(scenarioName + " / " + request.id() + + ": expected " + stored + " unset, got: " + body); + } if (Boolean.TRUE.equals(want.get("hasId"))) { if (!(body instanceof Map row)) throw new AssertionError(scenarioName + " / " + request.id() diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java index 36925cef6e..4cea941ec2 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAccountControllerHarness.java @@ -61,7 +61,10 @@ public final class GeneratedAccountControllerHarness implements AutoCloseable { ] } } """; - private final ObjectMapper mapper = new ObjectMapper(); + // Spring Boot's default: an undeclared request key is ignored, not a 400. The generated controller + // leaves this to the host's mapper; the corpus pins the Boot behaviour. + private final ObjectMapper mapper = new ObjectMapper() + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); private final URLClassLoader classLoader; private final Class dtoClass; private final Constructor controllerCtor; diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAuthorControllerHarness.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAuthorControllerHarness.java index f10c443007..3c2e6627bc 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAuthorControllerHarness.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/GeneratedAuthorControllerHarness.java @@ -130,7 +130,10 @@ public Instant deserialize(JsonParser p, DeserializationContext ctx) this.mapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .registerModule(utcInstant) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + // Spring Boot's default: an undeclared request key is ignored, not a 400. The generated + // controller leaves this to the host's mapper; the corpus pins the Boot behaviour. + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Path srcDir = genDir.resolve("src"); Path classesDir = genDir.resolve("classes"); diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAccountRepositorySource.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAccountRepositorySource.java index 773413c696..57dfd7d252 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAccountRepositorySource.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAccountRepositorySource.java @@ -68,7 +68,10 @@ public Optional findById(Long id) { @Override public AccountDto create(AccountDto dto) { - AccountDto saved = new AccountDto(nextId.getAndIncrement(), dto.name(), dto.tokenHash(), dto.pinHash()); + // Naive adopter repository: trusts the id and every column it is handed, so a forwarded + // client id or readOnly `role` would be stored and visible to the scenarios. + Long id = dto.id() != null ? dto.id() : Long.valueOf(nextId.getAndIncrement()); + AccountDto saved = new AccountDto(id, dto.name(), dto.tokenHash(), dto.pinHash(), dto.role()); rows.add(saved); return saved; } @@ -81,7 +84,8 @@ public Optional update(Long id, AccountDto dto) { AccountDto merged = new AccountDto(id, dto.name() != null ? dto.name() : cur.name(), dto.tokenHash() != null ? dto.tokenHash() : cur.tokenHash(), - dto.pinHash() != null ? dto.pinHash() : cur.pinHash()); + dto.pinHash() != null ? dto.pinHash() : cur.pinHash(), + dto.role() != null ? dto.role() : cur.role()); rows.set(i, merged); return Optional.of(merged); } @@ -98,7 +102,8 @@ public Optional patch(Long id, AccountPatch patch) { AccountDto merged = new AccountDto(id, assigned.containsKey("name") ? (String) assigned.get("name") : cur.name(), assigned.containsKey("tokenHash") ? (String) assigned.get("tokenHash") : cur.tokenHash(), - assigned.containsKey("pinHash") ? (String) assigned.get("pinHash") : cur.pinHash()); + assigned.containsKey("pinHash") ? (String) assigned.get("pinHash") : cur.pinHash(), + assigned.containsKey("role") ? (String) assigned.get("role") : cur.role()); rows.set(i, merged); return Optional.of(merged); } diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAuthorRepositorySource.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAuthorRepositorySource.java index 7027381627..a4c01db44c 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAuthorRepositorySource.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/generated/InMemoryAuthorRepositorySource.java @@ -100,7 +100,11 @@ public AuthorDto create(AuthorDto dto) { // Issue #203 / ADR-0045: the generated controller already stamped @autoSet via // AuthorDto.stampForInsert(dto) before calling create — the repo just persists // the incoming (already-stamped) values verbatim. - AuthorDto saved = new AuthorDto(nextId.getAndIncrement(), dto.name(), dto.bio(), + // A naive adopter repository: it trusts the id it is handed and mints one only when + // absent, so a client id the controller forwarded would be stored (and the shared + // input-server-owned-dropped scenario would see it). + Long id = dto.id() != null ? dto.id() : Long.valueOf(nextId.getAndIncrement()); + AuthorDto saved = new AuthorDto(id, dto.name(), dto.bio(), dto.createdAt(), dto.issuedCurrency(), dto.autoCreatedAt(), dto.autoUpdatedAt()); rows.add(saved); return saved; diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java index dbe315f4f9..22ad1739cd 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/GeneratedTphControllerHarness.java @@ -115,7 +115,10 @@ public Instant deserialize(JsonParser p, DeserializationContext ctx) this.mapper = new ObjectMapper() .registerModule(new JavaTimeModule()) .registerModule(utcInstant) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + // Spring Boot's default: an undeclared request key is ignored, not a 400. The generated + // controller leaves this to the host's mapper; the corpus pins the Boot behaviour. + .disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Path srcDir = genDir.resolve("src"); Path classesDir = genDir.resolve("classes"); Files.createDirectories(srcDir); diff --git a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java index 4f540110eb..f8343cbb49 100644 --- a/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java +++ b/server/java/integration-tests/src/test/java/com/metaobjects/integration/api/tph/generated/InMemoryAuthRepositorySource.java @@ -15,8 +15,8 @@ * *

      The base {@code AuthDto} is the UNION of all subtype columns (the TPH-base DTO shape), so a * single record type backs both polymorphic and per-subtype rows. Discriminator scoping is a plain - * {@code type.equals(discriminator)} filter; a create injects the URL-supplied discriminator and - * never reads {@code dto.type()}.

      + * {@code type.equals(discriminator)} filter; a create stores whatever id/discriminator the DTO carries, + * falling back to the URL's discriminator.

      */ final class InMemoryAuthRepositorySource { @@ -100,7 +100,9 @@ public Optional findByIdAndType(Long id, String discriminator) { @Override public AuthDto createWithType(String discriminator, AuthDto dto) { - // Discriminator injected from the URL — dto.type() is intentionally ignored. + // A naive adopter repository: it trusts what it is handed (the id and the DTO's own + // discriminator when present, falling back to the URL's), so a value the controller + // forwarded from the request body is stored and the shared scenarios can see it. // `type` is a value-constrained enum (field.enum discriminator), so coerce the // String URL discriminator into the generated AuthType (its members ARE the // discriminator values). @@ -109,7 +111,8 @@ public AuthDto createWithType(String discriminator, AuthDto dto) { // AuthDto.stampForInsert(dto) before calling createWithType — the repo just // persists the incoming (already-stamped) autoCreatedAt/autoUpdatedAt verbatim. AuthDto saved = new AuthDto( - nextId.getAndIncrement(), AuthDto.AuthType.valueOf(discriminator), dto.reference(), + dto.id() != null ? dto.id() : Long.valueOf(nextId.getAndIncrement()), + dto.type() != null ? dto.type() : AuthDto.AuthType.valueOf(discriminator), dto.reference(), // FR-037 R1: writeOnce IS bound on create — settable exactly once. dto.issuedCurrency(), dto.autoCreatedAt(), dto.autoUpdatedAt(), diff --git a/server/java/maven-plugin/pom.xml b/server/java/maven-plugin/pom.xml index 69c6963f79..56bdbcc152 100644 --- a/server/java/maven-plugin/pom.xml +++ b/server/java/maven-plugin/pom.xml @@ -2,7 +2,7 @@ metaobjects com.metaobjects - 8.2.0 + 8.2.2 4.0.0 diff --git a/server/java/metadata-ktx/pom.xml b/server/java/metadata-ktx/pom.xml index e902e8fc06..7c16b99371 100644 --- a/server/java/metadata-ktx/pom.xml +++ b/server/java/metadata-ktx/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-metadata-ktx diff --git a/server/java/metadata/pom.xml b/server/java/metadata/pom.xml index d0290e656b..c2716046fd 100644 --- a/server/java/metadata/pom.xml +++ b/server/java/metadata/pom.xml @@ -4,7 +4,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-metadata diff --git a/server/java/om/pom.xml b/server/java/om/pom.xml index e03690a86d..c33e76ccc6 100644 --- a/server/java/om/pom.xml +++ b/server/java/om/pom.xml @@ -5,7 +5,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-om diff --git a/server/java/omdb-ktx/pom.xml b/server/java/omdb-ktx/pom.xml index d5261ce1bd..07d9832f74 100644 --- a/server/java/omdb-ktx/pom.xml +++ b/server/java/omdb-ktx/pom.xml @@ -7,7 +7,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-omdb-ktx diff --git a/server/java/omdb/pom.xml b/server/java/omdb/pom.xml index ae699c85ce..4744ad6944 100644 --- a/server/java/omdb/pom.xml +++ b/server/java/omdb/pom.xml @@ -4,7 +4,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-omdb diff --git a/server/java/pom.xml b/server/java/pom.xml index b3f5c3595c..29ddd9fd55 100644 --- a/server/java/pom.xml +++ b/server/java/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.metaobjects metaobjects - 8.2.0 + 8.2.2 pom MetaObjects Core Universal metadata-driven development platform diff --git a/server/java/render/pom.xml b/server/java/render/pom.xml index 26f3dc66ab..a62d2e77cc 100644 --- a/server/java/render/pom.xml +++ b/server/java/render/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-render diff --git a/server/java/spring-boot-starter/pom.xml b/server/java/spring-boot-starter/pom.xml index c131688526..62abe5f9ee 100644 --- a/server/java/spring-boot-starter/pom.xml +++ b/server/java/spring-boot-starter/pom.xml @@ -6,7 +6,7 @@ com.metaobjects metaobjects - 8.2.0 + 8.2.2 metaobjects-spring-boot-starter diff --git a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md index 1b300bfa6f..a8c8385253 100644 --- a/server/python/src/metaobjects/codegen/KNOWN_GAPS.md +++ b/server/python/src/metaobjects/codegen/KNOWN_GAPS.md @@ -54,6 +54,18 @@ import wiring itself (`from ._entity import `), which still needs path-resolution/import-base machinery; the config's per-target `outDir` is the prerequisite that is now in place. +## TPH body discriminator: 400, not a silent drop + +**Status:** known divergence, out of scope for the 1.2.x input patch. + +A per-subtype write route (`POST /api/auths/bridge`) validates the request body with +that subtype's model, whose discriminator accepts only the route's own value. A body +that names another subtype (`"type": "Copay"`) is answered `400 {"error":"validation"}`. +Nothing is stored, so this is not a security hole, but the other ports drop the key +and create the row with the route's subtype. The shared +`tph-input-foreign-discriminator-dropped` scenario asserts the drop, and this port's +runner skips it with this reason (`tests/integration/test_api_contract_tph_generated.py`). + ## FR-015 stored-procedure callables are NOT generated by this port **Contract.** FR-015 gives a `source.rdb @kind: storedProc` / `tableFunction` a generated diff --git a/server/python/tests/integration/api_contract_assertions.py b/server/python/tests/integration/api_contract_assertions.py index 11a6f33445..fac4b8ccce 100644 --- a/server/python/tests/integration/api_contract_assertions.py +++ b/server/python/tests/integration/api_contract_assertions.py @@ -1,7 +1,7 @@ """Assertion engine for api-contract-conformance scenarios. The vocabulary (``equals`` / ``length`` / ``ids`` / ``names`` / ``row`` / -``hasId`` / ``envelope`` / ``error`` / ``field`` / ``empty``) is the cross-port contract — +``unset`` / ``hasId`` / ``envelope`` / ``error`` / ``field`` / ``empty``) is the cross-port contract — every per-port runner must implement these keys identically. See ``fixtures/api-contract-conformance/README.md``. @@ -202,6 +202,19 @@ def assert_response( f"but both = {a_value!r}" ) + if "unset" in expect_body: + # Each listed key is missing or null: a value the client may not set never reached + # storage. (Missing-or-null: ports differ on echoing an unset column as null.) + if not isinstance(body, dict): + raise AssertionError( + f"{scenario_name} / {request_id}: expected object for unset, got: {body!r}" + ) + stored = [k for k in expect_body["unset"] if body.get(k) is not None] + if stored: + raise AssertionError( + f"{scenario_name} / {request_id}: expected {stored!r} unset, got: {body!r}" + ) + if expect_body.get("hasId") is True: if not isinstance(body, dict): raise AssertionError( diff --git a/server/python/tests/integration/generated_secret_fields_app.py b/server/python/tests/integration/generated_secret_fields_app.py index 61d9eb9a4e..3a6a1f2f1c 100644 --- a/server/python/tests/integration/generated_secret_fields_app.py +++ b/server/python/tests/integration/generated_secret_fields_app.py @@ -28,7 +28,7 @@ from .corpus_config import attach_corpus_wire from .generated_router_app import InMemoryAuthorRepository -COLUMNS = ("id", "name", "tokenHash", "pinHash") +COLUMNS = ("id", "name", "tokenHash", "pinHash", "role") def load_account(meta_json: Path) -> MetaObject: diff --git a/server/python/tests/integration/test_api_contract_tph_generated.py b/server/python/tests/integration/test_api_contract_tph_generated.py index 7305eb6b78..b84fb01b84 100644 --- a/server/python/tests/integration/test_api_contract_tph_generated.py +++ b/server/python/tests/integration/test_api_contract_tph_generated.py @@ -55,6 +55,16 @@ def _load_scenarios() -> list[tuple[str, dict[str, Any]]]: _SCENARIOS = _load_scenarios() + +# Scenarios this port's generated routes answer differently, each with its reason. The routes +# validate the body's discriminator against the route's subtype and answer 400 rather than +# dropping it; nothing is stored either way. See codegen/KNOWN_GAPS.md. +_PORT_SKIPS: dict[str, str] = { + "tph-input-foreign-discriminator-dropped": ( + "a body discriminator naming another subtype is a 400 here, not a silent drop " + "(KNOWN_GAPS.md: TPH body discriminator)" + ), +} _APP, _REPO = build_generated_tph_app(_TPH_DIR) _CLIENT = TestClient(_APP) @@ -65,6 +75,8 @@ def _load_scenarios() -> list[tuple[str, dict[str, Any]]]: ids=[name for name, _ in _SCENARIOS], ) def test_api_contract_tph_generated_scenario(scenario_name: str, scenario: dict[str, Any]) -> None: + if scenario_name in _PORT_SKIPS: + pytest.skip(_PORT_SKIPS[scenario_name]) _REPO.reset() _REPO.seed(_SEED["auths"]) for req in scenario.get("requests", []): diff --git a/server/typescript/packages/ai-runtime/package.json b/server/typescript/packages/ai-runtime/package.json index 9ff757cf29..69fc612d73 100644 --- a/server/typescript/packages/ai-runtime/package.json +++ b/server/typescript/packages/ai-runtime/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/ai-runtime", - "version": "1.2.0", + "version": "1.2.2", "description": "LLM call loop + typed-trace recorder adapters for MetaObjects: provider-neutral LlmClient seam, callLlm bridge, Composite/Langfuse/OTel recorders.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/cli/package.json b/server/typescript/packages/cli/package.json index b1f41e6d4e..f1e3c07511 100644 --- a/server/typescript/packages/cli/package.json +++ b/server/typescript/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/cli", - "version": "1.2.0", + "version": "1.2.2", "description": "CLI for MetaObjects: scaffold, codegen, migrate, and drift-detection commands.", "type": "module", "main": "./dist/src/index.js", diff --git a/server/typescript/packages/codegen-ts-react/package.json b/server/typescript/packages/codegen-ts-react/package.json index 00d66c8985..343bdd944d 100644 --- a/server/typescript/packages/codegen-ts-react/package.json +++ b/server/typescript/packages/codegen-ts-react/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/codegen-ts-react", - "version": "1.2.0", + "version": "1.2.2", "description": "React codegen for metaobjects — emits .form.tsx files using react-hook-form and @metaobjectsdev/react helpers.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/codegen-ts-tanstack/package.json b/server/typescript/packages/codegen-ts-tanstack/package.json index 6ae9c41926..07dd6d0ca9 100644 --- a/server/typescript/packages/codegen-ts-tanstack/package.json +++ b/server/typescript/packages/codegen-ts-tanstack/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/codegen-ts-tanstack", - "version": "1.2.0", + "version": "1.2.2", "description": "TanStack codegen for metaobjects — TanStack Query hooks for every entity, plus TanStack Table column definitions and grid-state hooks for entities declaring a layout.dataGrid.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/codegen-ts/package.json b/server/typescript/packages/codegen-ts/package.json index cb52ec1a11..0785f3400e 100644 --- a/server/typescript/packages/codegen-ts/package.json +++ b/server/typescript/packages/codegen-ts/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/codegen-ts", - "version": "1.2.0", + "version": "1.2.2", "description": "TypeScript codegen engine for MetaObjects — emits Drizzle, Zod, and Fastify artifacts.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts index e6a526d36d..e21443f213 100644 --- a/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts +++ b/server/typescript/packages/codegen-ts/src/templates/zod-validators.ts @@ -386,6 +386,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); @@ -393,6 +394,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { */ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { const autoGenPkFields = autoGenPkFieldNames(obj); + const pkFields = primaryKeyFieldNames(obj); const tphPin = tphDiscriminatorPin(obj); const out: SchemaFieldShape[] = []; for (const child of obj.fields()) { @@ -408,6 +410,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { // edit form for an entity carrying one. Clearing counts as a write, so the // FR-035 present-null arm never reaches it either. if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): a primary-key field is the row's identity, which the URL names. An + // ASSIGNED key leaves the update shape exactly like a generated one, so a client-sent + // key is stripped and can never re-key the row. + if (pkFields.has(child.name)) continue; // TPH subtype discriminator: omitted from the update schema entirely. if (tphPin !== undefined && child.name === tphPin.fieldName) continue; const autoSet = child.attr(FIELD_ATTR_AUTO_SET); @@ -491,6 +497,10 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // below; a value presented on PATCH is stripped, not 400'd (see // updateSchemaFields for the grounding). if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): the row's identity is the URL's. An ASSIGNED primary key leaves the + // update shape too (a generated one never entered it), so a client-sent key is stripped + // on PUT/PATCH and can never re-key the row. Mirrors updateSchemaFields. + if (pkFields.has(child.name)) continue; // Update schema: @autoSet onCreate → omit entirely; onUpdate → transform if (autoSet === AUTO_SET_ON_CREATE) { @@ -515,10 +525,8 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // null — a present null CLEARS the column (`.set({field: null})` writes NULL). // Keyed on required-ness, NOT fieldWillBeOptional: a required-with-@default // field stays non-nullable so an explicit null on it is a 400 (validation), - // never a silent clear. PK fields are excluded: their Drizzle column is - // always not-null, so a nullable Zod type would fail `.set()`'s typecheck - // (and NOT NULL at runtime) — see primaryKeyFieldNames. - if (!isRequired(child) && !pkFields.has(child.name)) expr = code`${expr}.nullable()`; + // never a silent clear. PK fields never reach this branch (skipped above). + if (!isRequired(child)) expr = code`${expr}.nullable()`; updateFieldLines.push(code` ${child.name}: ${expr}`); } } diff --git a/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap b/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap index d5a0163053..cc8e306f31 100644 --- a/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap +++ b/server/typescript/packages/codegen-ts/test/__snapshots__/reporting-docs.test.ts.snap @@ -204,36 +204,36 @@ Generated API reference for this project; call these exactly as written. Imports \`import { Program, ProgramInsertSchema, ProgramUpdateSchema } from "./Program"\` - \`interface Program { id: number; title?: string; createdAt?: string }\` — The typed shape of a Program row, generated from its metadata. - \`ProgramInsertSchema: ZodType<{ id: number; title?: string; createdAt?: string }>\` — Zod schema validating the body of a create / POST request (auto-generated PKs excluded). -- \`ProgramUpdateSchema: ZodType<{ id?: number; title?: string; createdAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional). +- \`ProgramUpdateSchema: ZodType<{ title?: string; createdAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional). \`import { findProgramById, listPrograms, createProgram, updateProgram, deleteProgramById } from "./Program.queries"\` - \`findProgramById(db: Db, id: number): Promise\` — Fetch a single Program by its primary key; null when not found. - \`listPrograms(db: Db, opts?: { limit?: number; offset?: number }): Promise\` — List Program rows with optional limit/offset paging. - \`createProgram(db: Db, data: { id: number; title?: string; createdAt?: string }): Promise\` — Validate (via ProgramInsertSchema) and insert a new Program. [throws: ZodError when data fails ProgramInsertSchema validation.] -- \`updateProgram(db: Db, id: number, patch: { id?: number; title?: string; createdAt?: string }): Promise\` — Partially update a Program by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails ProgramUpdateSchema validation.] +- \`updateProgram(db: Db, id: number, patch: { title?: string; createdAt?: string }): Promise\` — Partially update a Program by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails ProgramUpdateSchema validation.] - \`deleteProgramById(db: Db, id: number): Promise\` — Delete a Program by primary key; true when a row was removed. \`import { programRoutes } from "./Program.routes"\` - \`GET /api/programs -> { id: number; title?: string; createdAt?: string }\` — List Program (supports filter/sort/paging query params). - \`GET /api/programs/:id -> { id: number; title?: string; createdAt?: string }\` — Fetch a single Program by id (404 when not found). - \`POST /api/programs body: { id: number; title?: string; createdAt?: string }\` — Create a Program (body validated by ProgramInsertSchema). -- \`PATCH /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — Partially update a Program by id (body validated by ProgramUpdateSchema). -- \`PUT /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema). +- \`PATCH /api/programs/:id body: { title?: string; createdAt?: string }\` — Partially update a Program by id (body validated by ProgramUpdateSchema). +- \`PUT /api/programs/:id body: { title?: string; createdAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema). - \`DELETE /api/programs/:id\` — Delete a Program by id. \`import { registerProgramRoutes } from "./Program.routes.hono"\` - \`GET /api/programs -> { id: number; title?: string; createdAt?: string }\` — [Hono] List Program (filter/sort/paging query params). - \`GET /api/programs/:id -> { id: number; title?: string; createdAt?: string }\` — [Hono] Fetch a single Program by id (404 when not found). - \`POST /api/programs body: { id: number; title?: string; createdAt?: string }\` — [Hono] Create a Program (body validated by ProgramInsertSchema). -- \`PATCH /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — [Hono] Partially update a Program by id (body validated by ProgramUpdateSchema). -- \`PUT /api/programs/:id body: { id?: number; title?: string; createdAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema). +- \`PATCH /api/programs/:id body: { title?: string; createdAt?: string }\` — [Hono] Partially update a Program by id (body validated by ProgramUpdateSchema). +- \`PUT /api/programs/:id body: { title?: string; createdAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by ProgramUpdateSchema). - \`DELETE /api/programs/:id\` — [Hono] Delete a Program by id. Example: \`\`\`ts const created = await createProgram(db, { id: 1 }); const found = await findProgramById(db, created.id); -const updated = await updateProgram(db, created.id, { id: 1 }); +const updated = await updateProgram(db, created.id, { title: "…" }); const removed = await deleteProgramById(db, created.id); \`\`\` @@ -242,37 +242,37 @@ const removed = await deleteProgramById(db, created.id); \`import { Purchase, PurchaseInsertSchema, PurchaseUpdateSchema, purchasesRelations } from "./Purchase"\` - \`interface Purchase { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — The typed shape of a Purchase row, generated from its metadata. - \`PurchaseInsertSchema: ZodType<{ id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }>\` — Zod schema validating the body of a create / POST request (auto-generated PKs excluded). -- \`PurchaseUpdateSchema: ZodType<{ id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional). +- \`PurchaseUpdateSchema: ZodType<{ programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional). - \`const purchasesRelations { program?: Program (1:1 / N:1) }\` — Drizzle relations() for Purchase — register it with your schema, then traverse via the relational query API (db.query.purchases.findMany({ with: { … } })). \`import { findPurchaseById, listPurchases, createPurchase, updatePurchase, deletePurchaseById } from "./Purchase.queries"\` - \`findPurchaseById(db: Db, id: number): Promise\` — Fetch a single Purchase by its primary key; null when not found. - \`listPurchases(db: Db, opts?: { limit?: number; offset?: number }): Promise\` — List Purchase rows with optional limit/offset paging. - \`createPurchase(db: Db, data: { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }): Promise\` — Validate (via PurchaseInsertSchema) and insert a new Purchase. [throws: ZodError when data fails PurchaseInsertSchema validation.] -- \`updatePurchase(db: Db, id: number, patch: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }): Promise\` — Partially update a Purchase by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails PurchaseUpdateSchema validation.] +- \`updatePurchase(db: Db, id: number, patch: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }): Promise\` — Partially update a Purchase by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails PurchaseUpdateSchema validation.] - \`deletePurchaseById(db: Db, id: number): Promise\` — Delete a Purchase by primary key; true when a row was removed. \`import { purchaseRoutes } from "./Purchase.routes"\` - \`GET /api/purchases -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — List Purchase (supports filter/sort/paging query params). - \`GET /api/purchases/:id -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Fetch a single Purchase by id (404 when not found). - \`POST /api/purchases body: { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Create a Purchase (body validated by PurchaseInsertSchema). -- \`PATCH /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Partially update a Purchase by id (body validated by PurchaseUpdateSchema). -- \`PUT /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema). +- \`PATCH /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — Partially update a Purchase by id (body validated by PurchaseUpdateSchema). +- \`PUT /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema). - \`DELETE /api/purchases/:id\` — Delete a Purchase by id. \`import { registerPurchaseRoutes } from "./Purchase.routes.hono"\` - \`GET /api/purchases -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] List Purchase (filter/sort/paging query params). - \`GET /api/purchases/:id -> { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Fetch a single Purchase by id (404 when not found). - \`POST /api/purchases body: { id: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Create a Purchase (body validated by PurchaseInsertSchema). -- \`PATCH /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Partially update a Purchase by id (body validated by PurchaseUpdateSchema). -- \`PUT /api/purchases/:id body: { id?: number; programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema). +- \`PATCH /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] Partially update a Purchase by id (body validated by PurchaseUpdateSchema). +- \`PUT /api/purchases/:id body: { programId?: number; customerEmail?: string; amountCents?: number; status?: string; refunded?: boolean; purchasedAt?: string; purchasedOn?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by PurchaseUpdateSchema). - \`DELETE /api/purchases/:id\` — [Hono] Delete a Purchase by id. Example: \`\`\`ts const created = await createPurchase(db, { id: 1 }); const found = await findPurchaseById(db, created.id); -const updated = await updatePurchase(db, created.id, { id: 1 }); +const updated = await updatePurchase(db, created.id, { programId: 1 }); const removed = await deletePurchaseById(db, created.id); \`\`\` @@ -281,36 +281,36 @@ const removed = await deletePurchaseById(db, created.id); \`import { WorkoutEvent, WorkoutEventInsertSchema, WorkoutEventUpdateSchema } from "./WorkoutEvent"\` - \`interface WorkoutEvent { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — The typed shape of a WorkoutEvent row, generated from its metadata. - \`WorkoutEventInsertSchema: ZodType<{ id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }>\` — Zod schema validating the body of a create / POST request (auto-generated PKs excluded). -- \`WorkoutEventUpdateSchema: ZodType<{ id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional). +- \`WorkoutEventUpdateSchema: ZodType<{ programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }>\` — Zod schema validating the body of an update / PATCH request (all fields optional). \`import { findWorkoutEventById, listWorkoutEvents, createWorkoutEvent, updateWorkoutEvent, deleteWorkoutEventById } from "./WorkoutEvent.queries"\` - \`findWorkoutEventById(db: Db, id: number): Promise\` — Fetch a single WorkoutEvent by its primary key; null when not found. - \`listWorkoutEvents(db: Db, opts?: { limit?: number; offset?: number }): Promise\` — List WorkoutEvent rows with optional limit/offset paging. - \`createWorkoutEvent(db: Db, data: { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }): Promise\` — Validate (via WorkoutEventInsertSchema) and insert a new WorkoutEvent. [throws: ZodError when data fails WorkoutEventInsertSchema validation.] -- \`updateWorkoutEvent(db: Db, id: number, patch: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }): Promise\` — Partially update a WorkoutEvent by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails WorkoutEventUpdateSchema validation.] +- \`updateWorkoutEvent(db: Db, id: number, patch: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }): Promise\` — Partially update a WorkoutEvent by primary key — writes only the assigned fields; null when not found. A renamed/dropped field is a compile error. [throws: ZodError when the patch fails WorkoutEventUpdateSchema validation.] - \`deleteWorkoutEventById(db: Db, id: number): Promise\` — Delete a WorkoutEvent by primary key; true when a row was removed. \`import { workoutEventRoutes } from "./WorkoutEvent.routes"\` - \`GET /api/workout_events -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — List WorkoutEvent (supports filter/sort/paging query params). - \`GET /api/workout_events/:id -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Fetch a single WorkoutEvent by id (404 when not found). - \`POST /api/workout_events body: { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Create a WorkoutEvent (body validated by WorkoutEventInsertSchema). -- \`PATCH /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema). -- \`PUT /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema). +- \`PATCH /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema). +- \`PUT /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema). - \`DELETE /api/workout_events/:id\` — Delete a WorkoutEvent by id. \`import { registerWorkoutEventRoutes } from "./WorkoutEvent.routes.hono"\` - \`GET /api/workout_events -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] List WorkoutEvent (filter/sort/paging query params). - \`GET /api/workout_events/:id -> { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Fetch a single WorkoutEvent by id (404 when not found). - \`POST /api/workout_events body: { id: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Create a WorkoutEvent (body validated by WorkoutEventInsertSchema). -- \`PATCH /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema). -- \`PUT /api/workout_events/:id body: { id?: number; programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema). +- \`PATCH /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] Partially update a WorkoutEvent by id (body validated by WorkoutEventUpdateSchema). +- \`PUT /api/workout_events/:id body: { programId?: number; customerEmail?: string; weekNumber?: number; dayNumber?: number; eventType?: string; occurredAt?: string }\` — [Hono] PUT alias of PATCH — the same handler and partial body (validated by WorkoutEventUpdateSchema). - \`DELETE /api/workout_events/:id\` — [Hono] Delete a WorkoutEvent by id. Example: \`\`\`ts const created = await createWorkoutEvent(db, { id: 1 }); const found = await findWorkoutEventById(db, created.id); -const updated = await updateWorkoutEvent(db, created.id, { id: 1 }); +const updated = await updateWorkoutEvent(db, created.id, { programId: 1 }); const removed = await deleteWorkoutEventById(db, created.id); \`\`\` " @@ -343,7 +343,7 @@ import { createProgram, findProgramById, updateProgram, deleteProgramById } from const created = await createProgram(db, { id: 1 }); const found = await findProgramById(db, created.id); -const updated = await updateProgram(db, created.id, { id: 1 }); +const updated = await updateProgram(db, created.id, { title: "…" }); const removed = await deleteProgramById(db, created.id); \`\`\` @@ -413,7 +413,6 @@ Request body (data): | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`title\` | \`string\` | | | | \`createdAt\` | \`string\` | | | @@ -495,7 +494,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`title\` | \`string\` | | | | \`createdAt\` | \`string\` | | | @@ -513,7 +511,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`title\` | \`string\` | | | | \`createdAt\` | \`string\` | | | @@ -597,7 +594,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`title\` | \`string\` | | | | \`createdAt\` | \`string\` | | | @@ -615,7 +611,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`title\` | \`string\` | | | | \`createdAt\` | \`string\` | | | @@ -661,7 +656,6 @@ Accepted fields: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`title\` | \`string\` | | | | \`createdAt\` | \`string\` | | | " @@ -694,7 +688,7 @@ import { createPurchase, findPurchaseById, updatePurchase, deletePurchaseById } const created = await createPurchase(db, { id: 1 }); const found = await findPurchaseById(db, created.id); -const updated = await updatePurchase(db, created.id, { id: 1 }); +const updated = await updatePurchase(db, created.id, { programId: 1 }); const removed = await deletePurchaseById(db, created.id); \`\`\` @@ -790,7 +784,6 @@ Request body (data): | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`amountCents\` | \`number\` | | | @@ -892,7 +885,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`amountCents\` | \`number\` | | | @@ -915,7 +907,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`amountCents\` | \`number\` | | | @@ -1019,7 +1010,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`amountCents\` | \`number\` | | | @@ -1042,7 +1032,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`amountCents\` | \`number\` | | | @@ -1098,7 +1087,6 @@ Accepted fields: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`amountCents\` | \`number\` | | | @@ -1150,7 +1138,7 @@ import { createWorkoutEvent, findWorkoutEventById, updateWorkoutEvent, deleteWor const created = await createWorkoutEvent(db, { id: 1 }); const found = await findWorkoutEventById(db, created.id); -const updated = await updateWorkoutEvent(db, created.id, { id: 1 }); +const updated = await updateWorkoutEvent(db, created.id, { programId: 1 }); const removed = await deleteWorkoutEventById(db, created.id); \`\`\` @@ -1228,7 +1216,6 @@ Request body (data): | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`weekNumber\` | \`number\` | | | @@ -1326,7 +1313,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`weekNumber\` | \`number\` | | | @@ -1348,7 +1334,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`weekNumber\` | \`number\` | | | @@ -1448,7 +1433,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`weekNumber\` | \`number\` | | | @@ -1470,7 +1454,6 @@ Request body: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`weekNumber\` | \`number\` | | | @@ -1524,7 +1507,6 @@ Accepted fields: | Field | Type | Required | Notes | |---|---|---|---| -| \`id\` | \`number\` | | | | \`programId\` | \`number\` | | | | \`customerEmail\` | \`string\` | | | | \`weekNumber\` | \`number\` | | | diff --git a/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts b/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts index 5b237c0213..ed91c3a735 100644 --- a/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts +++ b/server/typescript/packages/codegen-ts/test/templates/zod-validators.test.ts @@ -356,6 +356,22 @@ describe("renderZodValidators", () => { expect(update).toContain("name"); }); + test("SECURITY 1.2.x: an ASSIGNED primary key is in the Insert schema and OUT of the Update schema", () => { + // The URL names the row on PUT/PATCH. An assigned key (no @generation) is the caller's on + // create, but leaving it in the update shape let a client-sent `code` re-key the row. + const coupon = metaObject(OBJECT_SUBTYPE_ENTITY, "Coupon"); + coupon.addChild(metaField(FIELD_SUBTYPE_STRING, "code")); + coupon.addChild(metaField(FIELD_SUBTYPE_STRING, "label")); + const primary = meta(new TypeId(TYPE_IDENTITY, IDENTITY_SUBTYPE_PRIMARY), "primary"); + primary.setAttr("fields", ["code"]); + coupon.addChild(primary); + const out = renderZodValidators(coupon).toString(); + expect(schemaBody(out, "CouponInsertSchema")).toContain("code"); + const update = schemaBody(out, "CouponUpdateSchema"); + expect(update).not.toContain("code"); + expect(update).toContain("label"); + }); + test("FR-037 R1: no @mutability (⇒ readWrite) is in BOTH schemas — the no-churn default", () => { const out = customerWithMutability(undefined, "lifetimeValue"); expect(schemaBody(out, "CustomerInsertSchema")).toContain("lifetimeValue"); diff --git a/server/typescript/packages/docs-site/package.json b/server/typescript/packages/docs-site/package.json index a559b1c5e1..c99675193e 100644 --- a/server/typescript/packages/docs-site/package.json +++ b/server/typescript/packages/docs-site/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/docs-site", - "version": "1.2.0", + "version": "1.2.2", "description": "HTML documentation-site generator for metaobjects models — a browsable multi-page site (nav, search, per-object/package pages, kind-aware ER diagrams). Powers the `docs-site` generator (`docsSiteFile()`).", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/integration-tests/src/api-contract-scenario.ts b/server/typescript/packages/integration-tests/src/api-contract-scenario.ts index 41ea9becb3..ca329a6eb9 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-scenario.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-scenario.ts @@ -26,6 +26,10 @@ export interface ExpectBody { namesUnordered?: string[]; row?: Record; hasId?: boolean; + /** The response body is an object and each listed key is MISSING or `null` on it: a value + * the client was not allowed to set never reached storage, so it never comes back in the + * echo (the 1.2.x input scenarios). */ + unset?: string[]; /** Assert the listed RESPONSE fields all equal EACH OTHER (never a literal) — * format-agnostic. Used by @autoSet scenarios to prove two stamped columns * hold the same value without pinning the exact timestamp. */ @@ -283,6 +287,14 @@ export function assertResponse( if (typeof row["id"] !== "number") throw new Error(`${scenarioName} / ${request.id}: expected numeric id in body, got: ${stringify(body)}`); } + if (want.unset) { + if (body === null || typeof body !== "object" || Array.isArray(body)) + throw new Error(`${scenarioName} / ${request.id}: expected object for unset, got: ${stringify(body)}`); + const row = body as Record; + const stored = want.unset.filter((k) => row[k] !== undefined && row[k] !== null); + if (stored.length > 0) + throw new Error(`${scenarioName} / ${request.id}: expected ${stored.join(", ")} unset, got: ${stringify(body)}`); + } if (want.fieldsEqual) { const row = body as Record; // Compare the raw response fields to EACH OTHER (format-agnostic) — every diff --git a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts index 59885dde10..dbf642ed62 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts @@ -65,7 +65,7 @@ const READ_PATHS = { }; export interface SecretFieldsSeed { - rows: Array<{ id: number; name: string; tokenHash: string; pinHash: string }>; + rows: Array<{ id: number; name: string; tokenHash: string; pinHash: string; role: string }>; } export interface GeneratedSecretFieldsServerHandle { @@ -124,7 +124,8 @@ export const db = drizzle(pool); "id" bigserial PRIMARY KEY, "name" varchar(100) NOT NULL, "token_hash" varchar(100), - "pin_hash" varchar(100) + "pin_hash" varchar(100), + "role" varchar(20) ); CREATE OR REPLACE VIEW "v_account" AS SELECT "id", "name", "pin_hash" FROM "accounts"; CREATE TABLE IF NOT EXISTS "payers" ("id" bigserial PRIMARY KEY); @@ -165,7 +166,7 @@ export const db = drizzle(pool); for (const r of seed.rows) await executeSql( connectionUri, - `INSERT INTO "accounts" ("id","name","token_hash","pin_hash") VALUES (${r.id}, ${str(r.name)}, ${str(r.tokenHash)}, ${str(r.pinHash)})`, + `INSERT INTO "accounts" ("id","name","token_hash","pin_hash","role") VALUES (${r.id}, ${str(r.name)}, ${str(r.tokenHash)}, ${str(r.pinHash)}, ${str(r.role)})`, ); // The seed names ids explicitly; keep the sequence ahead of them for the POST scenarios. await executeSql(connectionUri, `SELECT setval(pg_get_serial_sequence('accounts','id'), (SELECT MAX("id") FROM "accounts"));`); diff --git a/server/typescript/packages/integration-tests/src/api-contract-server.ts b/server/typescript/packages/integration-tests/src/api-contract-server.ts index 32cc2b3661..4342322804 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-server.ts @@ -188,6 +188,16 @@ export async function startServer(connectionUri: string, root: MetaRoot): Promis return reply; }); + // The keys a client may write, as the generated routes' Insert/Update schemas have them: the + // server-generated `id`, the @autoSet columns and any key the entity does not declare are + // DROPPED silently (never 400'd), and `issuedCurrency` (writeOnce) is settable on create only. + const CREATE_KEYS = ["name", "bio", "createdAt", "issuedCurrency"] as const; + const UPDATE_KEYS = ["name", "bio", "createdAt"] as const; + const pick = (body: unknown, keys: readonly string[]): Record => { + const src = (body ?? {}) as Record; + return Object.fromEntries(keys.filter((k) => Object.hasOwn(src, k)).map((k) => [k, src[k]])); + }; + // POST /api/authors fastify.post(ROUTE_BASE, async (req, reply) => { // #203 / ADR-0045 — the TS runtime ObjectManager does NOT stamp @autoSet @@ -195,7 +205,7 @@ export async function startServer(connectionUri: string, root: MetaRoot): Promis // the generated lane's InsertSchema. Both onCreate + onUpdate columns get the // SAME captured now() on create; any caller-supplied value is ignored. const now = new Date().toISOString(); - const body = { ...(req.body as Record), autoCreatedAt: now, autoUpdatedAt: now }; + const body = { ...pick(req.body, CREATE_KEYS), autoCreatedAt: now, autoUpdatedAt: now }; const row = await om.create(ENTITY, body); reply.code(201).send(row); return reply; @@ -215,12 +225,7 @@ export async function startServer(connectionUri: string, root: MetaRoot): Promis // plain z.object() discards unknown keys). Dropping it also covers the // present-NULL arm for free: clearing is a write, so an explicit null must // not reach the column either. - const { - autoCreatedAt: _dropOnCreate, - issuedCurrency: _dropWriteOnce, - ...rest - } = (req.body as Record) ?? {}; - const body = { ...rest, autoUpdatedAt: new Date().toISOString() }; + const body = { ...pick(req.body, UPDATE_KEYS), autoUpdatedAt: new Date().toISOString() }; // A ValidationError (e.g. FR-035 present-null on a @required field) propagates // to the shared setErrorHandler above → 400 {error:"validation"}. const row = await om.update(ENTITY, Number(id), body, { ifMissing: "ignore" }); diff --git a/server/typescript/packages/metadata/package.json b/server/typescript/packages/metadata/package.json index 48a941c10e..b2ecbeddb6 100644 --- a/server/typescript/packages/metadata/package.json +++ b/server/typescript/packages/metadata/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/metadata", - "version": "1.2.0", + "version": "1.2.2", "description": "Metamodel loader, types, and constants for the MetaObjects standard.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/migrate-ts/package.json b/server/typescript/packages/migrate-ts/package.json index caf8274e57..c9340bfc10 100644 --- a/server/typescript/packages/migrate-ts/package.json +++ b/server/typescript/packages/migrate-ts/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/migrate-ts", - "version": "1.2.0", + "version": "1.2.2", "description": "Schema migration tooling for MetaObjects: diff metadata vs DB and emit SQL for Postgres and SQLite.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/render/package.json b/server/typescript/packages/render/package.json index 0fc26e9170..fdc0d33c59 100644 --- a/server/typescript/packages/render/package.json +++ b/server/typescript/packages/render/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/render", - "version": "1.2.0", + "version": "1.2.2", "description": "Deterministic text render engine for MetaObjects templates — Mustache (logic-less, the cross-port default) and Jinja (via nunjucks), provider-resolved partials, format-driven escaping, build-time payload drift check, zero core dependency.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/runtime-ts/package.json b/server/typescript/packages/runtime-ts/package.json index 376c24d585..c82fa8d88d 100644 --- a/server/typescript/packages/runtime-ts/package.json +++ b/server/typescript/packages/runtime-ts/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/runtime-ts", - "version": "1.2.0", + "version": "1.2.2", "description": "Node-side runtime helpers for MetaObjects: Fastify route builders, Drizzle filter/sort integration, Kysely drivers.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/sdk/package.json b/server/typescript/packages/sdk/package.json index 511723b6a9..29428e2d67 100644 --- a/server/typescript/packages/sdk/package.json +++ b/server/typescript/packages/sdk/package.json @@ -1,6 +1,6 @@ { "name": "@metaobjectsdev/sdk", - "version": "1.2.0", + "version": "1.2.2", "description": "Workspace helpers and agent-context assembly for MetaObjects projects.", "type": "module", "main": "./dist/index.js", diff --git a/server/typescript/packages/test-generators/src/templates/zod-validators.ts b/server/typescript/packages/test-generators/src/templates/zod-validators.ts index ea4945feae..1aafe1a916 100644 --- a/server/typescript/packages/test-generators/src/templates/zod-validators.ts +++ b/server/typescript/packages/test-generators/src/templates/zod-validators.ts @@ -386,6 +386,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { * The field SET the `UpdateSchema` accepts — same iteration + skip rules * as `insertSchemaFields`, but mirroring the UpdateSchema branch of * `renderZodValidators`: + * • a primary-key field is OMITTED, generated or assigned (the URL names the row); * • a TPH subtype's @discriminator field is OMITTED (clients can't change subtype); * • @autoSet onCreate fields are OMITTED (creation timestamps are immutable); * • @autoSet onUpdate fields are present + optional (server fills them); @@ -393,6 +394,7 @@ export function insertSchemaFields(obj: MetaObject): SchemaFieldShape[] { */ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { const autoGenPkFields = autoGenPkFieldNames(obj); + const pkFields = primaryKeyFieldNames(obj); const tphPin = tphDiscriminatorPin(obj); const out: SchemaFieldShape[] = []; for (const child of obj.fields()) { @@ -408,6 +410,10 @@ export function updateSchemaFields(obj: MetaObject): SchemaFieldShape[] { // edit form for an entity carrying one. Clearing counts as a write, so the // FR-035 present-null arm never reaches it either. if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): a primary-key field is the row's identity, which the URL names. An + // ASSIGNED key leaves the update shape exactly like a generated one, so a client-sent + // key is stripped and can never re-key the row. + if (pkFields.has(child.name)) continue; // TPH subtype discriminator: omitted from the update schema entirely. if (tphPin !== undefined && child.name === tphPin.fieldName) continue; const autoSet = child.attr(FIELD_ATTR_AUTO_SET); @@ -491,6 +497,10 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // below; a value presented on PATCH is stripped, not 400'd (see // updateSchemaFields for the grounding). if (isWriteOnceMutability(child)) continue; + // SECURITY (1.2.x): the row's identity is the URL's. An ASSIGNED primary key leaves the + // update shape too (a generated one never entered it), so a client-sent key is stripped + // on PUT/PATCH and can never re-key the row. Mirrors updateSchemaFields. + if (pkFields.has(child.name)) continue; // Update schema: @autoSet onCreate → omit entirely; onUpdate → transform if (autoSet === AUTO_SET_ON_CREATE) { @@ -515,10 +525,8 @@ export function renderZodValidators(obj: MetaObject, ctx?: RenderContext): Code // null — a present null CLEARS the column (`.set({field: null})` writes NULL). // Keyed on required-ness, NOT fieldWillBeOptional: a required-with-@default // field stays non-nullable so an explicit null on it is a 400 (validation), - // never a silent clear. PK fields are excluded: their Drizzle column is - // always not-null, so a nullable Zod type would fail `.set()`'s typecheck - // (and NOT NULL at runtime) — see primaryKeyFieldNames. - if (!isRequired(child) && !pkFields.has(child.name)) expr = code`${expr}.nullable()`; + // never a silent clear. PK fields never reach this branch (skipped above). + if (!isRequired(child)) expr = code`${expr}.nullable()`; updateFieldLines.push(code` ${child.name}: ${expr}`); } } From 3a9896936879e20503fe21ebf974cad448e7d496 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 16:23:36 -0500 Subject: [PATCH 182/267] fix(checks): TPH siblings sharing a column guard their own CHECKs; names cannot collide Sibling subtypes that declare one column with different checks each get their own, guarded by their discriminator values and named after the declaring object; identical ones share one unguarded CHECK. A subtype's cross-field CHECK carries its declarer in its default name. Two different CHECKs under one name on a table are refused when the schema is built. The corpus gains a concrete subtype with a concrete child, and TypeScript takes the subtype set C# takes (own @discriminatorValue). Drizzle guards the same enum CHECKs. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +- .../check-constraint-conformance/README.md | 18 +- .../expected.d1.json | 38 ++- .../expected.postgres.json | 46 +++- .../expected.postgres.skip-redundant.json | 46 +++- .../expected.sqlite.json | 38 ++- .../expected.sqlite.skip-redundant.json | 38 ++- .../input/meta.tph.json | 243 ++++++++++++++++-- .../CheckConstraintConformanceTests.cs | 23 +- .../Generators/CheckConstraints.cs | 209 +++++++++++---- .../src/templates/drizzle-schema.ts | 65 ++++- .../test/drizzle-enum-stringvaluemap.test.ts | 28 ++ .../migrate-ts/src/expected-schema.ts | 147 ++++++++--- .../test/check-name-collision.test.ts | 19 ++ 14 files changed, 823 insertions(+), 144 deletions(-) create mode 100644 server/typescript/packages/migrate-ts/test/check-name-collision.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a4cb8b86e4..81af1c45f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -633,8 +633,13 @@ vocabulary; upgrade every port together. cross-field validator a subtype declared was enforced nowhere. The base's table now carries them. A subtype-only column's field-level CHECK is the text a base column gets, with no discriminator guard: a CHECK refuses only FALSE, and a sibling subtype's row holds NULL there. - A subtype's cross-field validator is guarded by the discriminator, as an `@condition` ANDed with - its own, listing every concrete subtype it reaches. The Drizzle schema already declared the + Sibling subtypes that declare one column with DIFFERENT checks (different `@values`, a different + pattern) each get their own, guarded by their discriminator values and named + `
    Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'.
    @stringValueMappropertiesnometaobjects-core-typesOptional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE).
    @unique boolean no metaobjects-core-typesMember symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string.Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it.
    @xmlText
    ___…`; identical ones share one. A subtype's cross-field validator is + guarded by the discriminator, as an `@condition` ANDed with its own, listing every concrete + subtype it reaches, and its default name carries its declarer. Two different CHECKs under one + name on a table (a pre-existing hazard too: two comparisons with one left field) are now refused + when the schema is built, naming both, instead of a CREATE TABLE the database refuses. The Drizzle schema already declared the subtype enum CHECKs, so the two now agree. Pinned by `input/meta.tph.json` in the shared CHECK corpus. **Upgrade note:** the next `meta migrate` (or EF migration) adds these CHECKs to an existing TPH table; a legacy row outside a rule needs `@dbCheck: false` on that node first. diff --git a/fixtures/check-constraint-conformance/README.md b/fixtures/check-constraint-conformance/README.md index 5a938bb4d5..84b5513305 100644 --- a/fixtures/check-constraint-conformance/README.md +++ b/fixtures/check-constraint-conformance/README.md @@ -30,12 +30,18 @@ The rules the corpus pins (ruling R55, which follows `meta migrate`): nor a cross-field CHECK naming one (`band`, an `origin.computed` reached by the `HighGadgets` projection's `@filter`); - FR-017 TPH (`input/meta.tph.json`): the discriminator base's table carries its concrete - subtypes' CHECKs (`devices`). A subtype-only column's field-level CHECK is the text a base - column gets, unguarded — a CHECK refuses only FALSE, and a sibling's row holds NULL there. A - cross-field validator a subtype (or an abstract level, or a parent subtype) adds is guarded by - the discriminator, as an `@condition` ANDed with its own, listing every concrete subtype it - reaches (`powerRating` reaches `METER` and `SENSOR`). Subtypes in name order, fields - deduplicated by name as the column fold is; + subtypes' CHECKs (`devices`), subtypes in name order (a concrete subtype is one declaring its own + `@discriminatorValue`; `SmartMeter` is a concrete child of the concrete `Meter`). A column ONE + field node owns (`voltage`, declared once on the abstract `Powered`), or that sibling nodes + declare with identical CHECKs (`note`), gets the base-column text, unguarded: a CHECK refuses + only FALSE, and a sibling's row holds NULL there. Sibling nodes that DISAGREE (`grade` with + different `@values`, `serial` with different patterns) each get their own CHECK, guarded by the + discriminator values of the subtypes carrying that node (`Meter`'s reaches `METER` and + `SMART_METER`) and named `
    ___…`. A cross-field validator a subtype (or an + abstract level, or a parent subtype) adds is guarded the same way, as an `@condition` ANDed with + its own, and named after its declarer, so the same rule on two siblings does not collide + (`devices_sensor_note_reqwhen_chk`, `devices_switch_note_reqwhen_chk`). Two different CHECKs + under one name are refused at build; - a string-stored enum gets its membership CHECK and its `validator.length` CHECK, under `skipRedundant` too (`channel`); no regex CHECK on SQLite; `IS DISTINCT FROM` on Postgres, `IS NOT` on SQLite; `num_nonnulls` on Postgres, a sum of presence tests on SQLite. diff --git a/fixtures/check-constraint-conformance/expected.d1.json b/fixtures/check-constraint-conformance/expected.d1.json index 5201a31eab..81c504fc25 100644 --- a/fixtures/check-constraint-conformance/expected.d1.json +++ b/fixtures/check-constraint-conformance/expected.d1.json @@ -86,31 +86,59 @@ "devices": [ { "name": "devices_kind_chk", - "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" }, { "name": "devices_voltage_numeric_chk", "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, { "name": "devices_mode_chk", "expression": "\"mode\" IN ('AUTO', 'MANUAL')" }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, { "name": "devices_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" }, { - "name": "devices_voltage_atleastone_chk", - "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" }, { - "name": "devices_unit_reqwhen_chk", + "name": "devices_sensor_unit_reqwhen_chk", "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" }, { - "name": "devices_label_cmp_chk", + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS NOT 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS NOT 'OFF') OR (\"note\" IS NOT NULL))" } ] } diff --git a/fixtures/check-constraint-conformance/expected.postgres.json b/fixtures/check-constraint-conformance/expected.postgres.json index e7e431302e..c86432d996 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.json +++ b/fixtures/check-constraint-conformance/expected.postgres.json @@ -90,35 +90,67 @@ "devices": [ { "name": "devices_kind_chk", - "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" }, { "name": "devices_voltage_numeric_chk", "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" }, { - "name": "devices_serial_regex_chk", - "expression": "\"serial\" ~ '^M[0-9]+$'" + "name": "devices_meter_serial_regex_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"serial\" ~ '^M[0-9]+$')" + }, + { + "name": "devices_sensor_serial_regex_chk", + "expression": "(\"kind\" <> 'SENSOR') OR (\"serial\" ~ '^S[0-9]+$')" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" }, { "name": "devices_mode_chk", "expression": "\"mode\" IN ('AUTO', 'MANUAL')" }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, { "name": "devices_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" }, { - "name": "devices_voltage_atleastone_chk", - "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" }, { - "name": "devices_unit_reqwhen_chk", + "name": "devices_sensor_unit_reqwhen_chk", "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"unit\" IS NOT NULL))" }, { - "name": "devices_label_cmp_chk", + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS DISTINCT FROM 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS DISTINCT FROM 'OFF') OR (\"note\" IS NOT NULL))" } ] } diff --git a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json index 0646c3546f..9377b5e52f 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json @@ -90,35 +90,67 @@ "devices": [ { "name": "devices_kind_chk", - "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" }, { "name": "devices_voltage_numeric_chk", "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" }, { - "name": "devices_serial_regex_chk", - "expression": "\"serial\" ~ '^M[0-9]+$'" + "name": "devices_meter_serial_regex_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"serial\" ~ '^M[0-9]+$')" + }, + { + "name": "devices_sensor_serial_regex_chk", + "expression": "(\"kind\" <> 'SENSOR') OR (\"serial\" ~ '^S[0-9]+$')" + }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" }, { "name": "devices_mode_chk", "expression": "\"mode\" IN ('AUTO', 'MANUAL')" }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, { "name": "devices_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" }, { - "name": "devices_voltage_atleastone_chk", - "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" }, { - "name": "devices_unit_reqwhen_chk", + "name": "devices_sensor_unit_reqwhen_chk", "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"unit\" IS NOT NULL))" }, { - "name": "devices_label_cmp_chk", + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS DISTINCT FROM 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS DISTINCT FROM 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS DISTINCT FROM 'OFF') OR (\"note\" IS NOT NULL))" } ] } diff --git a/fixtures/check-constraint-conformance/expected.sqlite.json b/fixtures/check-constraint-conformance/expected.sqlite.json index 5201a31eab..81c504fc25 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.json @@ -86,31 +86,59 @@ "devices": [ { "name": "devices_kind_chk", - "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" }, { "name": "devices_voltage_numeric_chk", "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, { "name": "devices_mode_chk", "expression": "\"mode\" IN ('AUTO', 'MANUAL')" }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, { "name": "devices_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" }, { - "name": "devices_voltage_atleastone_chk", - "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" }, { - "name": "devices_unit_reqwhen_chk", + "name": "devices_sensor_unit_reqwhen_chk", "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" }, { - "name": "devices_label_cmp_chk", + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS NOT 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS NOT 'OFF') OR (\"note\" IS NOT NULL))" } ] } diff --git a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json index 97f27264f8..4368f8ac55 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json @@ -86,31 +86,59 @@ "devices": [ { "name": "devices_kind_chk", - "expression": "\"kind\" IN ('METER', 'SENSOR', 'SWITCH')" + "expression": "\"kind\" IN ('METER', 'SENSOR', 'SMART_METER', 'SWITCH')" }, { "name": "devices_voltage_numeric_chk", "expression": "\"voltage\" >= 1 AND \"voltage\" <= 480" }, + { + "name": "devices_meter_grade_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SMART_METER')) OR (\"grade\" IN ('A', 'B'))" + }, + { + "name": "devices_switch_grade_chk", + "expression": "(\"kind\" <> 'SWITCH') OR (\"grade\" IN ('X', 'Y'))" + }, + { + "name": "devices_note_length_chk", + "expression": "length(\"note\") <= 40" + }, { "name": "devices_mode_chk", "expression": "\"mode\" IN ('AUTO', 'MANUAL')" }, + { + "name": "devices_firmware_length_chk", + "expression": "length(\"firmware\") >= 1" + }, { "name": "devices_label_length_chk", "expression": "length(\"label\") >= 1 AND length(\"label\") <= 12" }, { - "name": "devices_voltage_atleastone_chk", - "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" + "name": "devices_powered_voltage_atleastone_chk", + "expression": "((\"kind\" <> 'METER') AND (\"kind\" <> 'SENSOR') AND (\"kind\" <> 'SMART_METER')) OR (\"voltage\" IS NOT NULL OR \"watts\" IS NOT NULL)" }, { - "name": "devices_unit_reqwhen_chk", + "name": "devices_sensor_unit_reqwhen_chk", "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"unit\" IS NOT NULL))" }, { - "name": "devices_label_cmp_chk", + "name": "devices_sensor_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SENSOR') OR ((\"mode\" IS NOT 'MANUAL') OR (\"note\" IS NOT NULL))" + }, + { + "name": "devices_smartmeter_firmware_reqwhen_chk", + "expression": "(\"kind\" <> 'SMART_METER') OR ((\"grade\" IS NOT 'A') OR (\"firmware\" IS NOT NULL))" + }, + { + "name": "devices_switch_label_cmp_chk", "expression": "((\"kind\" <> 'SWITCH') OR (\"label\" IS NULL)) OR (\"label\" <> \"kind\")" + }, + { + "name": "devices_switch_note_reqwhen_chk", + "expression": "(\"kind\" <> 'SWITCH') OR ((\"legacy_position\" IS NOT 'OFF') OR (\"note\" IS NOT NULL))" } ] } diff --git a/fixtures/check-constraint-conformance/input/meta.tph.json b/fixtures/check-constraint-conformance/input/meta.tph.json index 321bcb376f..0588849f56 100644 --- a/fixtures/check-constraint-conformance/input/meta.tph.json +++ b/fixtures/check-constraint-conformance/input/meta.tph.json @@ -7,10 +7,35 @@ "name": "Device", "@discriminator": "kind", "children": [ - { "source.rdb": { "@table": "devices" } }, - { "field.long": { "name": "id" } }, - { "field.enum": { "name": "kind", "@required": true, "@values": ["METER", "SENSOR", "SWITCH"] } }, - { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } + { + "source.rdb": { + "@table": "devices" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.enum": { + "name": "kind", + "@required": true, + "@values": [ + "METER", + "SENSOR", + "SMART_METER", + "SWITCH" + ] + } + }, + { + "identity.primary": { + "name": "id", + "@fields": "id", + "@generation": "increment" + } + } ] } }, @@ -20,9 +45,33 @@ "abstract": true, "extends": "Device", "children": [ - { "field.int": { "name": "voltage", "children": [ { "validator.numeric": { "@min": 1, "@max": 480 } } ] } }, - { "field.int": { "name": "watts" } }, - { "validator.atLeastOne": { "name": "powerRating", "@fields": ["voltage", "watts"] } } + { + "field.int": { + "name": "voltage", + "children": [ + { + "validator.numeric": { + "@min": 1, + "@max": 480 + } + } + ] + } + }, + { + "field.int": { + "name": "watts" + } + }, + { + "validator.atLeastOne": { + "name": "powerRating", + "@fields": [ + "voltage", + "watts" + ] + } + } ] } }, @@ -32,7 +81,57 @@ "extends": "Powered", "@discriminatorValue": "METER", "children": [ - { "field.string": { "name": "serial", "@required": true, "children": [ { "validator.regex": { "@pattern": "^M[0-9]+$" } } ] } } + { + "field.string": { + "name": "serial", + "@required": true, + "children": [ + { + "validator.regex": { + "@pattern": "^M[0-9]+$" + } + } + ] + } + }, + { + "field.enum": { + "name": "grade", + "@values": [ + "A", + "B" + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "SmartMeter", + "extends": "Meter", + "@discriminatorValue": "SMART_METER", + "children": [ + { + "field.string": { + "name": "firmware", + "children": [ + { + "validator.length": { + "@min": 1 + } + } + ] + } + }, + { + "validator.requiredWhen": { + "name": "gradedFirmware", + "@field": "firmware", + "@when": "grade", + "@equals": "A" + } + } ] } }, @@ -42,9 +141,61 @@ "extends": "Powered", "@discriminatorValue": "SENSOR", "children": [ - { "field.enum": { "name": "mode", "@required": true, "@values": ["AUTO", "MANUAL"] } }, - { "field.string": { "name": "unit" } }, - { "validator.requiredWhen": { "name": "manualUnit", "@field": "unit", "@when": "mode", "@equals": "MANUAL" } } + { + "field.string": { + "name": "serial", + "children": [ + { + "validator.regex": { + "@pattern": "^S[0-9]+$" + } + } + ] + } + }, + { + "field.string": { + "name": "note", + "children": [ + { + "validator.length": { + "@max": 40 + } + } + ] + } + }, + { + "field.enum": { + "name": "mode", + "@required": true, + "@values": [ + "AUTO", + "MANUAL" + ] + } + }, + { + "field.string": { + "name": "unit" + } + }, + { + "validator.requiredWhen": { + "name": "manualUnit", + "@field": "unit", + "@when": "mode", + "@equals": "MANUAL" + } + }, + { + "validator.requiredWhen": { + "name": "manualNote", + "@field": "note", + "@when": "mode", + "@equals": "MANUAL" + } + } ] } }, @@ -54,10 +205,72 @@ "extends": "Device", "@discriminatorValue": "SWITCH", "children": [ - { "field.string": { "name": "label", "children": [ { "validator.length": { "@min": 1, "@max": 12 } } ] } }, - { "field.enum": { "name": "legacyPosition", "@values": ["ON", "OFF"], "@dbCheck": false } }, - { "validator.comparison": { "name": "labelled", "@left": "label", "@op": "ne", "@right": "kind", - "@condition": { "op": "isNotNull", "arg": { "field": "label" } } } } + { + "field.enum": { + "name": "grade", + "@values": [ + "X", + "Y" + ] + } + }, + { + "field.string": { + "name": "note", + "children": [ + { + "validator.length": { + "@max": 40 + } + } + ] + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "validator.length": { + "@min": 1, + "@max": 12 + } + } + ] + } + }, + { + "field.enum": { + "name": "legacyPosition", + "@values": [ + "ON", + "OFF" + ], + "@dbCheck": false + } + }, + { + "validator.comparison": { + "name": "labelled", + "@left": "label", + "@op": "ne", + "@right": "kind", + "@condition": { + "op": "isNotNull", + "arg": { + "field": "label" + } + } + } + }, + { + "validator.requiredWhen": { + "name": "offNote", + "@field": "note", + "@when": "legacyPosition", + "@equals": "OFF" + } + } ] } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs index e4fd508bef..616f1c2be7 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs @@ -87,7 +87,9 @@ public void The_context_declares_each_check_on_its_table() Assert.Contains("t.HasCheckConstraint(\"gadgets_rank_numeric_chk\", \"\\\"rank\\\" <= 99\")", context); // FR-017 TPH: a subtype's columns are on its base's table, and so are their CHECKs. Assert.Contains("modelBuilder.Entity().ToTable(t => t.HasCheckConstraint(\"devices_mode_chk\", \"\\\"mode\\\" IN ('AUTO', 'MANUAL')\"));", context); - Assert.Contains("t.HasCheckConstraint(\"devices_unit_reqwhen_chk\", ", context); + Assert.Contains("t.HasCheckConstraint(\"devices_sensor_unit_reqwhen_chk\", ", context); + // rc.21 fix round (I1): siblings that disagree on a shared column each guard their own CHECK. + Assert.Contains("t.HasCheckConstraint(\"devices_switch_grade_chk\", \"(\\\"kind\\\" <> 'SWITCH') OR (\\\"grade\\\" IN ('X', 'Y'))\")", context); Assert.DoesNotContain("devices_legacy_position_chk", context); } @@ -116,4 +118,23 @@ public void The_context_with_its_checks_compiles_against_EF_Core_8() .Select(d => $"{d.Id}: {d.GetMessage()}").ToList(); Assert.True(errors.Count == 0, string.Join("\n", errors)); } + + // rc.21 fix round (I2): two different CHECKs under one default name are refused, naming both. + [Fact] + public void Two_checks_under_one_name_are_refused() + { + var load = new MetaDataLoader().Load([new InMemoryStringSource(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Window", "children": [ + { "source.rdb": { "@table": "windows" } }, + { "field.long": { "name": "id" } }, + { "field.int": { "name": "a" } }, { "field.int": { "name": "b" } }, { "field.int": { "name": "c" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "validator.comparison": { "name": "ab", "@left": "a", "@op": "lt", "@right": "b" } }, + { "validator.comparison": { "name": "ac", "@left": "a", "@op": "lt", "@right": "c" } } ] } } ] } } + """, id: "w.json")]); + Assert.Empty(load.Errors); + var ex = Assert.Throws(() => CheckConstraints.For(load.Root.Objects().Single(), Ctx(load.Root, "postgres").Config)); + Assert.Contains("both named 'windows_a_cmp_chk'", ex.Message); + } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index 35dbf44247..5605976168 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -45,50 +45,11 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co var strategy = config.ColumnNamingStrategy; var table = CSharpNaming.Table(entity); var checks = new List(); - // FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded - // columns (name-sorted subtypes, deduplicated by field name, as the column fold is), so it - // carries their CHECKs too. A subtype-only column's CHECK is the text a base column gets, - // with no discriminator guard: a CHECK refuses only FALSE, and a sibling subtype's row - // holds NULL there, for which every field-level expression is NULL. + foreach (var field in entity.Fields()) + checks.AddRange(FieldChecks(field, table, strategy, dialect, config).Select(c => c.Check)); var root = entity.Root() as MetaRoot; var tph = root is null ? null : TphPlanBuilder.For(entity, root); - var fields = tph is null ? entity.Fields() : entity.Fields().Concat(TphPlanBuilder.CollectSubtypeFields(entity, root!)); - foreach (var field in fields) - { - // No field-level CHECK on an array column: every expression below is scalar-shaped. - if (field.ResolvedIsArray()) continue; - // A derived (origin-bearing) field is no column of the table: a CHECK on it fails the - // migration. Its validators apply where it is read. - if (field.IsDerived()) continue; - var col = CSharpNaming.Column(field, strategy); - var qcol = Quote(col); - // @dbCheck: false (resolving) asks for no CHECK: the rule is enforced app-side only. - if (field.SubType == FIELD_SUBTYPE_ENUM && !OptedOut(field) && field.EffectiveEnumValues is { Count: > 0 } values) - { - var ints = field.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; - // rc.21: a string member is stored as its @stringValueMap string, else as itself. - var members = ints is null - ? values.Select(v => Literal(EnumStorage.StoredValue(field, v))) - : values.Select(v => ints.TryGetValue(v, out var n) && n is not null - ? Number(n) - : throw new InvalidOperationException( - $"field.enum '{field.Name}' @intValueMap has no integer for member '{v}' — cannot build the CHECK constraint for column '{col}'.")); - checks.Add(Named(new CheckConstraint($"{table}_{col}_chk", $"{qcol} IN ({string.Join(", ", members)})"), field)); - } - // The VARCHAR(n) the column already is, when the project skips what it enforces. Not on - // SQLite / D1: they accept a declared length and store longer values anyway. - var enforcedMax = config.SkipRedundantChecks && !IsSqlite(dialect) ? VarcharLength(field) : null; - foreach (var v in field.Validators()) - { - if (OptedOut(v)) continue; - // A declared @constraintName asks for the CHECK by name, so it is kept even where - // skipRedundant would leave it out: a declaration beats a default. - var declared = DeclaredName(v) is not null; - var check = ValidatorCheck(v, qcol, table, col, dialect, - skipRedundant: !declared && config.SkipRedundantChecks, enforcedMax: declared ? null : enforcedMax); - if (check is not null) checks.Add(Named(check, v)); - } - } + if (tph is not null) checks.AddRange(SubtypeFieldChecks(entity, tph, table, strategy, dialect, config)); // A cross-field validator always keeps its CHECK: it is enforced nowhere else, and the loader // refuses @dbCheck: false on one (ERR_CROSS_FIELD_WITHOUT_CHECK). foreach (var v in entity.Validators()) @@ -97,15 +58,157 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); } if (tph is not null) checks.AddRange(SubtypeCrossFieldChecks(entity, tph, table, strategy, dialect)); + return Distinct(entity, checks); + } + + /// + /// One table's CHECKs, with an exact repeat (same name, same expression) kept once, and two + /// different CHECKs under one name refused: the database would refuse the second at CREATE + /// TABLE, and EF would keep only one of them. + /// + private static IReadOnlyList Distinct(MetaObject entity, List checks) + { + var byName = new Dictionary(StringComparer.Ordinal); + var outList = new List(); + foreach (var c in checks) + { + if (byName.TryGetValue(c.Name, out var seen)) + { + if (seen.Expression == c.Expression) continue; + throw new InvalidOperationException( + $"object.entity '{entity.Name}': two CHECK constraints are both named '{c.Name}' ({seen.Expression} | {c.Expression}). " + + "Give one of the validators (or enums) a @constraintName."); + } + byName[c.Name] = c; + outList.Add(c); + } + return outList; + } + + /// One column's field-level CHECKs (its enum membership, then each validator's), each with whether its name was declared. + private static List<(CheckConstraint Check, bool Declared)> FieldChecks( + MetaField field, string table, ColumnNamingStrategy strategy, string? dialect, GenConfig config) + { + var checks = new List<(CheckConstraint, bool)>(); + // No field-level CHECK on an array column: every expression below is scalar-shaped. + if (field.ResolvedIsArray()) return checks; + // A derived (origin-bearing) field is no column of the table: a CHECK on it fails the + // migration. Its validators apply where it is read. + if (field.IsDerived()) return checks; + var col = CSharpNaming.Column(field, strategy); + var qcol = Quote(col); + // @dbCheck: false (resolving) asks for no CHECK: the rule is enforced app-side only. + if (field.SubType == FIELD_SUBTYPE_ENUM && !OptedOut(field) && field.EffectiveEnumValues is { Count: > 0 } values) + { + var ints = field.Attr(FIELD_ATTR_INT_VALUE_MAP) as IReadOnlyDictionary; + // rc.21: a string member is stored as its @stringValueMap string, else as itself. + var members = ints is null + ? values.Select(v => Literal(EnumStorage.StoredValue(field, v))) + : values.Select(v => ints.TryGetValue(v, out var n) && n is not null + ? Number(n) + : throw new InvalidOperationException( + $"field.enum '{field.Name}' @intValueMap has no integer for member '{v}' — cannot build the CHECK constraint for column '{col}'.")); + checks.Add((Named(new CheckConstraint($"{table}_{col}_chk", $"{qcol} IN ({string.Join(", ", members)})"), field), DeclaredName(field) is not null)); + } + // The VARCHAR(n) the column already is, when the project skips what it enforces. Not on + // SQLite / D1: they accept a declared length and store longer values anyway. + var enforcedMax = config.SkipRedundantChecks && !IsSqlite(dialect) ? VarcharLength(field) : null; + foreach (var v in field.Validators()) + { + if (OptedOut(v)) continue; + // A declared @constraintName asks for the CHECK by name, so it is kept even where + // skipRedundant would leave it out: a declaration beats a default. + var declared = DeclaredName(v) is not null; + var check = ValidatorCheck(v, qcol, table, col, dialect, + skipRedundant: !declared && config.SkipRedundantChecks, enforcedMax: declared ? null : enforcedMax); + if (check is not null) checks.Add((Named(check, v), declared)); + } return checks; } + /// + /// FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded columns, + /// so it carries their field-level CHECKs too, the subtypes in name order. + /// A column ONE field node owns (declared once, on a subtype or on an abstract level its + /// subtypes share) gets the text a base column gets, with no guard: a CHECK refuses only FALSE, + /// and a sibling's row holds NULL there, for which every field-level expression is NULL. So does + /// a column several sibling nodes declare with identical CHECKs. Sibling nodes that disagree + /// (different @values, a different pattern) each get their own CHECKs, guarded by the + /// discriminator values of the subtypes that carry that node and named after the declaring + /// object (<table>_<declarer>_<col>_…), so neither refuses the other's rows. + /// + private static IEnumerable SubtypeFieldChecks( + MetaObject entity, TphPlan tph, string table, ColumnNamingStrategy strategy, string? dialect, GenConfig config) + { + var baseNames = new HashSet(entity.Fields().Select(f => f.Name), StringComparer.Ordinal); + var groups = new List<(string Name, List<(MetaField Node, List Values)> Owners)>(); + foreach (var st in tph.Subtypes) + { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + foreach (var f in st.Entity.Fields()) + { + if (baseNames.Contains(f.Name)) continue; + var g = groups.FindIndex(x => x.Name == f.Name); + if (g < 0) + { + groups.Add((f.Name, [(f, [st.Value])])); + continue; + } + var owners = groups[g].Owners; + var o = owners.FindIndex(x => ReferenceEquals(x.Node, f)); + if (o < 0) owners.Add((f, [st.Value])); + else owners[o].Values.Add(st.Value); + } + } + foreach (var (_, owners) in groups) + { + var per = owners.Select(o => (o.Node, o.Values, Checks: FieldChecks(o.Node, table, strategy, dialect, config))).ToList(); + var first = per[0].Checks.Select(c => c.Check).ToList(); + if (per.All(p => p.Checks.Select(c => c.Check).SequenceEqual(first))) + { + foreach (var c in first) yield return c; + continue; + } + foreach (var (node, values, nodeChecks) in per) + foreach (var (check, declared) in nodeChecks) + { + var guarded = Wrap(check, DiscriminatorIn(tph, values), entity, strategy, dialect); + yield return declared ? guarded : guarded with { Name = Qualified(check.Name, table, node.Parent) }; + } + } + } + + /// A default CHECK name made unique to the object that declares the rule: <table>_<declarer>_…. + private static string Qualified(string name, string table, MetaData? declarer) + { + var tag = (declarer?.Name ?? "subtype").ToLowerInvariant(); + return name.StartsWith(table + "_", StringComparison.Ordinal) + ? $"{table}_{tag}_{name[(table.Length + 1)..]}" + : $"{tag}_{name}"; + } + + /// The condition "the discriminator is one of ". + private static IReadOnlyDictionary DiscriminatorIn(TphPlan tph, IReadOnlyList values) + { + IReadOnlyDictionary Eq(string value) => new Dictionary + { + [KeyOp] = FILTER_OP_EQ, + [KeyLeft] = new Dictionary { [KeyField] = tph.DiscriminatorField }, + [KeyRight] = new Dictionary { [KeyValue] = value }, + }; + return values.Count == 1 + ? Eq(values[0]) + : new Dictionary { [KeyOp] = FILTER_COMPOSE_OR, [KeyArgs] = values.Select(x => (object?)Eq(x)).ToList() }; + } + /// /// FR-017 TPH: a cross-field validator a subtype adds holds for that subtype's rows only, so the /// discriminator guards it — unlike a field-level CHECK, most cross-field rules are FALSE (not /// NULL) over a sibling's NULL columns (atLeastOne, requiredWhen). The guard lists every concrete /// subtype the validator reaches (one on an abstract level, or on a parent subtype, reaches each - /// of its concrete descendants), as an @condition ANDed with the validator's own. + /// of its concrete descendants), as an @condition ANDed with the validator's own. Its + /// default name carries the declaring object (<table>_<declarer>_…), so the same + /// rule on two siblings, or on a sibling and the base, does not collide. /// private static IEnumerable SubtypeCrossFieldChecks( MetaObject entity, TphPlan tph, string table, ColumnNamingStrategy strategy, string? dialect) @@ -124,16 +227,8 @@ private static IEnumerable SubtypeCrossFieldChecks( foreach (var (v, holder, values) in reached) { if (CrossFieldCheck(v, holder, table, strategy, dialect) is not { } check) continue; - IReadOnlyDictionary Eq(string value) => new Dictionary - { - [KeyOp] = FILTER_OP_EQ, - [KeyLeft] = new Dictionary { [KeyField] = tph.DiscriminatorField }, - [KeyRight] = new Dictionary { [KeyValue] = value }, - }; - var guard = values.Count == 1 - ? Eq(values[0]) - : new Dictionary { [KeyOp] = FILTER_COMPOSE_OR, [KeyArgs] = values.Select(x => (object?)Eq(x)).ToList() }; - yield return Named(WithCondition(check, v, holder, strategy, dialect, guard), v); + var guarded = WithCondition(check, v, holder, strategy, dialect, DiscriminatorIn(tph, values)); + yield return DeclaredName(v) is { } name ? guarded with { Name = name } : guarded with { Name = Qualified(check.Name, table, v.Parent) }; } } @@ -271,7 +366,13 @@ private static CheckConstraint WithCondition( var condition = guard is null ? own : own is null ? guard : new Dictionary { [KeyOp] = FILTER_COMPOSE_AND, [KeyArgs] = new List { guard, own } }; - if (condition is null) return check; + return condition is null ? check : Wrap(check, condition, entity, strategy, dialect); + } + + /// The CHECK holds only where does: the negated condition OR the rule. + private static CheckConstraint Wrap( + CheckConstraint check, IReadOnlyDictionary condition, MetaObject entity, ColumnNamingStrategy strategy, string? dialect) + { string? Column(string name) => entity.Fields().FirstOrDefault(f => f.Name == name) is { } f ? Quote(CSharpNaming.Column(f, strategy)) : null; // An int-backed enum stores a member as its integer; a duration in the form its column stores. diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 010ef5cf6a..8889803ccd 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -26,12 +26,13 @@ import { dialectModule } from "../dialect-module.js"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "../names.js"; -import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { intValueMapOf } from "../enum-meta.js"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "../tph.js"; import { effectivePackage } from "../docs-paths.js"; @@ -267,8 +268,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -750,3 +755,55 @@ function renderColumn( ? code` // ${spec.leadingComment}\n${columnLine}` : columnLine; } + +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
    ___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): Array<{ name: Code; expr: Code }> | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: Array<{ name: Code; expr: Code }> = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + const name = typeof declared === "string" && declared.length > 0 + ? declared + : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + }); + return out; +} diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts index 8121ca4ac9..a626e3301f 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts @@ -69,3 +69,31 @@ describe("Drizzle codegen — @stringValueMap field.enum customType", () => { expect(out).toContain('dataType: () => "varchar(12)"'); }); }); + +// rc.21 fix round (I1): sibling TPH subtypes declaring one column with different @values each +// get their own enum CHECK, guarded by their discriminator value, as `meta migrate` derives it. +describe("Drizzle codegen — TPH siblings sharing a column with different @values", () => { + test("each owner's CHECK is guarded by its discriminator value", async () => { + const json = JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Device", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "devices" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "kind", "@values": ["METER", "SWITCH"] } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.entity": { name: "Meter", extends: "Device", "@discriminatorValue": "METER", children: [ + { "field.enum": { name: "grade", "@values": ["A", "B"] } } ] } }, + { "object.entity": { name: "Switch", extends: "Device", "@discriminatorValue": "SWITCH", children: [ + { "field.enum": { name: "grade", "@values": ["X", "Y"] } } ] } } ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + const ctx = makeRenderContext({ + dialect: "postgres", loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root), + }); + const out = renderDrizzleSchema(res.root.findObject("Device")!, ctx).toString(); + expect(out).toContain(`"devices_meter_grade_chk"`); + expect(out).toContain(`("kind" <> 'METER') OR (grade IN ('A', 'B'))`); + expect(out).toContain(`"devices_switch_grade_chk"`); + expect(out).not.toContain(`"devices_grade_chk"`); + }); +}); diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index 0f9ccb84cb..ff763c8bad 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -895,24 +895,8 @@ function buildChecks( root?: MetaData, ): CheckDescriptor[] { const checks: CheckDescriptor[] = []; - // FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded - // columns, so it carries their CHECKs too — in name order, so every port lists them alike. - const subtypes = root === undefined ? [] : [...tphConcreteSubtypes(entity, root)] - .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); - // A subtype-only column's CHECK is the text a base column gets, with no discriminator guard: - // a CHECK refuses only FALSE, and a sibling subtype's row holds NULL there, for which every - // field-level expression is NULL. Deduplicated by field name, as the column fold is. - const baseFieldNames = new Set(entity.fields().map((f) => f.name)); - const subtypeFields: MetaField[] = []; - for (const sub of subtypes) { - // ADR-0039: effective fields — a field on an abstract intermediate level is a column too. - for (const field of sub.fields()) { - if (baseFieldNames.has(field.name)) continue; - baseFieldNames.add(field.name); - subtypeFields.push(field); - } - } - for (const field of [...entity.fields(), ...subtypeFields]) { + const fieldChecks = (field: MetaField): CheckDescriptor[] => { + const out: CheckDescriptor[] = []; // No field-level CHECKs on array columns: the derived expressions assume a // SCALAR column. `"labels" IN ('A','B')` against a text[] is a type error at // CREATE TABLE; `length(col)`/range checks are equally scalar-shaped. Array @@ -920,10 +904,10 @@ function buildChecks( // per-port validators), matching codegen-ts's column-mapper which also skips // the enum literal-union for isArray columns. // ADR-0039: resolving — array-ness may be inherited via extends. - if (field.resolvedIsArray()) continue; + if (field.resolvedIsArray()) return out; // A derived (origin-bearing) field is no column of the table (the column builder skips it // too): a CHECK on it fails CREATE TABLE. Its validators apply where it is read. - if (field.isDerived()) continue; + if (field.isDerived()) return out; const col = resolveColumnName(field, strategy); const qcol = quoteCheckCol(col); // Enum membership check. An INT-BACKED enum (@intValueMap, design D5) stores @@ -959,7 +943,7 @@ function buildChecks( expression = `${qcol} IN (${values.map((v) => `'${storedEnumValue(field, v).replace(/'/g, "''")}'`).join(", ")})`; } const enumCheck = { name: `${tableName}_${col}_chk`, expression }; - checks.push(withDeclaredName(enumCheck, field)); + out.push(withDeclaredName(enumCheck, field)); } } // Validator-derived checks. @@ -976,7 +960,66 @@ function buildChecks( const check = keep ? validatorCheck(v, qcol, tableName, col, dialect) : validatorCheck(v, qcol, tableName, col, dialect, skipRedundant, enforcedMax); - if (check) checks.push(withDeclaredName(check, v)); + if (check) out.push(withDeclaredName(check, v)); + } + return out; + }; + for (const field of entity.fields()) checks.push(...fieldChecks(field)); + // FR-017 TPH: a discriminator base's table also holds every concrete subtype's folded columns, + // so it carries their CHECKs too — subtypes in name order, so every port lists them alike. A + // concrete subtype is one that declares its own @discriminatorValue (the loader requires one on + // every concrete subtype, ERR_DISCRIMINATOR_VALUE_MISSING), the set the C# port takes. + const discriminator = entity.attr(OBJECT_ATTR_DISCRIMINATOR); + const subtypes = root === undefined ? [] : [...tphConcreteSubtypes(entity, root)] + // ADR-0039: own — a concrete subtype declares its OWN value. + .filter((c) => c.ownAttr(OBJECT_ATTR_DISCRIMINATOR_VALUE) !== undefined) + .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const valueOf = (sub: MetaObject): string => String(sub.ownAttr(OBJECT_ATTR_DISCRIMINATOR_VALUE)); + const discriminatorIn = (values: readonly string[]): ExprNode => { + const eq = (value: string): ExprNode => + ({ op: "eq", left: { field: discriminator }, right: { value } }) as unknown as ExprNode; + return values.length === 1 ? eq(values[0]!) : ({ op: "or", args: values.map(eq) } as unknown as ExprNode); + }; + if (typeof discriminator === "string" && subtypes.length > 0) { + // A column ONE field node owns (declared once, on a subtype or on an abstract level its + // subtypes share) gets the text a base column gets, with no guard: a CHECK refuses only FALSE, + // and a sibling's row holds NULL there, for which every field-level expression is NULL. So does + // a column several sibling nodes declare with identical CHECKs. Sibling nodes that disagree + // (different @values, a different pattern) each get their own CHECKs, guarded by the + // discriminator values of the subtypes carrying that node and named after the declaring object + // (`
    ___…`), so neither refuses the other's rows. + const baseFieldNames = new Set(entity.fields().map((f) => f.name)); + const groups = new Map(); + for (const sub of subtypes) { + // ADR-0039: effective fields — a field on an abstract level or a parent subtype is a column too. + for (const field of sub.fields()) { + if (baseFieldNames.has(field.name)) continue; + const owners = groups.get(field.name) ?? []; + if (!groups.has(field.name)) groups.set(field.name, owners); + const owner = owners.find((o) => o.node === field); + if (owner === undefined) owners.push({ node: field, values: [valueOf(sub)] }); + else owner.values.push(valueOf(sub)); + } + } + const same = (a: CheckDescriptor[], b: CheckDescriptor[]): boolean => + a.length === b.length && a.every((c, i) => c.name === b[i]!.name && c.expression === b[i]!.expression); + for (const owners of groups.values()) { + const per = owners.map((o) => ({ ...o, checks: fieldChecks(o.node) })); + if (per.every((p) => same(p.checks, per[0]!.checks))) { + checks.push(...per[0]!.checks); + continue; + } + for (const { node, values, checks: nodeChecks } of per) { + for (const check of nodeChecks) { + const guarded = wrapCondition(check, discriminatorIn(values), entity, strategy, dialect); + if (DECLARED_CHECKS.has(check)) { + DECLARED_CHECKS.add(guarded); + checks.push(guarded); + } else { + checks.push({ ...guarded, name: qualifiedCheckName(check.name, tableName, node.parent) }); + } + } + } } } // Entity-scoped cross-field validators (comparison / requiredWhen / presentIff / atLeastOne). @@ -991,31 +1034,63 @@ function buildChecks( // FALSE (not NULL) over a sibling's NULL columns (atLeastOne, requiredWhen). The guard lists // every concrete subtype the validator reaches (an abstract level's, or a parent subtype's, // reaches each of its concrete descendants), as an @condition ANDed with the validator's own. - const discriminator = entity.attr(OBJECT_ATTR_DISCRIMINATOR); + // Its default name carries the declaring object, so the same rule on two siblings, or on a + // sibling and the base, does not collide. if (typeof discriminator === "string" && subtypes.length > 0) { const baseValidators = new Set(entity.validators()); const reached = new Map(); for (const sub of subtypes) { - // ADR-0039: effective — @discriminatorValue may be inherited (sub-subtype). - const value = String(sub.attr(OBJECT_ATTR_DISCRIMINATOR_VALUE)); // ADR-0039: effective validators — one declared on an abstract level or a parent subtype applies here too. for (const v of sub.validators()) { if (baseValidators.has(v)) continue; const entry = reached.get(v); - if (entry === undefined) reached.set(v, { holder: sub, values: [value] }); - else entry.values.push(value); + if (entry === undefined) reached.set(v, { holder: sub, values: [valueOf(sub)] }); + else entry.values.push(valueOf(sub)); } } for (const [v, { holder, values }] of reached) { const check = crossFieldCheck(v, holder, tableName, strategy, dialect); if (!check) continue; - const eq = (value: string): ExprNode => - ({ op: "eq", left: { field: discriminator }, right: { value } }) as unknown as ExprNode; - const guard = values.length === 1 ? eq(values[0]!) : ({ op: "or", args: values.map(eq) } as unknown as ExprNode); - checks.push(withDeclaredName(withCondition(check, v, holder, strategy, dialect, guard), v)); + const guarded = withCondition(check, v, holder, strategy, dialect, discriminatorIn(values)); + checks.push(declaredCheckName(v) !== undefined + ? withDeclaredName(guarded, v) + : { ...guarded, name: qualifiedCheckName(check.name, tableName, v.parent) }); + } + } + return distinctChecks(entity, checks); +} + +/** A default CHECK name made unique to the object that declares the rule: `
    __…`. */ +function qualifiedCheckName(name: string, tableName: string, declarer: MetaData | undefined): string { + const tag = (declarer?.name ?? "subtype").toLowerCase(); + return name.startsWith(`${tableName}_`) ? `${tableName}_${tag}_${name.slice(tableName.length + 1)}` : `${tag}_${name}`; +} + +/** + * One table's CHECKs, an exact repeat (same name, same expression) kept once, and two different + * CHECKs under one name refused: the database would refuse the second at CREATE TABLE. + */ +function distinctChecks(entity: MetaObject, checks: CheckDescriptor[]): CheckDescriptor[] { + const byName = new Map(); + const out: CheckDescriptor[] = []; + for (const c of checks) { + const seen = byName.get(c.name); + if (seen !== undefined) { + if (seen.expression === c.expression) continue; + // A DECLARED name's collision is checkDeclaredCheckNames' to report, with its own error. + if (DECLARED_CHECKS.has(c) || DECLARED_CHECKS.has(seen)) { + out.push(c); + continue; + } + throw new Error( + `object.entity '${entity.name}': two CHECK constraints are both named '${c.name}' ` + + `(${seen.expression} | ${c.expression}). Give one of the validators (or enums) a @constraintName.`, + ); } + byName.set(c.name, c); + out.push(c); } - return checks; + return out; } /** @@ -1169,7 +1244,13 @@ function withCondition( const condition: ExprNode | undefined = guard === undefined ? own : own === undefined ? guard : ({ op: "and", args: [guard, own] } as unknown as ExprNode); - if (condition === undefined) return check; + return condition === undefined ? check : wrapCondition(check, condition, entity, strategy, dialect); +} + +/** The CHECK holds only where `condition` does: the negated condition OR the rule. */ +function wrapCondition( + check: CheckDescriptor, condition: ExprNode, entity: MetaObject, strategy: ColumnNamingStrategy, dialect: Dialect | undefined, +): CheckDescriptor { const column = (name: string): string | undefined => { const field = entity.fields().find((f) => f.name === name); return field === undefined ? undefined : quoteCheckCol(resolveColumnName(field, strategy)); diff --git a/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts b/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts new file mode 100644 index 0000000000..60c771b830 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts @@ -0,0 +1,19 @@ +// rc.21 fix round (I2): two different CHECKs under one default name are refused at build, naming +// both, instead of a CREATE TABLE the database refuses ("constraint already exists"). + +import { expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../src/expected-schema.js"; + +test("two CHECKs under one default name are refused", async () => { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Window", children: [ + { "source.rdb": { "@table": "windows" } }, + { "field.long": { name: "id" } }, + { "field.int": { name: "a" } }, { "field.int": { name: "b" } }, { "field.int": { name: "c" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "validator.comparison": { name: "ab", "@left": "a", "@op": "lt", "@right": "b" } }, + { "validator.comparison": { name: "ac", "@left": "a", "@op": "lt", "@right": "c" } } ] } } ] } }))]); + expect(errors).toEqual([]); + expect(() => buildExpectedSchema(root, { dialect: "postgres" })).toThrow(/both named 'windows_a_cmp_chk'/); +}); From 25dfc7ef8b9a4cf4ad5bbfbc9d082885e16b3c23 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 16:25:38 -0500 Subject: [PATCH 183/267] fix(reports): a report row carries @stringValueMap from its type source A view-backed report's row model carried @intValueMap but not @stringValueMap, so a dimension over a string-mapped enum read the raw stored string (TypeScript) or went through the name-based converter (C#). Every port's row model now carries it, so the row reads the member and an unknown stored value throws. Co-Authored-By: Claude Opus 5.5 --- .../ReportRowCodegenTests.cs | 18 ++++++++++++++++ .../csharp/MetaObjects.Codegen/ReportRows.cs | 2 ++ .../reporting/ReportReadModel.java | 1 + .../meta/core/reporting/report_read_model.py | 2 ++ .../src/core/reporting/report-read-model.ts | 3 +++ .../test/object-manager-report.test.ts | 21 +++++++++++++++++++ 6 files changed, 47 insertions(+) diff --git a/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs b/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs index 2749609a93..e09a2963d2 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/ReportRowCodegenTests.cs @@ -685,6 +685,24 @@ public void An_enum_dimension_declares_its_enum_and_reads_it_as_text() files["AppDbContext.g.cs"]); } + // rc.21 fix round (I3): a dimension over a @stringValueMap enum reads its stored strings — the + // row model carries the map from its type source, so the row gets the member <-> stored-string + // converter (which throws on an unknown stored value), not the name-based HasConversion(). + [Fact] + public void A_string_value_map_enum_dimension_reads_its_stored_strings() + { + var model = ModelTemplate.Replace( + "{ \"field.enum\": { \"name\": \"status\", \"@required\": true, \"@values\": [\"OPEN\", \"PAID\"] } }", + "{ \"field.enum\": { \"name\": \"status\", \"@required\": true, \"@values\": [\"OPEN\", \"PAID\"], \"@stringValueMap\": { \"OPEN\": \"open_v1\", \"PAID\": \"paid_v1\" } } }") + .Replace("<>", Report("SalesCube", "\"@kind\": \"view\", \"@view\": \"v_sales_cube\"", AllDimensions, AllMeasures)); + var load = new MetaDataLoader().Load([new InMemoryStringSource(model, id: "shop.json")]); + Assert.Empty(load.Errors); + var context = EmitAll(RunnerContext(load.Root))["AppDbContext.g.cs"]; + var line = context.Split('\n').Single(l => l.Contains("Entity().Property(x => x.Status)")); + Assert.Contains("? \"open_v1\" :", line); + Assert.Contains("UnmappedEnumStoredValue<", line); + } + [Theory] [InlineData(true)] [InlineData(false)] diff --git a/server/csharp/MetaObjects.Codegen/ReportRows.cs b/server/csharp/MetaObjects.Codegen/ReportRows.cs index 71dc443208..5212c8730a 100644 --- a/server/csharp/MetaObjects.Codegen/ReportRows.cs +++ b/server/csharp/MetaObjects.Codegen/ReportRows.cs @@ -62,6 +62,8 @@ public static class ReportRows FIELD_ATTR_CURRENCY, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, + // rc.21: a @stringValueMap enum is read through its stored strings, here as everywhere. + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java index 25216933fe..490297e3da 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java +++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportReadModel.java @@ -82,6 +82,7 @@ public final class ReportReadModel extends ReportMetaObject CurrencyField.ATTR_CURRENCY, EnumField.ATTR_VALUES, EnumField.ATTR_INT_VALUE_MAP, + EnumField.ATTR_STRING_VALUE_MAP, MetaField.ATTR_MAX_LENGTH, MetaField.ATTR_PRECISION, MetaField.ATTR_SCALE, diff --git a/server/python/src/metaobjects/meta/core/reporting/report_read_model.py b/server/python/src/metaobjects/meta/core/reporting/report_read_model.py index aee8c8c22f..f438df4419 100644 --- a/server/python/src/metaobjects/meta/core/reporting/report_read_model.py +++ b/server/python/src/metaobjects/meta/core/reporting/report_read_model.py @@ -39,6 +39,7 @@ FIELD_ATTR_CURRENCY, FIELD_ATTR_FILTERABLE, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_OBJECT_REF, FIELD_ATTR_PRECISION, @@ -63,6 +64,7 @@ FIELD_ATTR_CURRENCY, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, diff --git a/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts b/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts index 03381467c8..ce1ffb5272 100644 --- a/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts +++ b/server/typescript/packages/metadata/src/core/reporting/report-read-model.ts @@ -37,6 +37,7 @@ import { FIELD_ATTR_CURRENCY, FIELD_ATTR_FILTERABLE, FIELD_ATTR_INT_VALUE_MAP, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_REQUIRED, @@ -59,6 +60,8 @@ const CARRIED_ATTRS = [ FIELD_ATTR_CURRENCY, FIELD_ATTR_VALUES, FIELD_ATTR_INT_VALUE_MAP, + // rc.21: a @stringValueMap enum is read through its stored strings, here as everywhere. + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_MAX_LENGTH, FIELD_ATTR_PRECISION, FIELD_ATTR_SCALE, diff --git a/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts b/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts index 24c0257d6a..7c2f520772 100644 --- a/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts +++ b/server/typescript/packages/runtime-ts/test/object-manager-report.test.ts @@ -347,3 +347,24 @@ describe("ObjectManager reads a view-backed report (FR-044)", () => { expect(await om.count("Sale")).toBe(2); }); }); + +// rc.21 fix round (I3): a report dimension over a @stringValueMap enum reads and filters as its +// member — the row model carries the map from its type source, as it carries @intValueMap. +describe("a report dimension over a @stringValueMap enum", () => { + test("reads the member and filters by its stored string; an unknown stored value throws", async () => { + const model = JSON.parse(JSON.stringify(SALES).replace( + `"@intValueMap":{"OPEN":1,"CLOSED":2}`, `"@stringValueMap":{"OPEN":"open_v1","CLOSED":"closed_v1"}`)); + const result = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); + expect(result.errors.map((e) => e.message)).toEqual([]); + if (!isMetaRoot(result.root)) throw new Error("not a root"); + const driver = inMemoryDriver({ + seed: { v_sales_by_status: [{ status: "open_v1", sales: 4, revenue: 4000 }, { status: "closed_v1", sales: 6, revenue: 9000 }] }, + pkFields: { v_sales_by_status: ["status"] }, + }); + const om = new ObjectManager({ metadata: result.root, driver }); + expect(await om.findMany("SalesByStatus", { status: "OPEN" })).toEqual([{ status: "OPEN", sales: 4, revenue: 4000 }]); + const bad = new ObjectManager({ metadata: result.root, driver: inMemoryDriver({ + seed: { v_sales_by_status: [{ status: "lost", sales: 1, revenue: 1 }] }, pkFields: { v_sales_by_status: ["status"] } }) }); + await expect(bad.findMany("SalesByStatus")).rejects.toThrow(/no member in @stringValueMap/); + }); +}); From 4a1c3c605d8a5a9c15c52ae6ad42045ab6355a8a Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 16:53:56 -0500 Subject: [PATCH 184/267] fix: unmapped @stringValueMap writes fail loud; nav match by sole navigation; fragment-dropped derived columns - Writing a member with no stored string throws in every port (TS runtime, Drizzle codec, OMDB, Python), as C# already did: under @dbCheck: false no CHECK stands behind the column. A Python filter still passes it through. - The Spring shared-enum path keeps the map (dbValue/fromDbValue). - A flattened-member reference uses the owned type's only navigation to the target whatever its name; with several, the one over the declared FK, and none of those throws at model build. - A write-through entity declares the derived columns its abstract-entity fragment drops. - The owned template copies are resynced. Co-Authored-By: Claude Opus 5.5 --- .../codegen/templates/drizzle-schema.ts | 65 +++++++++++++++++-- .../codegen/templates/enum-int-codec.ts | 11 +++- .../codegen/templates/drizzle-schema.ts | 65 +++++++++++++++++-- .../codegen/templates/enum-int-codec.ts | 11 +++- examples/showcase/site-payload.json | 2 +- .../NamesGeneratorTests.cs | 28 ++++++++ .../MetaObjects.Codegen/CSharpNaming.cs | 6 ++ .../Generators/DbContextGenerator.cs | 10 ++- .../generator/spring/Fr019SharedEnum.java | 12 +++- .../spring/SpringIntBackedEnumTest.java | 29 +++++++++ .../manager/db/codec/JdbcCodecs.java | 17 ++++- server/python/src/metaobjects/core_types.py | 4 +- .../src/metaobjects/runtime/object_manager.py | 15 ++++- .../packages/codegen-ts/src/names.ts | 8 +++ .../src/templates/enum-int-codec.ts | 11 +++- .../test/names-derived-field.test.ts | 22 +++++++ .../packages/runtime-ts/src/type-coercer.ts | 11 +++- .../test/string-value-map-codec.test.ts | 21 ++++-- .../src/templates/drizzle-schema.ts | 65 +++++++++++++++++-- .../src/templates/enum-int-codec.ts | 11 +++- 20 files changed, 382 insertions(+), 42 deletions(-) diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index 39af23323d..64434dc4c9 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -26,12 +26,13 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; @@ -267,8 +268,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -750,3 +755,55 @@ function renderColumn( ? code` // ${spec.leadingComment}\n${columnLine}` : columnLine; } + +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
    ___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): Array<{ name: Code; expr: Code }> | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: Array<{ name: Code; expr: Code }> = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + const name = typeof declared === "string" && declared.length > 0 + ? declared + : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + }); + return out; +} diff --git a/examples/advanced-modeling/codegen/templates/enum-int-codec.ts b/examples/advanced-modeling/codegen/templates/enum-int-codec.ts index b002b88a05..c9392157cb 100644 --- a/examples/advanced-modeling/codegen/templates/enum-int-codec.ts +++ b/examples/advanced-modeling/codegen/templates/enum-int-codec.ts @@ -148,7 +148,8 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter * comparison binds the stored string too. An unmapped stored string throws on read, for the reason - * the int codec's does. + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). */ function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); @@ -158,7 +159,13 @@ const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, const ${t.fromIntConstName}: Record = { ${fromEntries} }; const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ dataType: () => ${JSON.stringify(t.dataType)}, - toDriver: (value) => ${t.toIntConstName}[value], + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, fromDriver: (value) => { const member = ${t.fromIntConstName}[value]; if (member === undefined) { diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index 39af23323d..64434dc4c9 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -26,12 +26,13 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; @@ -267,8 +268,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -750,3 +755,55 @@ function renderColumn( ? code` // ${spec.leadingComment}\n${columnLine}` : columnLine; } + +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
    ___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): Array<{ name: Code; expr: Code }> | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: Array<{ name: Code; expr: Code }> = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + const name = typeof declared === "string" && declared.length > 0 + ? declared + : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + }); + return out; +} diff --git a/examples/showcase/codegen/templates/enum-int-codec.ts b/examples/showcase/codegen/templates/enum-int-codec.ts index b002b88a05..c9392157cb 100644 --- a/examples/showcase/codegen/templates/enum-int-codec.ts +++ b/examples/showcase/codegen/templates/enum-int-codec.ts @@ -148,7 +148,8 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter * comparison binds the stored string too. An unmapped stored string throws on read, for the reason - * the int codec's does. + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). */ function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); @@ -158,7 +159,13 @@ const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, const ${t.fromIntConstName}: Record = { ${fromEntries} }; const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ dataType: () => ${JSON.stringify(t.dataType)}, - toDriver: (value) => ${t.toIntConstName}[value], + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, fromDriver: (value) => { const member = ${t.fromIntConstName}[value]; if (member === undefined) { diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 91f83a2e98..5637a5287c 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 468, + "fixtures": 469, "corpora": 38, "baseTypes": 17 }, diff --git a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs index 924e8f6d5f..41e9dc9451 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/NamesGeneratorTests.cs @@ -157,6 +157,34 @@ public void A_derived_field_of_a_table_entity_has_no_column_constant() Assert.Contains("public const string DoubledColumn = \"doubled\";", view); } + // rc.21 fix round (M8): an abstract-entity fragment drops its derived field, so a write-through + // extender (whose read view HAS that column) declares the constant itself. + [Fact] + public void A_write_through_extender_declares_the_derived_column_its_fragment_drops() + { + const string model = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Tracked", "abstract": true, "children": [ + { "field.int": { "name": "score" } }, + { "field.boolean": { "name": "isHigh", "children": [ { "origin.computed": { "@expr": { + "op": "gte", "left": { "field": "score" }, "right": { "value": 4 } } } } ] } } ] } }, + { "object.entity": { "name": "Account", "extends": "Tracked", "children": [ + { "source.rdb": { "@table": "accounts" } }, + { "source.rdb": { "name": "read", "@kind": "view", "@view": "v_accounts", "@role": "replica" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.projection": { "name": "HighAccounts", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_high_accounts" } }, + { "field.long": { "name": "id", "extends": "Account.id" } }, + { "identity.primary": { "name": "id", "extends": "Account.id" } } ] } } ] } } + """; + var files = new NamesGenerator().Generate(Ctx(Load(model))).ToList(); + var tracked = files.Single(f => f.Path.EndsWith("TrackedNames.g.cs", StringComparison.Ordinal)).Content; + Assert.DoesNotContain("IsHigh", tracked); + var account = files.Single(f => f.Path.EndsWith("AccountNames.g.cs", StringComparison.Ordinal)).Content; + Assert.Contains("public const string IsHighColumn = \"is_high\";", account); + } + [Fact] public void An_explicit_column_wins_over_the_naming_strategy() { diff --git a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs index f4a0fc7e6b..83219e1b24 100644 --- a/server/csharp/MetaObjects.Codegen/CSharpNaming.cs +++ b/server/csharp/MetaObjects.Codegen/CSharpNaming.cs @@ -575,6 +575,12 @@ public static bool HasPrimarySource(MetaObject obj) => ownFields[f.Name] = FieldNamesOf(f, strategy); var superObj = NamesArtifactSuperOf(obj); + // rc.21 fix round (M8): an abstract-entity fragment leaves its derived fields out (they are + // no column of the tables extending it), so an object whose derived fields ARE columns (a + // write-through entity's read view) declares the ones it inherits itself, or it would lose them. + if (!noColumn && superObj is not null && superObj.IsEntity() && superObj.IsAbstract) + foreach (var f in obj.Fields().Where(f => f.IsDerived() && !ownFields.ContainsKey(f.Name))) + ownFields[f.Name] = FieldNamesOf(f, strategy); // Identity of the resolved source NODE, not equality of the resolved strings: a // divergence guard is exactly what this codebase forbids here, and the question // being asked is structural — did this object declare a source, or is it using its diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index 9920adea16..cba6b886c5 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -1593,10 +1593,16 @@ private IEnumerable FlattenedMemberReferenceConfig( // columns would then be a second relationship, with a shadow FK beside it (`_1`). // So the relationship is configured THROUGH the navigation EF found over these FK properties, // when there is one, and navigation-less otherwise. Read from the model, not reflected. + // Which navigation: none to the target, none; exactly one, that one (whatever its name, so + // `HomeCountry` over `CountryId` matches too); several, the one whose convention FK is these + // properties — and with no such one the model build THROWS, naming the owner, rather than + // configure a second relationship beside them (rc.21 fix round, M6). var linq = "global::System.Linq.Enumerable"; var fkNames = string.Join(", ", props.Select(p => $"\"{p}\"")); - var navigation = $"{linq}.FirstOrDefault(b.OwnedEntityType.GetNavigations(), n => n.TargetEntityType.ClrType == typeof({targetRef}) " - + $"&& {linq}.SequenceEqual({linq}.Select(n.ForeignKey.Properties, p => p.Name), new[] {{ {fkNames} }}))?.Name"; + var toTarget = $"{linq}.Where(b.OwnedEntityType.GetNavigations(), n => n.TargetEntityType.ClrType == typeof({targetRef}))"; + var byFk = $"{linq}.FirstOrDefault({toTarget}, n => {linq}.SequenceEqual({linq}.Select(n.ForeignKey.Properties, p => p.Name), new[] {{ {fkNames} }}))"; + var ambiguous = $"new global::System.InvalidOperationException(\"{CSharpNaming.CSharpStringLiteral($"{entity.Name}.{nav} has several navigations to {target.Name} and none over {string.Join(", ", props)}: name the one this reference uses with that foreign key, or remove the others.")}\")"; + var navigation = $"({linq}.Count({toTarget}) == 0 ? null : {linq}.Count({toTarget}) == 1 ? {linq}.First({toTarget}) : ({byFk} ?? throw {ambiguous}))?.Name"; return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.HasOne<{targetRef}>({navigation})" + $".WithMany().HasForeignKey({ForeignKeyExpression("e", props)})" + PrincipalKeyCall(reference, target) diff --git a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java index 1e7021ce1d..9072857681 100644 --- a/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java +++ b/server/java/codegen-spring/src/main/java/com/metaobjects/generator/spring/Fr019SharedEnum.java @@ -72,7 +72,13 @@ private Fr019SharedEnum() { /* no instances */ } */ public record SharedEnum(String name, List values, boolean provided, String metaPackage, String javaPackage, - Map intValueMap) { } + Map intValueMap, Map stringValueMap) { + /** The record without a {@code @stringValueMap} (rc.21), for callers that predate it. */ + public SharedEnum(String name, List values, boolean provided, String metaPackage, String javaPackage, + Map intValueMap) { + this(name, values, provided, metaPackage, javaPackage, intValueMap, null); + } + } /** Per-port codegen config for resolving a {@code @provided} enum's Java namespace (ADR-0001). * Generator args, never metadata: a package→namespace map (keyed by metadata package in @@ -128,7 +134,7 @@ public static SharedEnum sharedEnumForField(MetaField field) { String name = SpringNaming.capitalize(split[1]); String metaPackage = metaPackageOf(decl.getName()); return new SharedEnum(name, values, isProvided((EnumField) decl), metaPackage, javaPackage, - SpringTypeMapper.intValueMap((EnumField) decl)); + SpringTypeMapper.intValueMap((EnumField) decl), SpringTypeMapper.stringValueMap((EnumField) decl)); } /** The declaration's metadata package in {@code ::} form, stripped of the trailing {@code ::Name} @@ -213,7 +219,7 @@ public static void emitMaterialized(MetaDataLoader loader, Path outRoot) { } src.append("/** GENERATED — shared enum ").append(shared.name()) .append(". Do not hand-edit; regenerated from metadata. */\n"); - src.append(SpringTypeMapper.enumDeclaration(shared.name(), shared.values(), shared.intValueMap())) + src.append(SpringTypeMapper.enumDeclaration(shared.name(), shared.values(), shared.intValueMap(), shared.stringValueMap())) .append("\n"); try { Path outFile = outRoot.resolve(shared.javaPackage().replace('.', '/')) diff --git a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java index 8021b7b0a7..82e7dfbc09 100644 --- a/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java +++ b/server/java/codegen-spring/src/test/java/com/metaobjects/generator/spring/SpringIntBackedEnumTest.java @@ -72,4 +72,33 @@ public void anIntBackedEnumMapsBothWaysAndRefusesAnUnmappedValue() throws Except } } } + + // rc.21: a @stringValueMap enum carries its stored STRING both ways, and a shared declaration + // (Fr019SharedEnum) keeps it (fix round M4). + @Test + public void aStringValueMapEnumMapsBothWaysAndRefusesAnUnmappedValue() throws Exception { + Map stored = new LinkedHashMap<>(); + stored.put("DRAFT", "draft_v1"); + stored.put("PUBLISHED", "published_v1"); + String decl = SpringTypeMapper.enumDeclaration("Phase", List.of("DRAFT", "PUBLISHED"), null, stored); + Path src = tmp.newFolder("src2").toPath(); + Path out = tmp.newFolder("out2").toPath(); + Path file = src.resolve("Phase.java"); + Files.writeString(file, decl + "\n"); + assertEquals("generated enum must compile", 0, + ToolProvider.getSystemJavaCompiler().run(null, null, null, "-d", out.toString(), file.toString())); + try (URLClassLoader cl = new URLClassLoader(new URL[]{ out.toUri().toURL() }, null)) { + Class phase = cl.loadClass("Phase"); + assertEquals("PUBLISHED", ((Enum) phase.getMethod("fromDbValue", String.class).invoke(null, "published_v1")).name()); + assertEquals("draft_v1", phase.getMethod("dbValue").invoke(Enum.valueOf(phase.asSubclass(Enum.class), "DRAFT"))); + try { + phase.getMethod("fromDbValue", String.class).invoke(null, "lost"); + fail("an unmapped stored value must throw"); + } catch (InvocationTargetException e) { + assertTrue(e.getCause() instanceof IllegalArgumentException); + } + } + Fr019SharedEnum.SharedEnum shared = new Fr019SharedEnum.SharedEnum("Phase", List.of("DRAFT", "PUBLISHED"), false, "acme", "acme", null, stored); + assertEquals(stored, shared.stringValueMap()); + } } diff --git a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java index c48f5718a9..e11b589c0f 100644 --- a/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java +++ b/server/java/omdb/src/main/java/com/metaobjects/manager/db/codec/JdbcCodecs.java @@ -493,11 +493,22 @@ static final class EnumCodec implements JdbcFieldCodec { s.setNull(j, Types.VARCHAR); return; } - // rc.21: a @stringValueMap enum binds the member's stored string; an unmapped - // member is bound unchanged, so the column's CHECK rejects it. + // rc.21: a @stringValueMap enum binds the member's stored string. An unmapped + // member throws (every port): no CHECK need stand behind it (@dbCheck: false), + // and binding the symbol would store a spelling the column does not hold. Map storedMap = stringValueMap(f); String member = v.toString(); - s.setString(j, storedMap == null ? member : storedMap.getOrDefault(member, member)); + if (storedMap == null) { + s.setString(j, member); + return; + } + String stored = storedMap.get(member); + if (stored == null) { + throw new SQLException("field.enum '" + f.getName() + "' cannot write " + member + + ": it has no stored string in @" + EnumField.ATTR_STRING_VALUE_MAP + + " — the value is not one of the members the model declares."); + } + s.setString(j, stored); return; } refuseArray(f); diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index 336e49d7ed..d44f12ed56 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -660,8 +660,8 @@ def _register_subtypes( ), # rc.21 — @stringValueMap: optional per-member stored strings ({member: str}) of a # string-stored enum (the string twin of @intValueMap). Content rules in - # _validate_enum_values (Rule 5). Python persists no string enum through it yet: - # the ObjectManager refuses an entity carrying one (see object_manager.py). + # _validate_enum_values (Rule 5). The ObjectManager writes and reads through it + # (see object_manager.py: _coerce_write_value, _decode_read_value). AttrSchema( name=FIELD_ATTR_STRING_VALUE_MAP, value_type=ATTR_SUBTYPE_PROPERTIES, diff --git a/server/python/src/metaobjects/runtime/object_manager.py b/server/python/src/metaobjects/runtime/object_manager.py index eba3361c5a..f3d6997569 100644 --- a/server/python/src/metaobjects/runtime/object_manager.py +++ b/server/python/src/metaobjects/runtime/object_manager.py @@ -1125,13 +1125,13 @@ def _coerce_filter_value(field: MetaField, value: Any) -> Any: value = True elif lowered in ("false", "0"): value = False - return _coerce_write_value(field, value) + return _coerce_write_value(field, value, for_filter=True) _INT_TEXT = _re.compile(r"^\s*-?\d+\s*$") -def _coerce_write_value(field: MetaField, value: Any) -> Any: +def _coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = False) -> Any: if value is None: return None sub = field.sub_type @@ -1225,7 +1225,16 @@ def _coerce_write_value(field: MetaField, value: Any) -> Any: # loader refuses it on an array). An unmapped member passes through, as above. stored_map = _string_value_map(field) if stored_map is not None and isinstance(value, str): - return stored_map.get(value, value) + if value in stored_map or for_filter: + # A filter on a member that does not exist matches nothing, honestly. + return stored_map.get(value, value) + # Written, an unmapped member raises (rc.21 ruling, every port): no CHECK need hold + # behind it (@dbCheck: false), and storing the symbol would write a spelling the + # column does not hold. + raise ValueError( + f"field.enum '{field.name}' cannot write {value!r}: it has no stored string in " + f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} — the value is not one of the members the model declares." + ) # Everything else (string / int / long / double / float / boolean / enum) # is already the native type pg8000 binds directly. diff --git a/server/typescript/packages/codegen-ts/src/names.ts b/server/typescript/packages/codegen-ts/src/names.ts index c0beba56e2..15331ab8a6 100644 --- a/server/typescript/packages/codegen-ts/src/names.ts +++ b/server/typescript/packages/codegen-ts/src/names.ts @@ -383,6 +383,14 @@ export function resolveObjectNames( } const superObj = namesArtifactSuperOf(obj); + // rc.21 fix round (M8): an abstract-entity fragment leaves its derived fields out (no column of + // the tables extending it), so an object whose derived fields ARE columns (a write-through + // entity's read view) declares the ones it inherits itself. + if (superObj !== undefined && superObj.subType === OBJECT_SUBTYPE_ENTITY && superObj.isAbstract) { + for (const f of obj.fields()) { + if (f.isDerived() && !columnless(f) && ownFields[f.name] === undefined) ownFields[f.name] = fieldNamesOf(f, strategy); + } + } const superNames: SuperNames | undefined = superObj === undefined ? undefined : { name: superObj.name, package: effectivePackage(superObj) }; diff --git a/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts b/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts index 111793d921..75c771c9a5 100644 --- a/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts +++ b/server/typescript/packages/codegen-ts/src/templates/enum-int-codec.ts @@ -148,7 +148,8 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter * comparison binds the stored string too. An unmapped stored string throws on read, for the reason - * the int codec's does. + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). */ function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); @@ -158,7 +159,13 @@ const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, const ${t.fromIntConstName}: Record = { ${fromEntries} }; const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ dataType: () => ${JSON.stringify(t.dataType)}, - toDriver: (value) => ${t.toIntConstName}[value], + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, fromDriver: (value) => { const member = ${t.fromIntConstName}[value]; if (member === undefined) { diff --git a/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts b/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts index 53ac29c557..0aa12da32a 100644 --- a/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts +++ b/server/typescript/packages/codegen-ts/test/names-derived-field.test.ts @@ -33,3 +33,25 @@ describe("names of a derived field", () => { expect(resolveObjectNames(obj("AccountView"))!.fields["doubled"]?.column).toBe("doubled"); }); }); + +// rc.21 fix round (M8): a write-through extender declares the derived column its fragment drops. +test("a write-through extender of an abstract entity keeps its inherited derived column", async () => { + const model = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Tracked", abstract: true, children: [ + { "field.int": { name: "score" } }, + { "field.boolean": { name: "isHigh", children: [ { "origin.computed": { "@expr": { + op: "gte", left: { field: "score" }, right: { value: 4 } } } } ] } } ] } }, + { "object.entity": { name: "Account", extends: "Tracked", children: [ + { "source.rdb": { "@table": "accounts" } }, + { "source.rdb": { name: "read", "@kind": "view", "@view": "v_accounts", "@role": "replica" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.projection": { name: "HighAccounts", "@filter": { isHigh: true }, children: [ + { "source.rdb": { "@kind": "view", "@view": "v_high_accounts" } }, + { "field.long": { name: "id", extends: "Account.id" } }, + { "identity.primary": { name: "id", extends: "Account.id" } } ] } } ] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(model))]); + expect(errors).toEqual([]); + const account = root.objects().find((o) => o.name === "Account" && isMetaObject(o)) as MetaObject; + expect(resolveObjectNames(account)!.ownFields["isHigh"]?.column).toBe("is_high"); +}); diff --git a/server/typescript/packages/runtime-ts/src/type-coercer.ts b/server/typescript/packages/runtime-ts/src/type-coercer.ts index fc85e2c345..272d262778 100644 --- a/server/typescript/packages/runtime-ts/src/type-coercer.ts +++ b/server/typescript/packages/runtime-ts/src/type-coercer.ts @@ -135,9 +135,18 @@ function encodeStoredStringEnums(entity: MetaData, row: Row): Row { let out: Row | null = null; for (const child of entity.children()) { if (child.type !== TYPE_FIELD || child.subType !== FIELD_SUBTYPE_ENUM) continue; - if (stringValueMapOf(child) === undefined || !(child.name in row)) continue; + const map = stringValueMapOf(child); + if (map === undefined || !(child.name in row)) continue; const raw = row[child.name]; if (typeof raw !== "string") continue; + // An unmapped member THROWS (rc.21 ruling, every port): no CHECK need stand behind it + // (@dbCheck: false), and writing the symbol would store a spelling the column does not hold. + if (typeof map[raw] !== "string") { + throw new Error( + `field.enum '${child.name}' cannot write '${raw}': it has no stored string in ` + + `@stringValueMap (declared: ${JSON.stringify(map)}) — the value is not one of the members the model declares.`, + ); + } out ??= { ...row }; out[child.name] = storedEnumValue(child, raw); } diff --git a/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts index f5b7fc7a4d..ae6de4cab9 100644 --- a/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts +++ b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts @@ -8,20 +8,20 @@ import { compileFilter } from "../src/query-builder.js"; async function upload(): Promise { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Upload", children: [ - { "source.rdb": { "@table": "uploads" } }, + { "object.entity": { name: "Article", children: [ + { "source.rdb": { "@table": "articles" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "status", "@values": ["Pending", "Delivered"], "@stringValueMap": { Pending: "pending", Delivered: "delivered" } } }, + { "field.enum": { name: "status", "@values": ["Draft", "Published"], "@stringValueMap": { Draft: "draft", Published: "published" } } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } } ] } }))]); expect(errors).toEqual([]); - return root.findObject("Upload")!; + return root.findObject("Article")!; } describe("@stringValueMap — ObjectManager codec", () => { test("writes the stored string and reads the member", async () => { const entity = await upload(); - expect(coerceRowOnWrite(entity, { id: 1, status: "Delivered" }, "postgres")["status"]).toBe("delivered"); - expect(coerceRowOnRead(entity, { id: 1, status: "delivered" }, "postgres")["status"]).toBe("Delivered"); + expect(coerceRowOnWrite(entity, { id: 1, status: "Published" }, "postgres")["status"]).toBe("published"); + expect(coerceRowOnRead(entity, { id: 1, status: "published" }, "postgres")["status"]).toBe("Published"); }); test("an unmapped stored string read back throws", async () => { @@ -31,6 +31,13 @@ describe("@stringValueMap — ObjectManager codec", () => { test("a filter binds the stored string", async () => { const entity = await upload(); - expect(JSON.stringify(compileFilter(entity, { status: "Pending" }))).toContain('"pending"'); + expect(JSON.stringify(compileFilter(entity, { status: "Draft" }))).toContain('"draft"'); + }); +}); + +describe("@stringValueMap — an unmapped member", () => { + test("is refused on write, naming the field", async () => { + const entity = await upload(); + expect(() => coerceRowOnWrite(entity, { id: 1, status: "Archived" }, "postgres")).toThrow(/cannot write 'Archived'/); }); }); diff --git a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts index 39af23323d..64434dc4c9 100644 --- a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts @@ -26,12 +26,13 @@ import { dialectModule } from "@metaobjectsdev/codegen-ts/engine"; import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; -import { resolveTableSchema, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; import { renderRelationsBlock } from "./relations-block.js"; import { renderDocsFor } from "./jsdoc.js"; -import { collectTphSubtypeFields, tphConcreteSubtypes } from "./tph-discriminator.js"; +import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-discriminator.js"; import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; @@ -267,8 +268,12 @@ export function renderDrizzleSchema( ); columnLines.push(fieldDocs ? code` ${fieldDocs}\n${columnLine}` : columnLine); // Enum CHECK constraints stay valid under TPH: `NULL IN (...)` is NULL - // (not false), so other-subtype rows with NULL pass the check. - if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); + // (not false), so other-subtype rows with NULL pass the check. Sibling subtypes that + // declare this column with DIFFERENT checks (rc.21 fix round, I1) each get their own, + // guarded by their discriminator values — exactly as `meta migrate` derives them. + const guarded = guardedSiblingEnumChecks(obj, child.name, tableName, ctx); + if (guarded !== undefined) checkConstraints.push(...guarded); + else if (spec.checkConstraint !== undefined) checkConstraints.push(checkEntry(child, spec)); } // Build all table callback entries @@ -750,3 +755,55 @@ function renderColumn( ? code` // ${spec.leadingComment}\n${columnLine}` : columnLine; } + +/** + * rc.21 fix round (I1) — the enum CHECKs of a TPH column several sibling subtypes declare with + * different checks (each owner a distinct field node), one per owner, guarded by the discriminator + * values of the subtypes carrying that node and named `
    ___chk` (a declared + * `@constraintName` kept): the text `meta migrate` derives (expected-schema.ts buildChecks), up to + * the quoting its comparator ignores. Undefined when one node owns the column, or every owner's + * CHECK is the same: the caller emits the plain one. + */ +function guardedSiblingEnumChecks( + obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, +): Array<{ name: Code; expr: Code }> | undefined { + const plan = tphPlan(obj, ctx.loadedRoot); + if (plan === null) return undefined; + const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); + const owners: { node: MetaField; values: string[] }[] = []; + for (const st of subs) { + // ADR-0039: resolving — a field on an abstract level or a parent subtype is a column too. + const node = st.entity.fields().find((f) => f.name === fieldName); + if (node === undefined) continue; + const owner = owners.find((o) => o.node === node); + if (owner === undefined) owners.push({ node, values: [st.value] }); + else owner.values.push(st.value); + } + if (owners.length < 2) return undefined; + const specs = owners.map((o) => mapColumnType(o.node, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode)); + if (specs.every((sp) => sp.checkConstraint === specs[0]!.checkConstraint)) return undefined; + const disc = obj.fields().find((f) => f.name === plan.discriminatorField); + const discCol = disc === undefined ? plan.discriminatorField + : mapColumnType(disc, ctx.dialect, ctx.columnNamingStrategy, ctx.timestampMode).dbName; + const literal = (value: string): string => { + const ints = disc === undefined ? undefined : intValueMapOf(disc); + const n = ints?.[value]; + if (typeof n === "number") return String(n); + const stored = disc === undefined ? value : storedEnumValue(disc, value); + return `'${stored.replace(/'/g, "''")}'`; + }; + const out: Array<{ name: Code; expr: Code }> = []; + owners.forEach((o, i) => { + const check = specs[i]!.checkConstraint; + if (check === undefined) return; + const unless = o.values.length === 1 + ? `"${discCol}" <> ${literal(o.values[0]!)}` + : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); + const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + const name = typeof declared === "string" && declared.length > 0 + ? declared + : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + }); + return out; +} diff --git a/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts b/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts index b002b88a05..c9392157cb 100644 --- a/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts +++ b/server/typescript/packages/test-generators/src/templates/enum-int-codec.ts @@ -148,7 +148,8 @@ const ${t.fnConstName} = ${customTypeSym}<{ data: (${union})[]; driverData: stri * varchar(n) `meta migrate` creates) holds each member's stored string, the TS side the member. * Encoded on bind and decoded on read at the column, exactly as the int-backed codec, so a filter * comparison binds the stored string too. An unmapped stored string throws on read, for the reason - * the int codec's does. + * the int codec's does, and an unmapped member throws on write (rc.21 ruling: no CHECK need stand + * behind it under @dbCheck: false). */ function renderStoredStringCodec(t: EnumIntCustomType, stored: Record, customTypeSym: unknown, union: string): Code { const toEntries = t.members.map((m) => `${JSON.stringify(m)}: ${JSON.stringify(stored[m])}`).join(", "); @@ -158,7 +159,13 @@ const ${t.toIntConstName} = { ${toEntries} } as const satisfies Record<${union}, const ${t.fromIntConstName}: Record = { ${fromEntries} }; const ${t.fnConstName} = ${customTypeSym}<{ data: ${union}; driverData: string }>({ dataType: () => ${JSON.stringify(t.dataType)}, - toDriver: (value) => ${t.toIntConstName}[value], + toDriver: (value) => { + const stored = ${t.toIntConstName}[value]; + if (stored === undefined) { + throw new Error(\`unmapped ${t.fnConstName} member: \${String(value)}\`); + } + return stored; + }, fromDriver: (value) => { const member = ${t.fromIntConstName}[value]; if (member === undefined) { From 9fbf57eb12ea4a65a0cc80316b36b038d327e9f2 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 16:54:06 -0500 Subject: [PATCH 185/267] docs, tests: neutral examples for the rc.21 vocabulary; U7 marked breaking The @stringValueMap registry description, docs, fixtures and tests, and the U1/U9 tests and CHANGELOG entries, use neutral domain names. The U7 entry is labelled breaking with an upgrade note; the U9 entry says Java and Python keep their message and carries the U1/U9 naming note. Adds the M6 and write-refusal tests. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 52 ++++++++++++------- docs/features/field-types.md | 8 +-- .../expected.d1.json | 14 ++--- .../expected.postgres.json | 14 ++--- .../expected.postgres.skip-redundant.json | 14 ++--- .../expected.sqlite.json | 14 ++--- .../expected.sqlite.skip-redundant.json | 14 ++--- .../input/meta.stored.json | 8 +-- .../enum-string-value-map/expected.json | 28 +++++----- .../input/meta.enums.json | 14 ++--- .../input/meta.enums.json | 2 +- .../input/meta.enums.json | 6 +-- .../input/meta.enums.json | 6 +-- .../input/meta.enums.json | 8 +-- .../metamodel-docs/expected/types/field.md | 2 +- .../expected-registry.json | 2 +- .../ReverseHopHintTests.cs | 30 +++++------ .../SuperResolveTests.cs | 26 +++++----- .../EfModelGapsTests.cs | 42 +++++++++++---- .../MetaObjects/SpecMetamodel/field.json | 2 +- ...otlinExposedTableStringValueMapEnumTest.kt | 4 +- .../enum-string-value-map/meta.shop.json | 8 +-- .../src/metaobjects/spec_metamodel/field.json | 2 +- .../test_object_manager_string_value_map.py | 20 ++++--- .../test/drizzle-enum-stringvaluemap.test.ts | 10 ++-- .../core/field/field-definition.embedded.ts | 2 +- .../test/unresolved-super-hint.test.ts | 24 ++++----- .../migrate-ts/test/string-value-map.test.ts | 22 ++++---- site-reference/types/field.html | 2 +- spec/metamodel/field.json | 2 +- 30 files changed, 223 insertions(+), 179 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81af1c45f6..1ebadcb3ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,7 +25,7 @@ vocabulary; upgrade every port together. - **`@stringValueMap`: a field.enum member's stored string (rc.21).** A string-stored enum may declare the string each member is stored as, `{ member: string }`, for a legacy column whose - spelling differs from the member symbols (`pending`, `Key_File_Path`). The generated native + spelling differs from the member symbols (lowercase `draft`, `LEGACY_A`). The generated native type and the wire keep the members; the column, its CHECK, its length, a `@default` and a `@condition` or `@equals` literal hold the stored strings. It is the string twin of `@intValueMap` (attr subtype `properties`): keys must match `@values` exactly, values are @@ -37,8 +37,11 @@ vocabulary; upgrade every port together. Drizzle column (a member/stored-string codec), the TypeScript runtime ObjectManager (write, read, filter) and the view, report and Cube lowerings; by the Java OMDB codec; by the Kotlin Exposed table (a VARCHAR `customEnumeration`); by the generated Spring enum (`dbValue()` / - `fromDbValue(String)`, for a hand-written repository); and by the Python ObjectManager. A - stored string that maps to no member throws on read in every port. `metamodelVersion` stays + `fromDbValue(String)`, for a hand-written repository, a shared declaration included); and by the + Python ObjectManager. A view-backed report's row carries it from its type source, in every + port. A stored string that maps to no member throws on read, and a member with no stored string + throws on write, in every port (the map is total, so only a value outside `@values` can reach + that). `metamodelVersion` stays `1.3`: the addition lands in the same unreleased minor. Fixtures `fixtures/conformance/enum-string-value-map` and four `error-enum-stringvaluemap-*`; the shared CHECK corpus gains `input/meta.stored.json`. @@ -583,37 +586,48 @@ vocabulary; upgrade every port together. owned type also carries a `Country` navigation (an adopter's partial class, say), EF's convention builds a relationship from it as the owned type joins the model, so the navigation-less call made a second one, with a shadow FK property (`CountryId1`) and a second - foreign key. The relationship is now configured through the navigation EF found on the owned - type over the same FK properties, read from the model at build time (`OwnsOne(x => x.Address, - b => b.HasOne()…)`), and navigation-less when there is - none. One foreign key, no shadow column, and `@onDelete` / `@constraintName` land on it. + foreign key. The relationship is now configured through the owned type's navigation to the + target, read from the model at build time (`OwnsOne(x => x.Address, b => + b.HasOne()…)`): its only navigation to the target, + whatever its name (`HomeCountry` over `CountryId` too); with several, the one whose foreign key + is these properties, and with none of those the model build throws, naming the owner; with none, + navigation-less. One foreign key, no shadow column, and `@onDelete` / `@constraintName` land on it. Generated output changes for every reference over a flattened member. -- **Fix, TypeScript and C#: `Names` has no entry for a derived field with no column +- **Breaking, TypeScript and C#: `Names` has no entry for a derived field with no column (rc.21, U7).** A derived (`origin.*`) field of an entity read from its table is no column of that table (a projection that reaches it lowers it inline), yet the names artifact emitted a `…Field`/`…Column` pair (C#) or a `fields..column` (TypeScript) for it, and a `ColumnsByField` entry, all naming a column that does not exist. It now emits no entry for such a field, so code reading one fails to compile instead of querying a missing column. A projection's derived field is a column of its view, and a write-through entity's is a column of - its read view: both keep their entry. Java and Kotlin are unchanged (no entity-derived fields). + its read view: both keep their entry; a write-through entity extending an abstract entity + declares the derived columns it inherits itself, since the abstract fragment drops them. Java + and Kotlin are unchanged (no entity-derived fields). **Upgrade note:** code that reads + `Names.Field` / `Column` (C#), `fields.` (TypeScript) or a + `ColumnsByField` entry for such a field no longer compiles; use `nameof(...)` or the metamodel + name as a literal instead, since there is no column to name. - **Fix, TypeScript and C#: a `@via` hop under a guessed name lists the reverse hops (rc.21, U9).** The first hop from a projection's base entity already walks an `identity.reference` backwards - (`Case.caseHistory` for `CaseHistory.caseId`), named by the holder's collection name, first - letter lowercased. A holder whose `@collectionName` is singular (`CaseHistory`) makes that name - hard to guess, and the refusal (`no such relationship or reference "histories" on Case`) did not - say what it was. It now ends `The reverse hops from Case are: "caseHistory" (walks - CaseHistory.caseId backwards) — …`. No hop name changes: an `@inverseName` spelling is not - accepted, because no registered vocabulary declares one. + (`Order.orderEvent` for `OrderEvent.orderId`), named by the holder's collection name, first + letter lowercased. A holder whose `@collectionName` is singular (`OrderEvent`) makes that name + hard to guess, and the refusal (`no such relationship or reference "events" on Order`) did not + say what it was. It now ends `The reverse hops from Order are: "orderEvent" (walks + OrderEvent.orderId backwards) — …`. No hop name changes: an `@inverseName` spelling is not + accepted, because no registered vocabulary declares one. Java and Python keep their message. + **Naming note (this entry and U1's):** neither was a resolution bug. A dotted `extends` names an + identity by its name (an unnamed `identity.primary` is `primary`), and a reverse hop by the + holder's collection name; both already resolved under those names, and the errors now say what + the names are. - **Fix, TypeScript and C#: a dotted `extends` whose member is missing names the owner's members - (rc.21, U1).** `extends: "Authorization.id"` on an `identity.primary`, where `Authorization` + (rc.21, U1).** `extends: "Shipment.id"` on an `identity.primary`, where `Shipment` inherits its identity from an abstract base, failed with `ERR_UNRESOLVED_SUPER` and the advice to - qualify `Authorization` with its package, although `Authorization` had resolved. The member was + qualify `Shipment` with its package, although `Shipment` had resolved. The member was the problem: an identity declared without a name is named after its subtype (`primary`), and the - inherited one resolves as `Authorization.primary`, which already worked. The error now says - so: `'acme::auth::Authorization' has no identity named "id"; its identity children are: + inherited one resolves as `Shipment.primary`, which already worked. The error now says + so: `'acme::shipping::Shipment' has no identity named "id"; its identity children are: "primary" (identity.primary). An identity.primary declared without a name is named "primary".` The package advice is given only when the owner itself did not resolve. Java and Python keep their message. diff --git a/docs/features/field-types.md b/docs/features/field-types.md index 776b49ac2f..1c7d430d66 100644 --- a/docs/features/field-types.md +++ b/docs/features/field-types.md @@ -249,14 +249,14 @@ Two rules follow from int-backing being a **persistence-layer codec**: **A stored spelling per member (rc.21):** `@stringValueMap` gives each member of a string-stored enum the string its column holds, when the database's spelling is not the -member symbol — a legacy column holding `pending`, or `Key_File_Path`: +member symbol — a legacy column holding lowercase `draft`, or `LEGACY_A`: ```json -{ "field.enum": { "name": "status", "@values": ["Pending", "Delivered"], - "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } } } +{ "field.enum": { "name": "status", "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Published": "published" } } } ``` -The generated enum type and the wire keep the members (`Pending`); the column, its `CHECK`, +The generated enum type and the wire keep the members (`Draft`); the column, its `CHECK`, its length (`@maxLength` must fit the longest stored string), a `@default` and a `@condition` or `@equals` literal hold the stored strings. It is the string twin of `@intValueMap`, with its rules: keys must match `@values` exactly, values are unique non-empty strings, and a shared diff --git a/fixtures/check-constraint-conformance/expected.d1.json b/fixtures/check-constraint-conformance/expected.d1.json index 81c504fc25..18b3c47414 100644 --- a/fixtures/check-constraint-conformance/expected.d1.json +++ b/fixtures/check-constraint-conformance/expected.d1.json @@ -69,18 +69,18 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], - "feeds": [ + "jobs": [ { - "name": "feeds_status_chk", - "expression": "\"status\" IN ('pending', 'done', 'failed')" + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" }, { - "name": "feeds_error_reqwhen_chk", - "expression": "(\"status\" IS NOT 'failed') OR (\"error\" IS NOT NULL)" + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'q_failed') OR (\"error\" IS NOT NULL)" }, { - "name": "feeds_done_at_cmp_chk", - "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" } ], "devices": [ diff --git a/fixtures/check-constraint-conformance/expected.postgres.json b/fixtures/check-constraint-conformance/expected.postgres.json index c86432d996..6f8d742b98 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.json +++ b/fixtures/check-constraint-conformance/expected.postgres.json @@ -73,18 +73,18 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], - "feeds": [ + "jobs": [ { - "name": "feeds_status_chk", - "expression": "\"status\" IN ('pending', 'done', 'failed')" + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" }, { - "name": "feeds_error_reqwhen_chk", - "expression": "(\"status\" IS DISTINCT FROM 'failed') OR (\"error\" IS NOT NULL)" + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS DISTINCT FROM 'q_failed') OR (\"error\" IS NOT NULL)" }, { - "name": "feeds_done_at_cmp_chk", - "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" } ], "devices": [ diff --git a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json index 9377b5e52f..0aa5bbd111 100644 --- a/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.postgres.skip-redundant.json @@ -73,18 +73,18 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], - "feeds": [ + "jobs": [ { - "name": "feeds_status_chk", - "expression": "\"status\" IN ('pending', 'done', 'failed')" + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" }, { - "name": "feeds_error_reqwhen_chk", - "expression": "(\"status\" IS DISTINCT FROM 'failed') OR (\"error\" IS NOT NULL)" + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS DISTINCT FROM 'q_failed') OR (\"error\" IS NOT NULL)" }, { - "name": "feeds_done_at_cmp_chk", - "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" } ], "devices": [ diff --git a/fixtures/check-constraint-conformance/expected.sqlite.json b/fixtures/check-constraint-conformance/expected.sqlite.json index 81c504fc25..18b3c47414 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.json @@ -69,18 +69,18 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], - "feeds": [ + "jobs": [ { - "name": "feeds_status_chk", - "expression": "\"status\" IN ('pending', 'done', 'failed')" + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" }, { - "name": "feeds_error_reqwhen_chk", - "expression": "(\"status\" IS NOT 'failed') OR (\"error\" IS NOT NULL)" + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'q_failed') OR (\"error\" IS NOT NULL)" }, { - "name": "feeds_done_at_cmp_chk", - "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" } ], "devices": [ diff --git a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json index 4368f8ac55..b3b281a83e 100644 --- a/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json +++ b/fixtures/check-constraint-conformance/expected.sqlite.skip-redundant.json @@ -69,18 +69,18 @@ "expression": "(\"level\" <> 2) OR (\"phone\" IS NOT NULL OR \"fax\" IS NOT NULL)" } ], - "feeds": [ + "jobs": [ { - "name": "feeds_status_chk", - "expression": "\"status\" IN ('pending', 'done', 'failed')" + "name": "jobs_status_chk", + "expression": "\"status\" IN ('q_queued', 'q_done', 'q_failed')" }, { - "name": "feeds_error_reqwhen_chk", - "expression": "(\"status\" IS NOT 'failed') OR (\"error\" IS NOT NULL)" + "name": "jobs_error_reqwhen_chk", + "expression": "(\"status\" IS NOT 'q_failed') OR (\"error\" IS NOT NULL)" }, { - "name": "feeds_done_at_cmp_chk", - "expression": "(\"status\" <> 'done') OR (\"done_at\" >= \"started_at\")" + "name": "jobs_done_at_cmp_chk", + "expression": "(\"status\" <> 'q_done') OR (\"done_at\" >= \"started_at\")" } ], "devices": [ diff --git a/fixtures/check-constraint-conformance/input/meta.stored.json b/fixtures/check-constraint-conformance/input/meta.stored.json index b221fc4ca7..84c5358eef 100644 --- a/fixtures/check-constraint-conformance/input/meta.stored.json +++ b/fixtures/check-constraint-conformance/input/meta.stored.json @@ -4,12 +4,12 @@ "children": [ { "object.entity": { - "name": "Feed", + "name": "Job", "children": [ - { "source.rdb": { "@table": "feeds" } }, + { "source.rdb": { "@table": "jobs" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "status", "@required": true, "@values": ["Pending", "Done", "Failed"], - "@stringValueMap": { "Pending": "pending", "Done": "done", "Failed": "failed" } } }, + { "field.enum": { "name": "status", "@required": true, "@values": ["Queued", "Done", "Failed"], + "@stringValueMap": { "Queued": "q_queued", "Done": "q_done", "Failed": "q_failed" } } }, { "field.string": { "name": "error" } }, { "field.timestamp": { "name": "startedAt" } }, { "field.timestamp": { "name": "doneAt" } }, diff --git a/fixtures/conformance/enum-string-value-map/expected.json b/fixtures/conformance/enum-string-value-map/expected.json index b6545a2f1b..f08172f0ad 100644 --- a/fixtures/conformance/enum-string-value-map/expected.json +++ b/fixtures/conformance/enum-string-value-map/expected.json @@ -4,7 +4,7 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ { "field.long": { @@ -14,32 +14,32 @@ { "field.enum": { "name": "status", - "@default": "Pending", + "@default": "Draft", "@stringValueMap": { - "Delivered": "delivered", - "Failed": "failed", - "Pending": "pending" + "Draft": "draft", + "Published": "published", + "Retracted": "retracted" }, "@values": [ - "Pending", - "Delivered", - "Failed" + "Draft", + "Published", + "Retracted" ] } }, { "field.enum": { - "name": "authType", + "name": "channel", "@maxLength": 16, "@stringValueMap": { - "KeyFileContent": "Key_File_Content", - "KeyFilePath": "Key_File_Path", - "None": "None" + "Email": "EMAIL_V1", + "None": "None", + "TextMessage": "SMS_LEGACY" }, "@values": [ "None", - "KeyFilePath", - "KeyFileContent" + "Email", + "TextMessage" ] } }, diff --git a/fixtures/conformance/enum-string-value-map/input/meta.enums.json b/fixtures/conformance/enum-string-value-map/input/meta.enums.json index 62b3ccaad9..8da81e43dc 100644 --- a/fixtures/conformance/enum-string-value-map/input/meta.enums.json +++ b/fixtures/conformance/enum-string-value-map/input/meta.enums.json @@ -4,22 +4,22 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", - "@values": ["Pending", "Delivered", "Failed"], - "@stringValueMap": { "Pending": "pending", "Delivered": "delivered", "Failed": "failed" }, - "@default": "Pending" + "@values": ["Draft", "Published", "Retracted"], + "@stringValueMap": { "Draft": "draft", "Published": "published", "Retracted": "retracted" }, + "@default": "Draft" } }, { "field.enum": { - "name": "authType", - "@values": ["None", "KeyFilePath", "KeyFileContent"], - "@stringValueMap": { "None": "None", "KeyFilePath": "Key_File_Path", "KeyFileContent": "Key_File_Content" }, + "name": "channel", + "@values": ["None", "Email", "TextMessage"], + "@stringValueMap": { "None": "None", "Email": "EMAIL_V1", "TextMessage": "SMS_LEGACY" }, "@maxLength": 16 } }, diff --git a/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json index adc91b84d3..60a9e4b0ce 100644 --- a/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json +++ b/fixtures/conformance/error-enum-stringvaluemap-array/input/meta.enums.json @@ -4,7 +4,7 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ { "field.long": { "name": "id" } }, { diff --git a/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json index 52e727aecc..8c9ceb902d 100644 --- a/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json +++ b/fixtures/conformance/error-enum-stringvaluemap-duplicate-value/input/meta.enums.json @@ -4,14 +4,14 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", - "@values": ["Pending", "Waiting"], - "@stringValueMap": { "Pending": "pending", "Waiting": "pending" } + "@values": ["Draft", "Queued"], + "@stringValueMap": { "Draft": "draft", "Queued": "draft" } } }, { "identity.primary": { "name": "id", "@fields": "id" } } diff --git a/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json index e53647b538..3dd0e8ecfa 100644 --- a/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json +++ b/fixtures/conformance/error-enum-stringvaluemap-key-mismatch/input/meta.enums.json @@ -4,14 +4,14 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", - "@values": ["Pending", "Delivered"], - "@stringValueMap": { "Pending": "pending", "Lost": "lost" } + "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Archived": "archived" } } }, { "identity.primary": { "name": "id", "@fields": "id" } } diff --git a/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json index b44297ff09..ab0d7cfe89 100644 --- a/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json +++ b/fixtures/conformance/error-enum-stringvaluemap-with-int-value-map/input/meta.enums.json @@ -4,15 +4,15 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", - "@values": ["Pending", "Delivered"], - "@intValueMap": { "Pending": 0, "Delivered": 1 }, - "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } + "@values": ["Draft", "Published"], + "@intValueMap": { "Draft": 0, "Published": 1 }, + "@stringValueMap": { "Draft": "draft", "Published": "published" } } }, { "identity.primary": { "name": "id", "@fields": "id" } } diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index a28ee68986..76131fbca2 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -282,7 +282,7 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@required` | boolean | no | | | metaobjects-core-types | When true, the field is NOT NULL. Equivalent to attaching a validator.required child. On a non-array string, generated wire-tier input validation (create/patch) additionally rejects the empty string by default — whitespace is accepted — unless an explicit validator.length @min: 0 opts back to presence-only. In-process read models never enforce this at construction. | | `@sortable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD sort allowlists. Inherits from @filterable by default; set false to opt out. | | `@sortableDefaultOrder` | string | no | | `asc`, `desc` | metaobjects-ui | Direction a sort takes when it names this field but omits the order: a ?sort= with no :order, and a layout.dataGrid whose @defaultSortField names it with no @defaultSortOrder. Defaults to 'asc'. | -| `@stringValueMap` | properties | no | | | metaobjects-core-types | Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE). | +| `@stringValueMap` | properties | no | | | metaobjects-core-types | Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE). | | `@unique` | boolean | no | | | metaobjects-core-types | When true, the field gets a column-level UNIQUE constraint. | | `@values` | string[] | yes | | | metaobjects-core-types | Member symbols of an enum-subtype field. Declaration order is significant; each is a legal identifier and its own stored string unless @stringValueMap or @intValueMap maps it. | | `@xmlText` | boolean | no | | | metaobjects-prompt | When true, this field receives its element's XML TEXT CONTENT during tolerant extract (JAXB @XmlValue / Jackson @JacksonXmlText / .NET [XmlText]) instead of a same-named child. No effect when the eliciting prompt's @responseFormat is json. | diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index af98f20006..dadc0a44ce 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -1343,7 +1343,7 @@ "valueType": "properties", "isArray": false, "required": false, - "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." + "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." }, { "name": "unique", diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs index a2ff7d39ae..715ef8108b 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ReverseHopHintTests.cs @@ -13,37 +13,37 @@ public class ReverseHopHintTests { private static LoadResult Load(string via, string? collectionName = null) => new MetaDataLoader(FullCoreRegistry.Compose(), strict: true).Load([new InMemoryStringSource($$""" - { "metadata.root": { "package": "acme::cases", "children": [ - { "object.entity": { "name": "Case", "children": [ - { "source.rdb": { "@table": "cases" } }, + { "metadata.root": { "package": "acme::orders", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, { "field.int": { "name": "id" } }, { "field.int": { "name": "statusId" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } } ] } }, - { "object.entity": { "name": "CaseHistory", {{(collectionName is null ? "" : $"\"@collectionName\": \"{collectionName}\",")}} "children": [ - { "source.rdb": { "@table": "case_history" } }, - { "field.int": { "name": "id" } }, { "field.int": { "name": "caseId" } }, { "field.int": { "name": "statusId" } }, + { "object.entity": { "name": "OrderEvent", {{(collectionName is null ? "" : $"\"@collectionName\": \"{collectionName}\",")}} "children": [ + { "source.rdb": { "@table": "order_events" } }, + { "field.int": { "name": "id" } }, { "field.int": { "name": "orderId" } }, { "field.int": { "name": "statusId" } }, { "field.timestamp": { "name": "createdDate" } }, { "identity.primary": { "name": "id", "@fields": "id", "@generation": "increment" } }, - { "identity.reference": { "name": "caseId", "@fields": "caseId", "@references": "Case" } } ] } }, - { "object.projection": { "name": "CaseView", "children": [ + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, + { "object.projection": { "name": "OrderView", "children": [ { "source.rdb": { "@kind": "view", "@view": "v_case" } }, - { "field.int": { "name": "id", "extends": "Case.id" } }, - { "field.int": { "name": "statusId", "extends": "Case.statusId" } }, - { "field.timestamp": { "name": "statusDate", "children": [ { "origin.aggregate": { "@via": "{{via}}", "@of": "CaseHistory.createdDate", + { "field.int": { "name": "id", "extends": "Order.id" } }, + { "field.int": { "name": "statusId", "extends": "Order.statusId" } }, + { "field.timestamp": { "name": "statusDate", "children": [ { "origin.aggregate": { "@via": "{{via}}", "@of": "OrderEvent.createdDate", "@agg": "min", "@filter": { "statusId": { "eq": { "field": "statusId" } } } } } ] } }, - { "identity.primary": { "name": "id", "extends": "Case.id" } } ] } } ] } } + { "identity.primary": { "name": "id", "extends": "Order.id" } } ] } } ] } } """, id: "cases.json")]); [Fact] public void The_first_hop_walks_the_reference_backwards_under_the_collection_name() { - Assert.Empty(Load("Case.caseHistory", collectionName: "CaseHistory").Errors); + Assert.Empty(Load("Order.orderEvent", collectionName: "OrderEvent").Errors); } [Fact] public void A_guessed_hop_name_is_refused_naming_the_reverse_hops() { - var error = Assert.Single(Load("Case.histories", collectionName: "CaseHistory").Errors); + var error = Assert.Single(Load("Order.histories", collectionName: "OrderEvent").Errors); Assert.Equal(ErrorCode.ERR_INVALID_ORIGIN, error.Code); - Assert.Contains("The reverse hops from Case are: \"caseHistory\" (walks CaseHistory.caseId backwards)", error.Message); + Assert.Contains("The reverse hops from Order are: \"orderEvent\" (walks OrderEvent.orderId backwards)", error.Message); } } diff --git a/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs b/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs index 17352c6187..d0cf28a7b1 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/SuperResolveTests.cs @@ -27,24 +27,24 @@ public void Nonexistent_extends_collects_ERR_UNRESOLVED_SUPER() // rc.21 (U1): a projection over a TPH root anchors its identity on the root's identity, which the // root inherits from an abstract base in another package. The identity is unnamed, so it is - // named "primary": `Authorization.primary` resolves through the inherited member, and - // `Authorization.id` (the identity spelled by its field) names the members it could have meant. + // named "primary": `Shipment.primary` resolves through the inherited member, and + // `Shipment.id` (the identity spelled by its field) names the members it could have meant. private static string U1Model(string target) => """ { "metadata.root": { "package": "acme::common", "children": [ { "object.entity": { "name": "BaseEntity", "abstract": true, "children": [ { "field.int": { "name": "id" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } } """ + "\u0000" + """ - { "metadata.root": { "package": "acme::auth", "children": [ - { "object.entity": { "name": "Authorization", "extends": "acme::common::BaseEntity", "@discriminator": "kind", "children": [ - { "source.rdb": { "@table": "authorizations" } }, + { "metadata.root": { "package": "acme::shipping", "children": [ + { "object.entity": { "name": "Shipment", "extends": "acme::common::BaseEntity", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "shipments" } }, { "field.string": { "name": "kind" } } ] } }, - { "object.entity": { "name": "PriorAuth", "extends": "Authorization", "@discriminatorValue": "Prior", "children": [ + { "object.entity": { "name": "AirShipment", "extends": "Shipment", "@discriminatorValue": "Air", "children": [ { "field.string": { "name": "key" } } ] } }, - { "object.projection": { "name": "AuthView", "children": [ - { "source.rdb": { "@kind": "view", "@view": "v_auth" } }, - { "field.int": { "name": "id", "extends": "Authorization.id" } }, - { "field.string": { "name": "key", "extends": "PriorAuth.key" } }, + { "object.projection": { "name": "ShipmentView", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_shipments" } }, + { "field.int": { "name": "id", "extends": "Shipment.id" } }, + { "field.string": { "name": "key", "extends": "AirShipment.key" } }, { "identity.primary": { "extends": "TARGET" } } ] } } ] } } """.Replace("TARGET", target); @@ -57,15 +57,15 @@ private static LoadResult LoadU1(string target) [Fact] public void A_dotted_extends_resolves_an_identity_the_owner_inherits() { - var result = LoadU1("Authorization.primary"); + var result = LoadU1("Shipment.primary"); Assert.Empty(result.Errors); } [Fact] public void A_dotted_extends_naming_a_missing_member_lists_the_owners_members() { - var error = Assert.Single(LoadU1("Authorization.id").Errors, e => e.Code == ErrorCode.ERR_UNRESOLVED_SUPER); - Assert.Contains("'acme::auth::Authorization' has no identity named \"id\"; its identity children are: \"primary\" (identity.primary).", error.Message); + var error = Assert.Single(LoadU1("Shipment.id").Errors, e => e.Code == ErrorCode.ERR_UNRESOLVED_SUPER); + Assert.Contains("'acme::shipping::Shipment' has no identity named \"id\"; its identity children are: \"primary\" (identity.primary).", error.Message); Assert.Contains("An identity.primary declared without a name is named \"primary\".", error.Message); // The owner was found, so the same-named-object FQN advice would be wrong. Assert.DoesNotContain("Qualify it with its package", error.Message); diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index 311abb9d7f..6610a78f6c 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -173,11 +173,11 @@ public void An_entity_derived_field_is_no_column_of_the_entity() private const string StoredStringModel = """ { "metadata.root": { "package": "acme", "children": [ - { "object.entity": { "name": "Upload", "children": [ - { "source.rdb": { "@table": "uploads" } }, + { "object.entity": { "name": "Article", "children": [ + { "source.rdb": { "@table": "articles" } }, { "field.long": { "name": "id" } }, - { "field.enum": { "name": "status", "@values": ["Pending", "Delivered"], "@default": "Pending", "@maxLength": 12, - "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } } }, + { "field.enum": { "name": "status", "@values": ["Draft", "Published"], "@default": "Draft", "@maxLength": 12, + "@stringValueMap": { "Draft": "draft", "Published": "published" } } }, { "identity.primary": { "@fields": "id" } } ]}} ]}} @@ -188,16 +188,16 @@ public void A_string_value_map_enum_converts_member_and_stored_string_both_ways( { var gen = GeneratedEfModel.Compile(StoredStringModel, "Acme.Stored"); using var db = gen.ModelOnlyContext(); - var status = EntityType(db, "Upload").FindProperty("Status")!; + var status = EntityType(db, "Article").FindProperty("Status")!; var converter = status.GetValueConverter()!; var enumType = Nullable.GetUnderlyingType(status.ClrType) ?? status.ClrType; - var delivered = Enum.Parse(enumType, "Delivered"); - Assert.Equal("delivered", converter.ConvertToProvider(delivered)); - Assert.Equal(delivered, converter.ConvertFromProvider("delivered")); + var delivered = Enum.Parse(enumType, "Published"); + Assert.Equal("published", converter.ConvertToProvider(delivered)); + Assert.Equal(delivered, converter.ConvertFromProvider("published")); Assert.Throws(() => converter.ConvertFromProvider("lost")); Assert.Equal(12, status.GetMaxLength()); - // The column default is the member; EF writes it through the converter, as 'pending'. - Assert.Equal("pending", converter.ConvertToProvider(status.GetDefaultValue())); + // The column default is the member; EF writes it through the converter, as 'draft'. + Assert.Equal("draft", converter.ConvertToProvider(status.GetDefaultValue())); } // ── G6 (reference half): an identity.reference over a flattened value-object member ────── @@ -263,6 +263,28 @@ public void A_reference_over_a_flattened_member_uses_the_owned_types_navigation( Assert.DoesNotContain(address.GetProperties(), p => p.Name.StartsWith("CountryId", StringComparison.Ordinal) && p.Name != "CountryId"); } + // rc.21 fix round (M6): the owned type's only navigation to the target is used whatever its name. + private sealed class AddressWithHomeCountry : MetaObjects.Codegen.Generators.EntityGenerator + { + protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + { + if (entity.Name == "Address") + sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? HomeCountry {{ get; set; }}"); + } + } + + [Fact] + public void A_reference_over_a_flattened_member_uses_the_owned_types_only_navigation_whatever_its_name() + { + var gen = GeneratedEfModel.Compile(FlattenedReferenceModel, "Acme.FlatHome", entities: new AddressWithHomeCountry()); + using var db = gen.ModelOnlyContext(); + var address = EntityType(db, "Plan").FindNavigation("Address")!.TargetEntityType; + var fk = Assert.Single(address.GetForeignKeys(), f => f.PrincipalEntityType.ClrType.Name == "Country"); + Assert.Equal(new[] { "CountryId" }, fk.Properties.Select(p => p.Name)); + Assert.Equal("HomeCountry", fk.DependentToPrincipal?.Name); + Assert.DoesNotContain(address.GetProperties(), p => p.Name is "HomeCountryId" or "CountryId1"); + } + [Fact] public void A_reference_carries_its_constraint_name_and_its_principal_key_into_the_model() { diff --git a/server/csharp/MetaObjects/SpecMetamodel/field.json b/server/csharp/MetaObjects/SpecMetamodel/field.json index c81d0eb3c5..9fdbc7aeba 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/field.json +++ b/server/csharp/MetaObjects/SpecMetamodel/field.json @@ -153,7 +153,7 @@ { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, - { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt index ba3bd373d9..33c0b49657 100644 --- a/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt +++ b/server/java/codegen-kotlin/src/test/kotlin/com/metaobjects/generator/kotlin/KotlinExposedTableStringValueMapEnumTest.kt @@ -46,10 +46,10 @@ class KotlinExposedTableStringValueMapEnumTest { gen.setArgs(mapOf("outputDir" to outDir.toString())) gen.execute(loader) } - val src = outDir.resolve("acme/shop/UploadTable.kt").readText() + val src = outDir.resolve("acme/shop/ArticleTable.kt").readText() assertTrue("customEnumeration(\"status\", \"VARCHAR(${KotlinTypeMapper.ENUM_VARCHAR_LEN})\"" in src, "status must use customEnumeration over VARCHAR; saw:\n$src") - assertTrue("\"pending\" -> UploadStatus.Pending" in src && "UploadStatus.Delivered -> \"delivered\"" in src, + assertTrue("\"draft\" -> ArticleStatus.Draft" in src && "ArticleStatus.Published -> \"published\"" in src, "both lambdas must carry the stored strings; saw:\n$src") val result = compile(outDir) assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode, result.messages) diff --git a/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json b/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json index 5c5410726e..5284bc6315 100644 --- a/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json +++ b/server/java/codegen-kotlin/src/test/resources/models/enum-string-value-map/meta.shop.json @@ -4,15 +4,15 @@ "children": [ { "object.entity": { - "name": "Upload", + "name": "Article", "children": [ - { "source.rdb": { "name": "src", "@table": "uploads", "@kind": "table" } }, + { "source.rdb": { "name": "src", "@table": "articles", "@kind": "table" } }, { "field.long": { "name": "id" } }, { "field.enum": { "name": "status", - "@values": ["Pending", "Delivered"], - "@stringValueMap": { "Pending": "pending", "Delivered": "delivered" } + "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Published": "published" } } }, { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } diff --git a/server/python/src/metaobjects/spec_metamodel/field.json b/server/python/src/metaobjects/spec_metamodel/field.json index c81d0eb3c5..9fdbc7aeba 100644 --- a/server/python/src/metaobjects/spec_metamodel/field.json +++ b/server/python/src/metaobjects/spec_metamodel/field.json @@ -153,7 +153,7 @@ { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, - { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { diff --git a/server/python/tests/runtime/test_object_manager_string_value_map.py b/server/python/tests/runtime/test_object_manager_string_value_map.py index 1c308cc26b..0030018ad4 100644 --- a/server/python/tests/runtime/test_object_manager_string_value_map.py +++ b/server/python/tests/runtime/test_object_manager_string_value_map.py @@ -12,11 +12,11 @@ from metaobjects.runtime.object_manager import _coerce_write_value, _decode_read_value _META = {"metadata.root": {"package": "acme", "children": [ - {"object.entity": {"name": "Upload", "children": [ - {"source.rdb": {"@table": "uploads"}}, + {"object.entity": {"name": "Article", "children": [ + {"source.rdb": {"@table": "articles"}}, {"field.long": {"name": "id"}}, - {"field.enum": {"name": "status", "@values": ["Pending", "Delivered"], - "@stringValueMap": {"Pending": "pending", "Delivered": "delivered"}}}, + {"field.enum": {"name": "status", "@values": ["Draft", "Published"], + "@stringValueMap": {"Draft": "draft", "Published": "published"}}}, {"identity.primary": {"name": "id", "@fields": "id"}}, ]}}, ]}} @@ -30,10 +30,18 @@ def _status() -> Any: def test_writes_the_stored_string_and_reads_the_member() -> None: field = _status() - assert _coerce_write_value(field, "Delivered") == "delivered" - assert _decode_read_value(field, "delivered") == "Delivered" + assert _coerce_write_value(field, "Published") == "published" + assert _decode_read_value(field, "published") == "Published" def test_an_unmapped_stored_string_raises() -> None: with pytest.raises(ValueError, match="no member in @stringValueMap"): _decode_read_value(_status(), "lost") + + +def test_writing_an_unmapped_member_raises_but_a_filter_passes_it_through() -> None: + from metaobjects.runtime.object_manager import _coerce_filter_value + field = _status() + with pytest.raises(ValueError, match="no stored string in @stringValueMap"): + _coerce_write_value(field, "Archived") + assert _coerce_filter_value(field, "Archived") == "Archived" diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts index a626e3301f..44c948d0f1 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts @@ -21,8 +21,8 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { Dialect } from "../src/metaobjects-config.js"; -const VALUES = ["Pending", "Delivered"]; -const STORED = { Pending: "pending", Delivered: "delivered" }; +const VALUES = ["Draft", "Published"]; +const STORED = { Draft: "draft", Published: "published" }; async function emit(statusDecl: Record, extraRoots: unknown[] = [], dialect: Dialect = "postgres") { const json = JSON.stringify({ @@ -56,11 +56,11 @@ describe("Drizzle codegen — @stringValueMap field.enum customType", () => { for (const dialect of ["postgres", "sqlite"] as const) { test(`maps member <-> stored string at the column, and the CHECK lists the stored strings (${dialect})`, async () => { const out = await emit({ name: "status", "@values": VALUES, "@stringValueMap": STORED }, [], dialect); - expect(out).toContain('const STATUS_TO_STORED = { "Pending": "pending", "Delivered": "delivered" }'); - expect(out).toContain('const STATUS_FROM_STORED: Record = { "pending": "Pending", "delivered": "Delivered" }'); + expect(out).toContain('const STATUS_TO_STORED = { "Draft": "draft", "Published": "published" }'); + expect(out).toContain('const STATUS_FROM_STORED: Record = { "draft": "Draft", "published": "Published" }'); expect(out).toContain('dataType: () => "text"'); expect(out).toContain('statusStoredEnum("status")'); - expect(out).toContain("IN ('pending', 'delivered')"); + expect(out).toContain("IN ('draft', 'published')"); }); } diff --git a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts index 3e57b08ad1..533d8e4c20 100644 --- a/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/field/field-definition.embedded.ts @@ -307,7 +307,7 @@ export const FIELD_DEFINITION: ProviderDefinition = { "name": "stringValueMap", "min": 0, "max": 1, - "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." + "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, diff --git a/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts b/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts index c7089b83d9..5cb01cfcfa 100644 --- a/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts +++ b/server/typescript/packages/metadata/test/unresolved-super-hint.test.ts @@ -32,23 +32,23 @@ describe("ERR_UNRESOLVED_SUPER names the fix", () => { // rc.21 (U1): a projection over a TPH root anchors its identity on the root's identity, which the // root inherits from an abstract base in another package. The identity is unnamed, so it is named -// "primary": `Authorization.primary` resolves through the inherited member, and `Authorization.id` +// "primary": `Shipment.primary` resolves through the inherited member, and `Shipment.id` // (the identity spelled by its field) names the members it could have meant. describe("a dotted extends onto an inherited identity", () => { const common = JSON.stringify({ "metadata.root": { package: "acme::common", children: [ { "object.entity": { name: "BaseEntity", abstract: true, children: [ { "field.int": { name: "id" } }, { "identity.primary": { "@fields": "id", "@generation": "increment" } } ] } } ] } }); - const auth = (target: string) => JSON.stringify({ "metadata.root": { package: "acme::auth", children: [ - { "object.entity": { name: "Authorization", extends: "acme::common::BaseEntity", "@discriminator": "kind", children: [ - { "source.rdb": { "@table": "authorizations" } }, + const auth = (target: string) => JSON.stringify({ "metadata.root": { package: "acme::shipping", children: [ + { "object.entity": { name: "Shipment", extends: "acme::common::BaseEntity", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "shipments" } }, { "field.string": { name: "kind" } } ] } }, - { "object.entity": { name: "PriorAuth", extends: "Authorization", "@discriminatorValue": "Prior", children: [ + { "object.entity": { name: "AirShipment", extends: "Shipment", "@discriminatorValue": "Air", children: [ { "field.string": { name: "key" } } ] } }, - { "object.projection": { name: "AuthView", children: [ - { "source.rdb": { "@kind": "view", "@view": "v_auth" } }, - { "field.int": { name: "id", extends: "Authorization.id" } }, - { "field.string": { name: "key", extends: "PriorAuth.key" } }, + { "object.projection": { name: "ShipmentView", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_shipments" } }, + { "field.int": { name: "id", extends: "Shipment.id" } }, + { "field.string": { name: "key", extends: "AirShipment.key" } }, { "identity.primary": { extends: target } } ] } } ] } }); const load = (target: string) => new MetaDataLoader({ strict: true }).load([ new InMemoryStringSource(common, { id: "common.json", format: "json" }), @@ -56,12 +56,12 @@ describe("a dotted extends onto an inherited identity", () => { ]); test("resolves through the member the owner inherits", async () => { - expect((await load("Authorization.primary")).errors).toEqual([]); + expect((await load("Shipment.primary")).errors).toEqual([]); }); test("a missing member lists the owner's members, not a package qualification", async () => { - const err = (await load("Authorization.id")).errors.find((e) => (e as { code?: string }).code === "ERR_UNRESOLVED_SUPER"); - expect(err!.message).toContain(`'acme::auth::Authorization' has no identity named "id"; its identity children are: "primary" (identity.primary).`); + const err = (await load("Shipment.id")).errors.find((e) => (e as { code?: string }).code === "ERR_UNRESOLVED_SUPER"); + expect(err!.message).toContain(`'acme::shipping::Shipment' has no identity named "id"; its identity children are: "primary" (identity.primary).`); expect(err!.message).toContain(`An identity.primary declared without a name is named "primary".`); expect(err!.message).not.toContain("Qualify it with its package"); }); diff --git a/server/typescript/packages/migrate-ts/test/string-value-map.test.ts b/server/typescript/packages/migrate-ts/test/string-value-map.test.ts index b639d695b3..6ac1d9ef8c 100644 --- a/server/typescript/packages/migrate-ts/test/string-value-map.test.ts +++ b/server/typescript/packages/migrate-ts/test/string-value-map.test.ts @@ -6,29 +6,29 @@ import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; import { buildExpectedSchema } from "../src/expected-schema.js"; const MODEL = { "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Upload", children: [ - { "source.rdb": { "@table": "uploads" } }, + { "object.entity": { name: "Article", children: [ + { "source.rdb": { "@table": "articles" } }, { "field.long": { name: "id" } }, - { "field.enum": { name: "status", "@values": ["Pending", "Delivered"], "@default": "Pending", - "@stringValueMap": { Pending: "pending", Delivered: "delivered" } } }, - { "field.enum": { name: "authType", "@values": ["KeyFilePath", "KeyFileContent"], "@maxLength": 16, - "@stringValueMap": { KeyFilePath: "Key_File_Path", KeyFileContent: "Key_File_Content" } } }, + { "field.enum": { name: "status", "@values": ["Draft", "Published"], "@default": "Draft", + "@stringValueMap": { Draft: "draft", Published: "published" } } }, + { "field.enum": { name: "channel", "@values": ["Email", "TextMessage"], "@maxLength": 16, + "@stringValueMap": { Email: "EMAIL_V1", TextMessage: "SMS_LEGACY" } } }, { "identity.primary": { name: "id", "@fields": "id", "@generation": "increment" } } ] } } ] } }; describe("@stringValueMap in the expected schema", () => { test("the default, the length and the CHECK hold the stored strings", async () => { const { root, errors } = await new MetaDataLoader({ strict: true }).load([new InMemoryStringSource(JSON.stringify(MODEL))]); expect(errors).toEqual([]); - const table = buildExpectedSchema(root, { dialect: "postgres" }).tables.find((t) => t.name === "uploads")!; + const table = buildExpectedSchema(root, { dialect: "postgres" }).tables.find((t) => t.name === "articles")!; const status = table.columns.find((c) => c.name === "status")!; - expect(status.default).toEqual({ kind: "literal", value: "pending" }); - expect(table.checks.map((c) => c.expression)).toContain(`"auth_type" IN ('Key_File_Path', 'Key_File_Content')`); + expect(status.default).toEqual({ kind: "literal", value: "draft" }); + expect(table.checks.map((c) => c.expression)).toContain(`"channel" IN ('EMAIL_V1', 'SMS_LEGACY')`); }); test("a stored string longer than @maxLength is refused at load", async () => { const m = JSON.parse(JSON.stringify(MODEL)); - m["metadata.root"].children[0]["object.entity"].children[3]["field.enum"]["@maxLength"] = 14; + m["metadata.root"].children[0]["object.entity"].children[3]["field.enum"]["@maxLength"] = 9; const { errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(m))]); - expect(errors.map((e) => String(e.message)).join("\n")).toContain(`shorter than its stored value "Key_File_Content"`); + expect(errors.map((e) => String(e.message)).join("\n")).toContain(`shorter than its stored value "SMS_LEGACY"`); }); }); diff --git a/site-reference/types/field.html b/site-reference/types/field.html index ba4560c4d6..be2a31c07d 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -1351,7 +1351,7 @@

    field.enum

    - + diff --git a/spec/metamodel/field.json b/spec/metamodel/field.json index c81d0eb3c5..9fdbc7aeba 100644 --- a/spec/metamodel/field.json +++ b/spec/metamodel/field.json @@ -153,7 +153,7 @@ { "type": "attr", "subType": "boolean", "name": "provided", "min": 0, "max": 1, "description": "FR-019: marks an abstract package-level field.enum as externally provided — codegen references the type (resolved via per-port codegen config) instead of materializing it. Default false. Not a field attr — it lives on the type declaration." }, { "type": "attr", "subType": "int", "name": "maxLength", "min": 0, "max": 1, "description": "Column length of a string-stored enum (drives VARCHAR(n)); every member must fit. Overrides the project's enums.maxLength. Refused with @intValueMap, whose column is an integer." }, { "type": "attr", "subType": "intMap", "name": "intValueMap", "min": 0, "max": 1, "description": "Optional per-member int values ({member: int}) switching this enum field's DB persistence from string+CHECK to integer+CHECK. Keys must exactly match @values; values must be unique integers. The generated native type and wire format are unchanged in every language." }, - { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } + { "type": "attr", "subType": "properties", "name": "stringValueMap", "min": 0, "max": 1, "description": "Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE)." } ] }, { From 765e02f09d4baf033926cb33de584320dfa13b0f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 17:35:49 -0500 Subject: [PATCH 186/267] fix(checks): CHECK-name refusals only where the database needs them; long qualified names fit 63 bytes Two different CHECKs under one name are refused on Postgres, which requires unique constraint names, by meta migrate and now by the Drizzle schema too. SQLite and D1 accept and enforce both (probed on SQLite 3.51 and on Miniflare's D1), so meta migrate and Drizzle keep both there, declared names included, and the SQLite CHECK diff matches a name to a list so it converges. C# keeps the refusal on every dialect: EF Core keys a check constraint by name and keeps only the last (verified on EF Core 8.0.18). On Postgres a declarer-qualified default CHECK name over 63 bytes keeps its first 54 bytes plus '_' and 8 hex digits of its SHA-256, spelled the same in meta migrate, Drizzle and C#, so Postgres never truncates it; a collision that survives is refused by the same name check. Co-Authored-By: Claude Opus 5.5 --- .../CheckConstraintConformanceTests.cs | 43 +++++++ .../Generators/CheckConstraints.cs | 51 ++++++-- .../src/templates/drizzle-schema.ts | 40 ++++++- .../test/drizzle-enum-stringvaluemap.test.ts | 25 ++++ .../packages/migrate-ts/src/diff/index.ts | 13 +- .../packages/migrate-ts/src/errors.ts | 6 +- .../migrate-ts/src/expected-schema.ts | 55 ++++++--- .../packages/migrate-ts/src/expected.ts | 2 +- .../test/check-name-collision.test.ts | 112 ++++++++++++++++-- 9 files changed, 301 insertions(+), 46 deletions(-) diff --git a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs index 616f1c2be7..12aa309083 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/CheckConstraintConformanceTests.cs @@ -136,5 +136,48 @@ public void Two_checks_under_one_name_are_refused() Assert.Empty(load.Errors); var ex = Assert.Throws(() => CheckConstraints.For(load.Root.Objects().Single(), Ctx(load.Root, "postgres").Config)); Assert.Contains("both named 'windows_a_cmp_chk'", ex.Message); + Assert.Contains("Postgres requires each constraint on a table to have its own name", ex.Message); + // rc.21 part B (N1): SQLite and D1 accept the pair (meta migrate keeps both), but EF's model + // keys a check constraint by name and would keep only the last, so C# still refuses it there. + foreach (var dialect in new[] { "sqlite", "d1" }) + { + var lite = Assert.Throws(() => CheckConstraints.For(load.Root.Objects().Single(), Ctx(load.Root, dialect).Config)); + Assert.Contains("EF Core keeps one check constraint per name", lite.Message); + } + } + + // rc.21 part B (N2): a generated name fitted to Postgres's 63-byte limit, spelled as meta migrate spells it. + [Fact] + public void FitPgIdentifier_matches_the_TypeScript_spelling() + { + Assert.Equal("devices_meter_serial_regex_chk", CheckConstraints.FitPgIdentifier("devices_meter_serial_regex_chk")); + Assert.Equal("measurement_devices_with_a_rather_long_table_name_mete_559a7830", + CheckConstraints.FitPgIdentifier("measurement_devices_with_a_rather_long_table_name_meterdevicekind_serial_chk")); + Assert.Equal(new string('é', 27) + "_84fe2e03", CheckConstraints.FitPgIdentifier(new string('é', 40))); + } + + [Fact] + public void A_qualified_TPH_check_name_over_63_bytes_is_fitted_on_Postgres_only() + { + const string table = "measurement_devices_with_a_rather_long_table_name"; + var load = new MetaDataLoader().Load([new InMemoryStringSource($$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Device", "@discriminator": "kind", "children": [ + { "source.rdb": { "@table": "{{table}}" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "kind", "@maxLength": 20 } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.entity": { "name": "MeterDeviceKind", "extends": "Device", "@discriminatorValue": "METER", "children": [ + { "field.enum": { "name": "serial", "@values": ["M1", "M2"] } } ] } }, + { "object.entity": { "name": "SensorDeviceKind", "extends": "Device", "@discriminatorValue": "SENSOR", "children": [ + { "field.enum": { "name": "serial", "@values": ["S1", "S2"] } } ] } } ] } } + """, id: "d.json")]); + Assert.Empty(load.Errors); + var device = load.Root.Objects().Single(o => o.Name == "Device"); + IEnumerable Names(string dialect) => CheckConstraints.For(device, Ctx(load.Root, dialect).Config) + .Where(c => c.Expression.Contains("serial")).Select(c => c.Name); + Assert.Equal(new[] { "measurement_devices_with_a_rather_long_table_name_mete_559a7830", + CheckConstraints.FitPgIdentifier($"{table}_sensordevicekind_serial_chk") }, Names("postgres")); + Assert.Equal(new[] { $"{table}_meterdevicekind_serial_chk", $"{table}_sensordevicekind_serial_chk" }, Names("sqlite")); } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs index 5605976168..9202a21bf2 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/CheckConstraints.cs @@ -58,15 +58,18 @@ public static IReadOnlyList For(MetaObject entity, GenConfig co checks.Add(Named(WithCondition(check, v, entity, strategy, dialect), v)); } if (tph is not null) checks.AddRange(SubtypeCrossFieldChecks(entity, tph, table, strategy, dialect)); - return Distinct(entity, checks); + return Distinct(entity, checks, dialect); } /// /// One table's CHECKs, with an exact repeat (same name, same expression) kept once, and two - /// different CHECKs under one name refused: the database would refuse the second at CREATE - /// TABLE, and EF would keep only one of them. + /// different CHECKs under one name refused on every dialect. On Postgres the database would + /// refuse the second at CREATE TABLE. SQLite and D1 accept both (rc.21, N1), but EF's model keys + /// a check constraint by name: a second HasCheckConstraint with the same name replaces the + /// first (verified on EF Core 8.0.18), so the model would silently hold one of them. That is an + /// EF limit, so the C# port keeps the refusal where meta migrate accepts the pair. /// - private static IReadOnlyList Distinct(MetaObject entity, List checks) + private static IReadOnlyList Distinct(MetaObject entity, List checks, string? dialect) { var byName = new Dictionary(StringComparer.Ordinal); var outList = new List(); @@ -75,8 +78,11 @@ private static IReadOnlyList Distinct(MetaObject entity, List SubtypeFieldChecks( foreach (var (check, declared) in nodeChecks) { var guarded = Wrap(check, DiscriminatorIn(tph, values), entity, strategy, dialect); - yield return declared ? guarded : guarded with { Name = Qualified(check.Name, table, node.Parent) }; + yield return declared ? guarded : guarded with { Name = Qualified(check.Name, table, node.Parent, dialect) }; } } } /// A default CHECK name made unique to the object that declares the rule: <table>_<declarer>_…. - private static string Qualified(string name, string table, MetaData? declarer) + private static string Qualified(string name, string table, MetaData? declarer, string? dialect) { var tag = (declarer?.Name ?? "subtype").ToLowerInvariant(); - return name.StartsWith(table + "_", StringComparison.Ordinal) + var qualified = name.StartsWith(table + "_", StringComparison.Ordinal) ? $"{table}_{tag}_{name[(table.Length + 1)..]}" : $"{tag}_{name}"; + return IsSqlite(dialect) ? qualified : FitPgIdentifier(qualified); + } + + /// Postgres's identifier limit, in bytes (NAMEDATALEN - 1). A longer name is truncated. + private const int PgIdentifierMaxBytes = 63; + + /// + /// rc.21 (N2): a generated name fitted to Postgres's 63-byte identifier limit, spelled as + /// meta migrate spells it (fitPgIdentifier). A longer name keeps its first 54 + /// bytes (whole characters) and gains _ and the first 8 hex digits of the SHA-256 of the + /// whole name. A name that fits is unchanged. + /// + public static string FitPgIdentifier(string name) + { + var utf8 = System.Text.Encoding.UTF8; + if (utf8.GetByteCount(name) <= PgIdentifierMaxBytes) return name; + var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(utf8.GetBytes(name)))[..8].ToLowerInvariant(); + var head = new System.Text.StringBuilder(); + var bytes = 0; + foreach (var rune in name.EnumerateRunes()) + { + var n = rune.Utf8SequenceLength; + if (bytes + n > PgIdentifierMaxBytes - 9) break; + head.Append(rune.ToString()); + bytes += n; + } + return $"{head}_{hash}"; } /// The condition "the discriminator is one of ". @@ -228,7 +261,7 @@ private static IEnumerable SubtypeCrossFieldChecks( { if (CrossFieldCheck(v, holder, table, strategy, dialect) is not { } check) continue; var guarded = WithCondition(check, v, holder, strategy, dialect, DiscriminatorIn(tph, values)); - yield return DeclaredName(v) is { } name ? guarded with { Name = name } : guarded with { Name = Qualified(check.Name, table, v.Parent) }; + yield return DeclaredName(v) is { } name ? guarded with { Name = name } : guarded with { Name = Qualified(check.Name, table, v.Parent, dialect) }; } } diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 8889803ccd..3ba6e3fc25 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -27,6 +27,10 @@ import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "../names.js"; import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/migrate-ts/expected"; + +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } import { intValueMapOf } from "../enum-meta.js"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; @@ -177,7 +181,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -191,7 +195,7 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); @@ -204,6 +208,8 @@ export function renderDrizzleSchema( expr: names === undefined || values === undefined ? code`${spec.checkConstraint ?? ""}` : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", }; } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which @@ -212,6 +218,8 @@ export function renderDrizzleSchema( return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -220,6 +228,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -392,6 +402,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -766,7 +792,7 @@ function renderColumn( */ function guardedSiblingEnumChecks( obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, -): Array<{ name: Code; expr: Code }> | undefined { +): CheckEntry[] | undefined { const plan = tphPlan(obj, ctx.loadedRoot); if (plan === null) return undefined; const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); @@ -792,7 +818,7 @@ function guardedSiblingEnumChecks( const stored = disc === undefined ? value : storedEnumValue(disc, value); return `'${stored.replace(/'/g, "''")}'`; }; - const out: Array<{ name: Code; expr: Code }> = []; + const out: CheckEntry[] = []; owners.forEach((o, i) => { const check = specs[i]!.checkConstraint; if (check === undefined) return; @@ -800,10 +826,12 @@ function guardedSiblingEnumChecks( ? `"${discCol}" <> ${literal(o.values[0]!)}` : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; const name = typeof declared === "string" && declared.length > 0 ? declared - : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; - out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); }); return out; } diff --git a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts index 44c948d0f1..ccd97b68f1 100644 --- a/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts +++ b/server/typescript/packages/codegen-ts/test/drizzle-enum-stringvaluemap.test.ts @@ -97,3 +97,28 @@ describe("Drizzle codegen — TPH siblings sharing a column with different @valu expect(out).not.toContain(`"devices_grade_chk"`); }); }); + +// rc.21 part B (N1): two different CHECKs under one name are refused on Postgres, which requires +// unique constraint names, as `meta migrate` refuses them; SQLite accepts and enforces both. +describe("Drizzle codegen — two CHECKs under one name", () => { + async function render(dialect: Dialect) { + const json = JSON.stringify({ "metadata.root": { children: [ { "object.entity": { name: "Order", children: [ + { "field.long": { name: "id" } }, + { "field.enum": { name: "status", "@values": ["A", "B"], "@constraintName": "orders_state_chk" } }, + { "field.enum": { name: "phase", "@values": ["X", "Y"], "@constraintName": "orders_state_chk" } }, + { "source.rdb": { name: "src", "@table": "orders" } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } } ] } } ] } }); + const res = await new MetaDataLoader().load([new InMemoryStringSource(json)]); + expect(res.errors).toEqual([]); + const ctx = makeRenderContext({ dialect, loadedRoot: res.root, outDir: "/x", dbImport: "~/db", + pkMap: buildPkMap(res.root), relationMap: buildRelationMap(res.root) }); + return () => renderDrizzleSchema(res.root.findObject("Order")!, ctx).toString(); + } + test("refused on Postgres", async () => { + expect(await render("postgres")).toThrow(/both named 'orders_state_chk'.*Postgres requires/); + }); + test("both kept on SQLite", async () => { + const out = (await render("sqlite"))(); + expect(out.match(/"orders_state_chk"/g)?.length).toBe(2); + }); +}); diff --git a/server/typescript/packages/migrate-ts/src/diff/index.ts b/server/typescript/packages/migrate-ts/src/diff/index.ts index 9205bae7d7..887a89f323 100644 --- a/server/typescript/packages/migrate-ts/src/diff/index.ts +++ b/server/typescript/packages/migrate-ts/src/diff/index.ts @@ -1132,12 +1132,21 @@ function diffTableChecks( // on a name-matched check is still caught as drop+add. Postgres constraints are always // named, so it keeps the exact name-keyed behavior (exprFallback off). const exprFallback = dialect === "sqlite" || dialect === "d1"; - const actualByName = new Map(actual.checks.filter((c) => c.name !== "").map((c) => [c.name, c])); + // rc.21 (N1): SQLite and D1 accept two CHECKs under one name, and the expected schema may hold + // two there, so a name keys a LIST: the same-name actual with the same rule is taken first. + const actualByName = new Map(); + for (const c of actual.checks) { + if (c.name === "") continue; + const list = actualByName.get(c.name) ?? []; + if (!actualByName.has(c.name)) actualByName.set(c.name, list); + list.push(c); + } const consumed = new Set(); const textColumns = textColumnsOf(actual); for (const ec of expected.checks) { - const ac = actualByName.get(ec.name); + const named = (actualByName.get(ec.name) ?? []).filter((a) => !consumed.has(a)); + const ac = named.find((a) => checkMatchesLive(canon, ec, a, textColumns)) ?? named[0]; if (ac) { consumed.add(ac); if (!checkMatchesLive(canon, ec, ac, textColumns)) { diff --git a/server/typescript/packages/migrate-ts/src/errors.ts b/server/typescript/packages/migrate-ts/src/errors.ts index 026243e787..2d242ba068 100644 --- a/server/typescript/packages/migrate-ts/src/errors.ts +++ b/server/typescript/packages/migrate-ts/src/errors.ts @@ -344,9 +344,9 @@ export interface CheckNameProblem { } /** - * A declared CHECK name that cannot be applied as written. Two constraints on one table with - * one name fail at apply on Postgres ("already exists") and, on SQLite, collapse in a - * name-keyed diff so every run proposes the CHECK again. A name over 63 bytes is truncated by + * A declared CHECK name that cannot be applied as written on Postgres. Two constraints on one + * table with one name fail at apply ("already exists"); SQLite and D1 accept them (rc.21, N1), + * and their CHECK diff matches a name to a list, so nothing is refused there. A name over 63 bytes is truncated by * Postgres when it is created, so the declared name never matches the database and the CHECK * drifts forever. Either way the fix is to the metadata, so it is refused while the expected * schema is built. diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index ff763c8bad..c89b0da5d0 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -87,6 +87,7 @@ import type { import { qualifiedDbName } from "./qualified-name.js"; import { SQLITE_ISO_NOW } from "./column-default.js"; import { viewFingerprint } from "./view-fingerprint.js"; +import { createHash } from "node:crypto"; import { resolveReferentialActions, findReferentialActionConflict, @@ -1016,7 +1017,7 @@ function buildChecks( DECLARED_CHECKS.add(guarded); checks.push(guarded); } else { - checks.push({ ...guarded, name: qualifiedCheckName(check.name, tableName, node.parent) }); + checks.push({ ...guarded, name: qualifiedCheckName(check.name, tableName, node.parent, dialect) }); } } } @@ -1054,23 +1055,47 @@ function buildChecks( const guarded = withCondition(check, v, holder, strategy, dialect, discriminatorIn(values)); checks.push(declaredCheckName(v) !== undefined ? withDeclaredName(guarded, v) - : { ...guarded, name: qualifiedCheckName(check.name, tableName, v.parent) }); + : { ...guarded, name: qualifiedCheckName(check.name, tableName, v.parent, dialect) }); } } - return distinctChecks(entity, checks); + return distinctChecks(entity, checks, dialect); } -/** A default CHECK name made unique to the object that declares the rule: `
    metaobjects-core-typesOptional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding 'pending' or 'Key_File_Path'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE).Optional per-member stored strings ({member: string}) for a string-stored enum whose database spelling differs from its member symbols (a legacy column holding lowercase 'draft', or 'LEGACY_A'). The column, its CHECK, its length, a @default and a @condition literal hold the stored strings; the generated native type and wire format keep the members. Keys must exactly match @values; values must be unique non-empty strings. The string twin of @intValueMap, refused with it and on an array enum (ERR_BAD_ATTR_VALUE).
    @unique
    __…`. */ -function qualifiedCheckName(name: string, tableName: string, declarer: MetaData | undefined): string { +/** A default CHECK name made unique to the object that declares the rule: `
    __…`. + * On Postgres it is fitted to the 63-byte identifier limit ({@link fitPgIdentifier}). */ +function qualifiedCheckName(name: string, tableName: string, declarer: MetaData | undefined, dialect: Dialect | undefined): string { const tag = (declarer?.name ?? "subtype").toLowerCase(); - return name.startsWith(`${tableName}_`) ? `${tableName}_${tag}_${name.slice(tableName.length + 1)}` : `${tag}_${name}`; + const qualified = name.startsWith(`${tableName}_`) ? `${tableName}_${tag}_${name.slice(tableName.length + 1)}` : `${tag}_${name}`; + return dialect === "sqlite" || dialect === "d1" ? qualified : fitPgIdentifier(qualified); +} + +/** + * rc.21 (N2): a generated name fitted to Postgres's 63-byte identifier limit. A longer name keeps + * its first 54 bytes (whole characters) and gains `_` and the first 8 hex digits of the SHA-256 + * of the whole name, so two long names that share a prefix stay apart, and every port spells it + * the same. A name that fits is unchanged. Postgres would otherwise truncate it at CREATE, so the + * name the schema expects would never match the database. + */ +export function fitPgIdentifier(name: string): string { + if (Buffer.byteLength(name, "utf8") <= PG_IDENTIFIER_MAX_BYTES) return name; + const hash = createHash("sha256").update(name, "utf8").digest("hex").slice(0, 8); + let head = ""; + for (const ch of name) { + if (Buffer.byteLength(head + ch, "utf8") > PG_IDENTIFIER_MAX_BYTES - 9) break; + head += ch; + } + return `${head}_${hash}`; } /** * One table's CHECKs, an exact repeat (same name, same expression) kept once, and two different - * CHECKs under one name refused: the database would refuse the second at CREATE TABLE. + * CHECKs under one name refused where the database requires unique names: Postgres would refuse + * the second at CREATE TABLE. SQLite and D1 accept both under one name and enforce both (rc.21, + * N1: probed on SQLite 3.51 and on Miniflare's D1), so both are kept there; the CHECK diff matches + * a name to a list. A name shortened to fit the 63-byte limit that still collides is refused too. */ -function distinctChecks(entity: MetaObject, checks: CheckDescriptor[]): CheckDescriptor[] { +function distinctChecks(entity: MetaObject, checks: CheckDescriptor[], dialect: Dialect | undefined): CheckDescriptor[] { + const unique = dialect !== "sqlite" && dialect !== "d1"; const byName = new Map(); const out: CheckDescriptor[] = []; for (const c of checks) { @@ -1078,13 +1103,14 @@ function distinctChecks(entity: MetaObject, checks: CheckDescriptor[]): CheckDes if (seen !== undefined) { if (seen.expression === c.expression) continue; // A DECLARED name's collision is checkDeclaredCheckNames' to report, with its own error. - if (DECLARED_CHECKS.has(c) || DECLARED_CHECKS.has(seen)) { + if (!unique || DECLARED_CHECKS.has(c) || DECLARED_CHECKS.has(seen)) { out.push(c); continue; } throw new Error( `object.entity '${entity.name}': two CHECK constraints are both named '${c.name}' ` + - `(${seen.expression} | ${c.expression}). Give one of the validators (or enums) a @constraintName.`, + `(${seen.expression} | ${c.expression}); Postgres requires each constraint on a table to have its own name. ` + + `Give one of the validators (or enums) a @constraintName.`, ); } byName.set(c.name, c); @@ -1195,13 +1221,15 @@ function withDeclaredName(check: CheckDescriptor, node: MetaData): CheckDescript const PG_IDENTIFIER_MAX_BYTES = 63; /** - * Refuse a declared CHECK name another constraint on the same table already has, or (on - * Postgres) one over 63 bytes. Runs after the conventions have named primary keys, foreign - * keys and unique constraints. A collision among derived names is left as it always was. + * Refuse, on Postgres, a declared CHECK name another constraint on the same table already has, or + * one over 63 bytes. Runs after the conventions have named primary keys, foreign keys and unique + * constraints. SQLite and D1 require neither (rc.21, N1: two CHECKs under one name are accepted and + * both enforced, and a CHECK name is no schema object), so nothing is refused there. */ function checkDeclaredCheckNames(tables: readonly TableDescriptor[], dialect: Dialect | undefined): void { const problems: CheckNameProblem[] = []; const limited = dialect !== "sqlite" && dialect !== "d1"; + if (!limited) return; for (const t of tables) { const declared = new Set(t.checks.filter((c) => DECLARED_CHECKS.has(c)).map((c) => c.name)); if (declared.size === 0) continue; @@ -1220,7 +1248,6 @@ function checkDeclaredCheckNames(tables: readonly TableDescriptor[], dialect: Di for (const fk of t.foreignKeys) claim(fk.name, `the foreign key "${fk.name}"`); for (const ix of t.indexes) if (ix.constraint === "unique") claim(ix.name, `the unique constraint "${ix.name}"`); for (const c of t.checks) claim(c.name, `another CHECK named "${c.name}"`); - if (!limited) continue; for (const name of declared) { const bytes = Buffer.byteLength(name, "utf8"); if (bytes > PG_IDENTIFIER_MAX_BYTES) problems.push({ table: t.name, name, bytes }); diff --git a/server/typescript/packages/migrate-ts/src/expected.ts b/server/typescript/packages/migrate-ts/src/expected.ts index 076fdc4277..20aab755dc 100644 --- a/server/typescript/packages/migrate-ts/src/expected.ts +++ b/server/typescript/packages/migrate-ts/src/expected.ts @@ -6,7 +6,7 @@ // not need kysely installed. Its import graph is the model walk and nothing that opens a // connection; keep it that way. -export { buildExpectedSchema, buildExpectedSchemaWithProvenance, fieldSqlType } from "./expected-schema.js"; +export { buildExpectedSchema, buildExpectedSchemaWithProvenance, fieldSqlType, fitPgIdentifier } from "./expected-schema.js"; export { pgType } from "./emit/postgres.js"; export type { BuildExpectedSchemaOptions, SchemaBuildSettings, ExpectedSchemaWithProvenance, SchemaProvenance } from "./expected-schema.js"; export { qualifiedDbName } from "./qualified-name.js"; diff --git a/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts b/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts index 60c771b830..e78f10dcf5 100644 --- a/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts +++ b/server/typescript/packages/migrate-ts/test/check-name-collision.test.ts @@ -1,19 +1,109 @@ // rc.21 fix round (I2): two different CHECKs under one default name are refused at build, naming // both, instead of a CREATE TABLE the database refuses ("constraint already exists"). +// rc.21 part B (N1): only where the database requires unique names. SQLite and D1 accept and +// enforce two CHECKs under one name, so they keep both, and the CHECK diff converges on them. +// rc.21 part B (N2): a qualified default name is fitted to Postgres's 63-byte identifier limit. import { expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Kysely, sql } from "kysely"; +import { LibsqlDialect } from "@libsql/kysely-libsql"; import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; -import { buildExpectedSchema } from "../src/expected-schema.js"; +import { buildExpectedSchema, fitPgIdentifier } from "../src/expected-schema.js"; +import { diff } from "../src/diff/index.js"; +import { emit } from "../src/emit/index.js"; +import { introspect } from "../src/introspect/index.js"; -test("two CHECKs under one default name are refused", async () => { - const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ - { "object.entity": { name: "Window", children: [ - { "source.rdb": { "@table": "windows" } }, - { "field.long": { name: "id" } }, - { "field.int": { name: "a" } }, { "field.int": { name: "b" } }, { "field.int": { name: "c" } }, - { "identity.primary": { name: "id", "@fields": "id" } }, - { "validator.comparison": { name: "ab", "@left": "a", "@op": "lt", "@right": "b" } }, - { "validator.comparison": { name: "ac", "@left": "a", "@op": "lt", "@right": "c" } } ] } } ] } }))]); +const WINDOW = JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Window", children: [ + { "source.rdb": { "@table": "windows" } }, + { "field.long": { name: "id" } }, + { "field.int": { name: "a" } }, { "field.int": { name: "b" } }, { "field.int": { name: "c" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "validator.comparison": { name: "ab", "@left": "a", "@op": "lt", "@right": "b" } }, + { "validator.comparison": { name: "ac", "@left": "a", "@op": "lt", "@right": "c" } } ] } } ] } }); + +async function load(json: string) { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(json)]); expect(errors).toEqual([]); - expect(() => buildExpectedSchema(root, { dialect: "postgres" })).toThrow(/both named 'windows_a_cmp_chk'/); + return root; +} + +test("two CHECKs under one default name are refused on Postgres", async () => { + const root = await load(WINDOW); + expect(() => buildExpectedSchema(root, { dialect: "postgres" })).toThrow(/both named 'windows_a_cmp_chk'.*Postgres requires/); +}); + +test("SQLite and D1 keep both CHECKs under the one name", async () => { + const root = await load(WINDOW); + for (const dialect of ["sqlite", "d1"] as const) { + const windows = buildExpectedSchema(root, { dialect }).tables.find((t) => t.name === "windows")!; + expect(windows.checks.filter((c) => c.name === "windows_a_cmp_chk").map((c) => c.expression)) + .toEqual(['"a" < "b"', '"a" < "c"']); + } +}); + +test("SQLite: a table holding both same-named CHECKs migrates once and then shows no change", async () => { + const root = await load(WINDOW); + const dir = mkdtempSync(join(tmpdir(), "migrate-ts-dup-check-")); + const k = new Kysely>({ dialect: new LibsqlDialect({ url: `file:${join(dir, "t.db")}` }) }); + try { + const expected = buildExpectedSchema(root, { dialect: "sqlite" }); + const { up } = emit((await diff(expected, await introspect(k, "sqlite"), { dialect: "sqlite" })).changes, { dialect: "sqlite", expectedSchema: expected }); + for (const stmt of up.split(";").map((s) => s.trim()).filter((s) => s.length > 0)) await sql.raw(stmt).execute(k); + // Both rules hold. + await sql.raw("INSERT INTO windows (id, a, b, c) VALUES (1, 1, 2, 3)").execute(k); + await expect(sql.raw("INSERT INTO windows (id, a, b, c) VALUES (2, 1, 9, 0)").execute(k)).rejects.toThrow(/CHECK/); + await expect(sql.raw("INSERT INTO windows (id, a, b, c) VALUES (3, 1, 0, 9)").execute(k)).rejects.toThrow(/CHECK/); + const again = await diff(expected, await introspect(k, "sqlite"), { dialect: "sqlite" }); + expect(again.changes.filter((c) => c.kind === "add-check" || c.kind === "drop-check")).toEqual([]); + } finally { + await k.destroy(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("fitPgIdentifier keeps a name that fits and shortens a longer one to 63 bytes, deterministically", () => { + expect(fitPgIdentifier("devices_meter_serial_chk")).toBe("devices_meter_serial_chk"); + const long = `${"x".repeat(40)}_${"y".repeat(30)}_chk`; + const fitted = fitPgIdentifier(long); + expect(Buffer.byteLength(fitted)).toBe(63); + expect(fitted.startsWith("x".repeat(40) + "_" + "y".repeat(13))).toBe(true); + expect(fitted).toMatch(/_[0-9a-f]{8}$/); + expect(fitPgIdentifier(long)).toBe(fitted); + // Two long names sharing their first 54 bytes stay apart. + expect(fitPgIdentifier(long.replace("_chk", "_cmp"))).not.toBe(fitted); + // Whole characters only: a multi-byte character is never split. + const wide = "é".repeat(40); + expect(Buffer.byteLength(fitPgIdentifier(wide))).toBeLessThanOrEqual(63); + // The spelling every port pins (C#: CheckConstraintConformanceTests). + expect(fitPgIdentifier("measurement_devices_with_a_rather_long_table_name_meterdevicekind_serial_chk")) + .toBe("measurement_devices_with_a_rather_long_table_name_mete_559a7830"); + expect(fitPgIdentifier(wide)).toBe(`${"é".repeat(27)}_84fe2e03`); +}); + +test("a qualified TPH CHECK name over 63 bytes is fitted on Postgres and kept on SQLite", async () => { + const table = "measurement_devices_with_a_rather_long_table_name"; + const root = await load(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Device", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": table } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "kind", "@maxLength": 20 } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.entity": { name: "MeterDeviceKind", extends: "Device", "@discriminatorValue": "METER", children: [ + { "field.enum": { name: "serial", "@values": ["M1", "M2"] } } ] } }, + { "object.entity": { name: "SensorDeviceKind", extends: "Device", "@discriminatorValue": "SENSOR", children: [ + { "field.enum": { name: "serial", "@values": ["S1", "S2"] } } ] } }, + ] } })); + const names = (dialect: "postgres" | "sqlite") => + buildExpectedSchema(root, { dialect }).tables.find((t) => t.name === table)!.checks + .filter((c) => c.expression.includes('"serial"')).map((c) => c.name); + const pg = names("postgres"); + expect(pg.length).toBe(2); + for (const n of pg) expect(Buffer.byteLength(n)).toBe(63); + expect(pg).toEqual([`${table}_meterdevicekind_serial_chk`, `${table}_sensordevicekind_serial_chk`].map(fitPgIdentifier)); + expect(new Set(pg).size).toBe(2); + expect(names("sqlite")).toEqual([`${table}_meterdevicekind_serial_chk`, `${table}_sensordevicekind_serial_chk`]); }); From 418ae67da9f55b4a6e88f10ec5e2aad12b0b12fb Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 17:35:50 -0500 Subject: [PATCH 187/267] fix(csharp): a reference over a flattened member never takes another reference's sole navigation When the entity declares a second reference from the same owned member to the same target, codegen now emits only the foreign-key match: the navigation over this reference's own properties, or none. With one such reference, the sole-navigation rule stays, and only several navigations with none over the properties is left to the model build. Co-Authored-By: Claude Opus 5.5 --- .../Generators/DbContextGenerator.cs | 15 +++++- .../EfModelGapsTests.cs | 48 +++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index cba6b886c5..bd114b8d6b 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -1602,7 +1602,20 @@ private IEnumerable FlattenedMemberReferenceConfig( var toTarget = $"{linq}.Where(b.OwnedEntityType.GetNavigations(), n => n.TargetEntityType.ClrType == typeof({targetRef}))"; var byFk = $"{linq}.FirstOrDefault({toTarget}, n => {linq}.SequenceEqual({linq}.Select(n.ForeignKey.Properties, p => p.Name), new[] {{ {fkNames} }}))"; var ambiguous = $"new global::System.InvalidOperationException(\"{CSharpNaming.CSharpStringLiteral($"{entity.Name}.{nav} has several navigations to {target.Name} and none over {string.Join(", ", props)}: name the one this reference uses with that foreign key, or remove the others.")}\")"; - var navigation = $"({linq}.Count({toTarget}) == 0 ? null : {linq}.Count({toTarget}) == 1 ? {linq}.First({toTarget}) : ({byFk} ?? throw {ambiguous}))?.Name"; + // rc.21 part B (N3): what codegen can know, it decides here. When this entity declares + // another reference from the same owned member to the same target, a sole navigation may be + // THAT reference's, so only the navigation over these exact properties is this one's; with + // none, the relationship is navigation-less (the other reference keeps its navigation). With + // one reference, a sole navigation can only be this one's, and only "several, none over + // these properties" is left to the model build (the owned CLR type is invisible to codegen). + var siblings = entity.ReferenceIdentities().Count(r => + !ReferenceEquals(r, reference) + && ReferenceEquals(NamingRefs.RefTarget(r, IDENTITY_REFERENCE_ATTR_REFERENCES), target) + && ReferentialActions.ReadIdentityFields(r) is { Count: > 0 } other + && other.All(f => FlattenedMembers.Resolve(entity, f) is { } m && ReferenceEquals(m.Embedding, members[0]!.Embedding))); + var navigation = siblings > 0 + ? $"{byFk}?.Name" + : $"({linq}.Count({toTarget}) == 0 ? null : {linq}.Count({toTarget}) == 1 ? {linq}.First({toTarget}) : ({byFk} ?? throw {ambiguous}))?.Name"; return [$" modelBuilder.Entity<{owner}>().OwnsOne(x => x.{nav}, b => b.HasOne<{targetRef}>({navigation})" + $".WithMany().HasForeignKey({ForeignKeyExpression("e", props)})" + PrincipalKeyCall(reference, target) diff --git a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs index 6610a78f6c..2b4d3d9155 100644 --- a/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs +++ b/server/csharp/MetaObjects.IntegrationTests/EfModelGapsTests.cs @@ -285,6 +285,54 @@ public void A_reference_over_a_flattened_member_uses_the_owned_types_only_naviga Assert.DoesNotContain(address.GetProperties(), p => p.Name is "HomeCountryId" or "CountryId1"); } + // rc.21 part B (N3): two references from one owned member to one target. The owned type has a + // navigation for one of them only; the other must not take it as "the sole navigation". + private const string TwoFlattenedReferencesModel = """ + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Country", "children": [ + { "source.rdb": { "@table": "countries" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } + ]}}, + { "object.value": { "name": "Address", "children": [ + { "field.long": { "name": "homeCountryId" } }, + { "field.long": { "name": "billingCountryId" } } + ]}}, + { "object.entity": { "name": "Plan", "children": [ + { "source.rdb": { "@table": "plans" } }, + { "field.long": { "name": "id" } }, + { "field.object": { "name": "address", "@objectRef": "Address", "@storage": "flattened" } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.reference": { "name": "homeCountryId", "@fields": "address.homeCountryId", "@references": "Country" } }, + { "identity.reference": { "name": "billingCountryId", "@fields": "address.billingCountryId", "@references": "Country" } } + ]}} + ]}} + """; + + private sealed class AddressWithBillingCountry : MetaObjects.Codegen.Generators.EntityGenerator + { + protected override void EmitClassBodyTrailer(System.Text.StringBuilder sb, MetaObjects.Meta.MetaObject entity, MetaObjects.Codegen.GenContext ctx) + { + if (entity.Name == "Address") + sb.AppendLine($" public {MetaObjects.Codegen.ValueObjectNames.GlobalRef(ctx.Root.FindObject("Country")!, ctx.Config)}? BillingCountry {{ get; set; }}"); + } + } + + [Fact] + public void A_sole_navigation_of_another_reference_is_not_taken() + { + var gen = GeneratedEfModel.Compile(TwoFlattenedReferencesModel, "Acme.FlatTwo", entities: new AddressWithBillingCountry()); + using var db = gen.ModelOnlyContext(); + var address = EntityType(db, "Plan").FindNavigation("Address")!.TargetEntityType; + var fks = address.GetForeignKeys().Where(f => f.PrincipalEntityType.ClrType.Name == "Country").ToList(); + Assert.Equal(2, fks.Count); + var billing = Assert.Single(fks, f => f.Properties.Select(p => p.Name).SequenceEqual(new[] { "BillingCountryId" })); + Assert.Equal("BillingCountry", billing.DependentToPrincipal?.Name); + var home = Assert.Single(fks, f => f.Properties.Select(p => p.Name).SequenceEqual(new[] { "HomeCountryId" })); + Assert.Null(home.DependentToPrincipal); + Assert.DoesNotContain(address.GetProperties(), p => p.IsShadowProperty() && !p.IsPrimaryKey()); + } + [Fact] public void A_reference_carries_its_constraint_name_and_its_principal_key_into_the_model() { From 729d3ab43d45d7ae4131e7e4f35427089bbd1fad Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 17:35:53 -0500 Subject: [PATCH 188/267] fix(enum): a filter on a member with no stored string throws in every port; report-row tests A runtime filter on a @stringValueMap member outside the map now throws in the TypeScript runtime and Python, as the Java OMDB bind and the Drizzle codec already did: passed through, the symbol could equal another member's stored string and match that member's rows. Java and Python gain tests for the map carried onto a report row. The CHANGELOG records the CHECK-name, navigation and filter rulings. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 28 ++++++++++++++----- .../reporting/ReportReadModelTest.java | 27 ++++++++++++++++++ .../src/metaobjects/runtime/object_manager.py | 17 +++++------ .../test_object_manager_string_value_map.py | 10 +++++-- server/python/tests/test_report_read_model.py | 18 ++++++++++++ .../packages/runtime-ts/src/query-builder.ts | 16 +++++++++-- .../test/string-value-map-codec.test.ts | 8 ++++++ 7 files changed, 103 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ebadcb3ea..4ceba25175 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,8 +40,12 @@ vocabulary; upgrade every port together. `fromDbValue(String)`, for a hand-written repository, a shared declaration included); and by the Python ObjectManager. A view-backed report's row carries it from its type source, in every port. A stored string that maps to no member throws on read, and a member with no stored string - throws on write, in every port (the map is total, so only a value outside `@values` can reach - that). `metamodelVersion` stays + throws on write and in a runtime filter, in every port (the map is total, so only a value outside + `@values` can reach that). Ruling (rc.21 part B, N4): a filter does not pass such a member + through to match nothing, as an `@intValueMap` symbol does, because a passed-through symbol can + equal another member's stored string and match that member's rows; the TypeScript runtime and + Python now refuse it, as the Java OMDB bind and the Drizzle codec already did (C# and Kotlin + have no value outside the enum). `metamodelVersion` stays `1.3`: the addition lands in the same unreleased minor. Fixtures `fixtures/conformance/enum-string-value-map` and four `error-enum-stringvaluemap-*`; the shared CHECK corpus gains `input/meta.stored.json`. @@ -591,7 +595,10 @@ vocabulary; upgrade every port together. b.HasOne()…)`): its only navigation to the target, whatever its name (`HomeCountry` over `CountryId` too); with several, the one whose foreign key is these properties, and with none of those the model build throws, naming the owner; with none, - navigation-less. One foreign key, no shadow column, and `@onDelete` / `@constraintName` land on it. + navigation-less. When the entity declares a second reference from the same owned member to the + same target, codegen emits only the foreign-key match: a sole navigation may be the other + reference's, so this one takes the navigation over its own properties or none (rc.21 part B, + N3). One foreign key, no shadow column, and `@onDelete` / `@constraintName` land on it. Generated output changes for every reference over a flattened member. - **Breaking, TypeScript and C#: `Names` has no entry for a derived field with no column @@ -651,10 +658,17 @@ vocabulary; upgrade every port together. pattern) each get their own, guarded by their discriminator values and named `
    ___…`; identical ones share one. A subtype's cross-field validator is guarded by the discriminator, as an `@condition` ANDed with its own, listing every concrete - subtype it reaches, and its default name carries its declarer. Two different CHECKs under one - name on a table (a pre-existing hazard too: two comparisons with one left field) are now refused - when the schema is built, naming both, instead of a CREATE TABLE the database refuses. The Drizzle schema already declared the - subtype enum CHECKs, so the two now agree. Pinned by `input/meta.tph.json` in the shared CHECK + subtype it reaches, and its default name carries its declarer. On Postgres a declarer-qualified + default name longer than 63 bytes keeps its first 54 bytes plus `_` and 8 hex digits of its + SHA-256 (the same spelling in `meta migrate`, Drizzle and C#), so Postgres never truncates it. + Two different CHECKs under one name on a table (a pre-existing hazard too: two comparisons with + one left field) are refused where the database requires unique names: on Postgres, by `meta + migrate`, `meta verify --db`, Drizzle and C#, naming both, instead of a CREATE TABLE the database + refuses. SQLite and D1 accept and enforce both (probed on SQLite 3.51 and Miniflare's D1), so + `meta migrate` and Drizzle keep both there, a declared `@constraintName` included, and the + SQLite CHECK diff now matches a name to a list so it converges. C# refuses the pair on every + dialect: EF Core keys a check constraint by name and would keep only the last (verified on EF + Core 8.0.18). The Drizzle schema already declared the subtype enum CHECKs, so the two now agree. Pinned by `input/meta.tph.json` in the shared CHECK corpus. **Upgrade note:** the next `meta migrate` (or EF migration) adds these CHECKs to an existing TPH table; a legacy row outside a rule needs `@dbCheck: false` on that node first. diff --git a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java index 2010e26c07..fb79703820 100644 --- a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java +++ b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportReadModelTest.java @@ -323,6 +323,33 @@ public void aMeasureWithDefaultYieldsADetachedFieldWithRequiredTrue() { assertFalse(required(model.getMetaField("revenueRaw"))); } + @Test + public void anEnumDimensionCarriesItsStringValueMap() { + // rc.21 part B (N5): the row carries @stringValueMap from its type source, as C#, TS and + // Python do, so OMDB's codec decodes the stored string to the member. + MetaRoot root = loadJson(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Article", "children": [ + { "source.rdb": { "@table": "articles" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "status", "@values": ["Draft", "Published"], + "@stringValueMap": { "Draft": "draft", "Published": "published" } } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "identity.primary": { "name": "pk", "@fields": ["id"] } }, + { "dimension.attribute": { "name": "status", "@of": "Article.status" } }, + { "dimension.attribute": { "name": "kind", "@of": "Article.kind" } }, + { "measure.aggregate": { "name": "articles", "@agg": "count", "@of": "Article.id" } } + ] } }, + { "object.report": { "name": "ByStatus", "@from": "Article", "@dimensions": ["status", "kind"], "@measures": ["articles"], + "children": [ { "source.rdb": { "@kind": "view", "@view": "v_by_status" } } ] } } + ] } } + """); + ReportReadModel model = ReportReadModel.of(object(root, "ByStatus"), root); + Object map = model.getMetaField("status").getMetaAttr(EnumField.ATTR_STRING_VALUE_MAP).getValue(); + assertEquals(java.util.Map.of("Draft", "draft", "Published", "published"), map); + assertFalse(model.getMetaField("kind").hasMetaAttr(EnumField.ATTR_STRING_VALUE_MAP)); + } + @Test public void aSourcelessReportHasAShapeAndNoView() { MetaRoot root = loadJson(SALES_MODEL); diff --git a/server/python/src/metaobjects/runtime/object_manager.py b/server/python/src/metaobjects/runtime/object_manager.py index f3d6997569..540d51c769 100644 --- a/server/python/src/metaobjects/runtime/object_manager.py +++ b/server/python/src/metaobjects/runtime/object_manager.py @@ -1222,17 +1222,18 @@ def _coerce_write_value(field: MetaField, value: Any, *, for_filter: bool = Fals return [_encode_enum_member(int_map, v) for v in value] return _encode_enum_member(int_map, value) # rc.21: a @stringValueMap enum stores the member's string (scalar only; the - # loader refuses it on an array). An unmapped member passes through, as above. + # loader refuses it on an array). stored_map = _string_value_map(field) if stored_map is not None and isinstance(value, str): - if value in stored_map or for_filter: - # A filter on a member that does not exist matches nothing, honestly. - return stored_map.get(value, value) - # Written, an unmapped member raises (rc.21 ruling, every port): no CHECK need hold - # behind it (@dbCheck: false), and storing the symbol would write a spelling the - # column does not hold. + if value in stored_map: + return stored_map[value] + # An unmapped member raises, written or filtered (rc.21 rulings, every port). Written: + # no CHECK need hold behind it (@dbCheck: false), and storing the symbol would write a + # spelling the column does not hold. Filtered: passed through, the symbol could equal + # ANOTHER member's stored string and match that member's rows. + verb = "filter on" if for_filter else "write" raise ValueError( - f"field.enum '{field.name}' cannot write {value!r}: it has no stored string in " + f"field.enum '{field.name}' cannot {verb} {value!r}: it has no stored string in " f"@{fc.FIELD_ATTR_STRING_VALUE_MAP} — the value is not one of the members the model declares." ) diff --git a/server/python/tests/runtime/test_object_manager_string_value_map.py b/server/python/tests/runtime/test_object_manager_string_value_map.py index 0030018ad4..0c74f3f66c 100644 --- a/server/python/tests/runtime/test_object_manager_string_value_map.py +++ b/server/python/tests/runtime/test_object_manager_string_value_map.py @@ -39,9 +39,13 @@ def test_an_unmapped_stored_string_raises() -> None: _decode_read_value(_status(), "lost") -def test_writing_an_unmapped_member_raises_but_a_filter_passes_it_through() -> None: +def test_an_unmapped_member_raises_written_or_filtered() -> None: + # rc.21 part B (N4): a filter on an unmapped member raises, as a write does, in every port — + # passed through, the symbol could equal another member's stored string. from metaobjects.runtime.object_manager import _coerce_filter_value field = _status() - with pytest.raises(ValueError, match="no stored string in @stringValueMap"): + with pytest.raises(ValueError, match="cannot write 'Archived': it has no stored string in @stringValueMap"): _coerce_write_value(field, "Archived") - assert _coerce_filter_value(field, "Archived") == "Archived" + with pytest.raises(ValueError, match="cannot filter on 'Archived': it has no stored string in @stringValueMap"): + _coerce_filter_value(field, "Archived") + assert _coerce_filter_value(field, "Draft") == "draft" diff --git a/server/python/tests/test_report_read_model.py b/server/python/tests/test_report_read_model.py index cd37a93f81..90c1522120 100644 --- a/server/python/tests/test_report_read_model.py +++ b/server/python/tests/test_report_read_model.py @@ -23,6 +23,7 @@ FIELD_ATTR_PRECISION, FIELD_ATTR_REQUIRED, FIELD_ATTR_SCALE, + FIELD_ATTR_STRING_VALUE_MAP, FIELD_ATTR_VALUES, ) from metaobjects.meta.core.field.meta_field import MetaField @@ -215,3 +216,20 @@ def test_a_measure_with_default_yields_a_detached_field_with_required_true() -> ("revenueRaw", False), ] assert all(f.get_meta_attr(FIELD_ATTR_DEFAULT) is None for f in fields) + + +def test_string_value_map_is_carried_from_the_type_source() -> None: + """rc.21 part B (N5): a report row over a ``@stringValueMap`` enum carries the map (read + RESOLVING), so the row decodes the stored string to the member, as C# and TypeScript do.""" + model = json.loads(json.dumps(_MODEL)) + sale = model["metadata.root"]["children"][1]["object.entity"] + for child in sale["children"]: + if "field.enum" in child: + child["field.enum"]["@stringValueMap"] = {"OPEN": "open", "PAID": "paid"} + result = MetaDataLoader().load([InMemoryStringSource(json.dumps(model), "meta.shop.json")]) + assert result.errors == [], [e.message for e in result.errors] + report = next(c for c in result.root.children() if c.type == TYPE_OBJECT and c.name == "R") + status = {f.name: f for f in report_read_model(report, result.root).fields()}["status"] + assert status.get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP) == {"OPEN": "open", "PAID": "paid"} + # Without the map on the source, the row carries none. + assert _fields()["status"].get_meta_attr(FIELD_ATTR_STRING_VALUE_MAP) is None diff --git a/server/typescript/packages/runtime-ts/src/query-builder.ts b/server/typescript/packages/runtime-ts/src/query-builder.ts index d3aa0ebee6..70c299bb1e 100644 --- a/server/typescript/packages/runtime-ts/src/query-builder.ts +++ b/server/typescript/packages/runtime-ts/src/query-builder.ts @@ -185,9 +185,19 @@ function encodeFilterValue(field: MetaData, value: T, dialect?: Dialect): T { if (dialect === "memory") return micros as T; return formatDuration(micros) as T; } - // rc.21: a @stringValueMap enum is compared as the member's stored string. - if (field.subType === FIELD_SUBTYPE_ENUM && typeof value === "string" && stringValueMapOf(field) !== undefined) { - return storedEnumValue(field, value) as T; + // rc.21: a @stringValueMap enum is compared as the member's stored string. Unlike an + // @intValueMap symbol (which cannot equal an integer), an unmapped member passed through could + // equal ANOTHER member's stored string and match its rows, so it is refused, as a write is + // (rc.21 part B ruling N4, every port). + const storedMap = field.subType === FIELD_SUBTYPE_ENUM && typeof value === "string" ? stringValueMapOf(field) : undefined; + if (storedMap !== undefined) { + if (typeof storedMap[value as string] !== "string") { + throw new MetadataError( + `filter on field.enum '${field.name}': ${JSON.stringify(value)} has no stored string in @stringValueMap ` + + `(declared: ${JSON.stringify(storedMap)}) — the value is not one of the members the model declares.`, + ); + } + return storedEnumValue(field, value as string) as T; } const intMap = intValueMapOf(field); if (intMap === undefined || typeof value !== "string") return value; diff --git a/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts index ae6de4cab9..9e9201549e 100644 --- a/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts +++ b/server/typescript/packages/runtime-ts/test/string-value-map-codec.test.ts @@ -40,4 +40,12 @@ describe("@stringValueMap — an unmapped member", () => { const entity = await upload(); expect(() => coerceRowOnWrite(entity, { id: 1, status: "Archived" }, "postgres")).toThrow(/cannot write 'Archived'/); }); + + // rc.21 part B (N4): a filter refuses it too, in every port. Passed through, a symbol can equal + // another member's stored string ({ A: "B", B: "C" } filtering "B" would match member A's rows). + test("is refused in a filter, naming the field", async () => { + const entity = await upload(); + expect(() => compileFilter(entity, { status: "Archived" })).toThrow(/filter on field.enum 'status': "Archived" has no stored string/); + expect(() => compileFilter(entity, { status: { $in: ["Draft", "Archived"] } })).toThrow(/"Archived" has no stored string/); + }); }); From 4e717cf51116b015c0c263dff8ae971a68b6401d Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 18:06:10 -0500 Subject: [PATCH 189/267] feat(views): the rc.21 view vocabulary in the spec and TypeScript A projection can now build in metadata the views that needed @sql: - @dbColumnType takes the text spellings text, varchar / character varying, varchar(n) / character varying(n) and character(n) on a field.string (meta migrate, Drizzle and the view cast honour them; an unbounded varchar and text compare as one type). - @expr gains { cast, as, dbColumnType? } and a closed, typed function set beside coalesce: greatest, least, nullif, lower, upper, btrim, splitPart, concat, concatWs, substring, replace, left, right, length. SQLite gets equivalent spellings, and refuses what it cannot mean. - A { field } ref may name a scalar origin.aggregate (read on the grouped row) or, on a projection, a path of to-one hops joined but not output; a correlated @filter operand may be such a path too. - origin.function: a value computed by a database function the project owns, named and typed, never free SQL (Postgres only). - @grain / @grainOrdinal: one row per element of a jsonb field.object array; @union / @unionAll: a view that is the union of projections of one shape, checked at load. A grouped view now groups the joined columns its expressions read. A cross-field @condition takes only the CHECK subset of the grammar. Co-Authored-By: Claude Opus 5.5 --- .../expected-registry.json | 174 +++++------ .../MetaObjects/SpecMetamodel/attr.json | 2 +- .../csharp/MetaObjects/SpecMetamodel/db.json | 2 +- .../MetaObjects/SpecMetamodel/object.json | 4 + .../MetaObjects/SpecMetamodel/origin.json | 11 + .../src/metaobjects/spec_metamodel/attr.json | 2 +- .../src/metaobjects/spec_metamodel/db.json | 2 +- .../metaobjects/spec_metamodel/object.json | 4 + .../metaobjects/spec_metamodel/origin.json | 11 + .../packages/codegen-ts/src/column-mapper.ts | 9 +- .../src/projection/build-projection-views.ts | 12 +- .../src/projection/extract-view-spec.ts | 273 ++++++++++++++++-- .../src/projection/view-ddl-emit.ts | 206 ++++++++++--- .../codegen-ts/src/projection/view-spec.ts | 45 ++- .../rc21b-view-vocabulary.fixture.ts | 68 +++++ .../test/projection/tier2-vocabulary.test.ts | 12 +- .../test/view-vocabulary-rc21-pg.test.ts | 196 +++++++++++++ .../metadata/src/attr-schema-validate.ts | 29 +- .../src/core/attr/attr-definition.embedded.ts | 2 +- .../src/core/attr/meta-attr-expression.ts | 214 ++++++++++++-- .../src/core/object/object-constants.ts | 5 + .../core/object/object-definition.embedded.ts | 33 +++ .../typescript/packages/metadata/src/index.ts | 5 +- .../metadata/src/loader/meta-data-loader.ts | 4 +- .../metadata/src/loader/validation-passes.ts | 264 +++++++++++++++-- .../src/persistence/db/db-constants.ts | 55 +++- .../persistence/db/db-definition.embedded.ts | 6 +- .../persistence/origin/origin-constants.ts | 11 + .../origin/origin-definition.embedded.ts | 33 +++ .../metadata/test/types/origin.test.ts | 4 +- .../packages/migrate-ts/src/emit/postgres.ts | 5 +- .../packages/migrate-ts/src/emit/sqlite.ts | 5 +- .../migrate-ts/src/expected-schema.ts | 6 + .../migrate-ts/src/introspect/postgres.ts | 8 +- .../src/introspect/sqlite-shared.ts | 6 +- .../packages/migrate-ts/src/sql-type.ts | 20 +- spec/metamodel/attr.json | 2 +- spec/metamodel/db.json | 2 +- spec/metamodel/object.json | 4 + spec/metamodel/origin.json | 11 + 40 files changed, 1536 insertions(+), 231 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts create mode 100644 server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index dadc0a44ce..48ed0890fa 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -32,7 +32,7 @@ { "type": "attr", "subType": "expression", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159.", + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.", "attrs": [], "children": [] }, @@ -163,11 +163,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -305,11 +301,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -455,11 +447,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -608,11 +596,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -751,11 +735,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -907,11 +887,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1049,11 +1025,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1213,11 +1185,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1415,11 +1383,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1557,11 +1521,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1706,11 +1666,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1848,11 +1804,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -1991,11 +1943,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2148,11 +2096,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2316,11 +2260,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2486,11 +2426,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2639,11 +2575,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2788,11 +2720,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -2937,11 +2865,7 @@ "valueType": "string", "isArray": false, "required": false, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." }, { "name": "default", @@ -3690,6 +3614,20 @@ "required": false, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { + "name": "grain", + "valueType": "string", + "isArray": false, + "required": false, + "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." + }, + { + "name": "grainOrdinal", + "valueType": "string", + "isArray": false, + "required": false, + "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." + }, { "name": "object", "valueType": "string", @@ -3710,6 +3648,20 @@ "kotlin" ], "description": "JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it." + }, + { + "name": "union", + "valueType": "string", + "isArray": true, + "required": false, + "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." + }, + { + "name": "unionAll", + "valueType": "boolean", + "isArray": false, + "required": false, + "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." } ], "children": [ @@ -4123,6 +4075,36 @@ ], "children": [] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "attrs": [ + { + "name": "args", + "valueType": "string", + "isArray": true, + "required": false, + "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." + }, + { + "name": "function", + "valueType": "string", + "isArray": false, + "required": true, + "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." + }, + { + "name": "schema", + "valueType": "string", + "isArray": false, + "required": false, + "description": "The schema the function lives in, a plain identifier. Absent: public." + } + ], + "children": [] + }, { "type": "origin", "subType": "passthrough", diff --git a/server/csharp/MetaObjects/SpecMetamodel/attr.json b/server/csharp/MetaObjects/SpecMetamodel/attr.json index 0ccb0600b4..c05dab28b7 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/attr.json +++ b/server/csharp/MetaObjects/SpecMetamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/server/csharp/MetaObjects/SpecMetamodel/db.json b/server/csharp/MetaObjects/SpecMetamodel/db.json index 4b6a2d2452..e6b2898755 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/db.json +++ b/server/csharp/MetaObjects/SpecMetamodel/db.json @@ -7,7 +7,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, - { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "allowedValues": ["uuid", "jsonb"], "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, { diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index ad1afce6de..7dbadfcd07 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -55,6 +55,10 @@ "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index c4fde970f9..08e8584d24 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -42,6 +42,17 @@ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." } + ] + }, { "type": "origin", "subType": "first", diff --git a/server/python/src/metaobjects/spec_metamodel/attr.json b/server/python/src/metaobjects/spec_metamodel/attr.json index 0ccb0600b4..c05dab28b7 100644 --- a/server/python/src/metaobjects/spec_metamodel/attr.json +++ b/server/python/src/metaobjects/spec_metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/db.json b/server/python/src/metaobjects/spec_metamodel/db.json index 4b6a2d2452..e6b2898755 100644 --- a/server/python/src/metaobjects/spec_metamodel/db.json +++ b/server/python/src/metaobjects/spec_metamodel/db.json @@ -7,7 +7,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, - { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "allowedValues": ["uuid", "jsonb"], "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, { diff --git a/server/python/src/metaobjects/spec_metamodel/object.json b/server/python/src/metaobjects/spec_metamodel/object.json index ad1afce6de..7dbadfcd07 100644 --- a/server/python/src/metaobjects/spec_metamodel/object.json +++ b/server/python/src/metaobjects/spec_metamodel/object.json @@ -55,6 +55,10 @@ "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index c4fde970f9..08e8584d24 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -42,6 +42,17 @@ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." } + ] + }, { "type": "origin", "subType": "first", diff --git a/server/typescript/packages/codegen-ts/src/column-mapper.ts b/server/typescript/packages/codegen-ts/src/column-mapper.ts index 9944f3b8c0..2cfb5e5242 100644 --- a/server/typescript/packages/codegen-ts/src/column-mapper.ts +++ b/server/typescript/packages/codegen-ts/src/column-mapper.ts @@ -38,6 +38,7 @@ import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + parseDbColumnType, FIELD_ATTR_LOCAL_TIME, FIELD_ATTR_LENIENT, TYPE_ORIGIN, @@ -368,9 +369,13 @@ function pgColumnTypeOverride( return { fnName: "uuid" }; case DB_COLUMN_TYPE_JSONB: return { fnName: "jsonb" }; - default: - return undefined; } + // rc.21 part B (U2): the text spellings, as `meta migrate` creates them. + const parsed = parseDbColumnType(dbColumnType); + if (parsed?.kind === "text") return { fnName: "text" }; + if (parsed?.kind === "varchar") return parsed.length !== undefined ? { fnName: "varchar", fnOptions: { length: parsed.length } } : { fnName: "varchar" }; + if (parsed?.kind === "char") return { fnName: "char", fnOptions: { length: parsed.length } }; + return undefined; } /** Resolve max length from validator.length child or @maxLength attr. diff --git a/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts b/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts index bf4ab37213..3ca52a3ab5 100644 --- a/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts +++ b/server/typescript/packages/codegen-ts/src/projection/build-projection-views.ts @@ -463,7 +463,12 @@ function collectDependsOn( case "first": first(e.column); return; case "cmp": expr(e.left); expr(e.right); return; case "nullTest": case "not": expr(e.arg); return; - case "logic": case "coalesce": e.args.forEach(expr); return; + case "logic": case "coalesce": case "fn": case "call": e.args.forEach(expr); return; + case "cast": expr(e.arg); return; + case "agg": + if (e.column.kind === "aggregate" && e.column.filter !== undefined) clause(e.column.filter); + if (e.column.kind === "predicateAgg") clause(e.column.pred); + return; case "case": if (e.operand !== undefined) expr(e.operand); for (const w of e.whens) { expr(w.when); expr(w.then); } @@ -483,5 +488,10 @@ function collectDependsOn( else if (c.kind === "predicateAgg") clause(c.pred); } if (spec.where !== undefined) clause(spec.where); + // rc.21 part B (U15): a union reads every member's tables too. + for (const m of spec.union?.members ?? []) { + const t = joinTables[m.joinTree.baseEntity]; + for (const mt of collectDependsOn(m, t ?? baseTableName, joinTables)) tables.add(mt); + } return [...tables]; } diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index 0cac60fda0..eeb17f85ac 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -28,6 +28,19 @@ import { ORIGIN_FIRST_ATTR_OF, ORIGIN_FIRST_ATTR_VIA, ORIGIN_FIRST_ATTR_FILTER, + ORIGIN_SUBTYPE_FUNCTION, + ORIGIN_FUNCTION_ATTR_FUNCTION, + ORIGIN_FUNCTION_ATTR_SCHEMA, + ORIGIN_FUNCTION_ATTR_ARGS, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, + EXPR_CAST, + EXPR_CAST_AS, + EXPR_CAST_DB_COLUMN_TYPE, + EXPR_FUNCTIONS, + parseDbColumnType, AGG_ANY, AGG_ALL, AGG_COLLECT, @@ -95,7 +108,7 @@ import type { RelativeNow } from "./report-spec.js"; import type { ReportTemporal } from "./time-sql.js"; import type { JoinNode, JoinTree, SelectColumn, SelectSpec, ViewSpec, ViewFilterClause, - ViewExprNode, ViewExprLiteral, ViewOrderKey, FirstInnerJoin, TphScope, FirstColumn, ColRef, + ViewExprNode, ViewExprLiteral, ViewOrderKey, FirstInnerJoin, TphScope, FirstColumn, ColRef, CastTarget, } from "./view-spec.js"; /** Compose keys in the attr.filter shape. */ @@ -214,6 +227,15 @@ function resolveAggregateFilter( export interface OuterRow { readonly entity: MetaObject; readonly alias: string; + /** rc.21 part B (U4): the to-one paths from the outer row the view joined, by dotted key. */ + readonly paths?: ReadonlyMap; +} + +/** rc.21 part B (U3, U4): a to-one path from the base the view joined (not output): its end's alias and field. */ +export interface PathRef { + readonly alias: string; + readonly field: MetaField; + readonly entity: MetaObject; } /** A `{ field: "" }` operand (correlated-filter), not a relative date. */ @@ -252,6 +274,17 @@ function lowerFilterValue( } if (isFieldOperand(raw)) { const name = raw[FILTER_OPERAND_FIELD]; + if (name.includes(".")) { + // rc.21 part B (U4): a path operand reads the joined row at its end. + const path = outer?.paths?.get(name); + if (path === undefined) { + throw new Error(`${where}: "${key}" compares with the path "${name}", which the outer row did not join (a path operand is legal only on a projection's own origins).`); + } + if (path.field.isDerived()) { + throw new Error(`${where}: "${key}" compares with the path "${name}", a derived field; a path operand reads a stored column.`); + } + return { kind: "colRef", ref: `${path.alias}.${sourceColumnNameFor(path.field, ctx)}` } satisfies ColRef; + } const other = outer?.entity.fields().find((f) => f.name === name); if (outer === undefined || other === undefined) { throw new Error(`${where}: "${key}" compares with base-row field "${name}", which the base row does not have.`); @@ -934,11 +967,24 @@ function resolveExprNode( ...(otherwise !== undefined ? { else: otherwise } : {}), }; } + if (EXPR_CAST in raw) { + // rc.21 part B (U12): a cast to a field subtype's column type, optionally a text spelling. + const arg = sub(raw[EXPR_CAST]); + const as = raw[EXPR_CAST_AS]; + if (arg === undefined || typeof as !== "string") return undefined; + const spelling = typeof raw[EXPR_CAST_DB_COLUMN_TYPE] === "string" ? parseDbColumnType(raw[EXPR_CAST_DB_COLUMN_TYPE] as string) : undefined; + const to: CastTarget = spelling !== undefined && spelling.kind !== "uuid" && spelling.kind !== "jsonb" + ? { subType: as, spelling: { kind: spelling.kind, ...("length" in spelling && spelling.length !== undefined ? { length: spelling.length } : {}) } } + : { subType: as }; + return { kind: "cast", arg, to }; + } if ("fn" in raw) { - if (raw.fn !== EXPR_FN_COALESCE || !Array.isArray(raw.args)) return undefined; + if (typeof raw.fn !== "string" || !Object.prototype.hasOwnProperty.call(EXPR_FUNCTIONS, raw.fn) || !Array.isArray(raw.args)) return undefined; const args = raw.args.map((a) => sub(a)); if (args.some((a) => a === undefined)) return undefined; - return { kind: "coalesce", args: args as ViewExprNode[] }; + if (raw.fn === EXPR_FN_COALESCE) return { kind: "coalesce", args: args as ViewExprNode[] }; + // rc.21 part B (U11, U13): the rest of the closed function set. + return { kind: "fn", name: raw.fn, args: args as ViewExprNode[] }; } if ("op" in raw && typeof raw.op === "string") { const op = raw.op; @@ -979,6 +1025,77 @@ function temporalOfField(f: MetaField): ReportTemporal { return f.subType === FIELD_SUBTYPE_DATE || f.subType === FIELD_SUBTYPE_TIMESTAMP ? temporalOf(f) : "instant"; } +/** rc.21 part B (U10): an origin.function's call, each argument resolved by `arg` (undefined if one does not). */ +function functionCall(origin: MetaData, arg: (name: string) => ViewExprNode | undefined): ViewExprNode | undefined { + // ADR-0039: own — origin.* never inherits (ADR-0029). + const name = origin.ownAttr(ORIGIN_FUNCTION_ATTR_FUNCTION); + const schema = origin.ownAttr(ORIGIN_FUNCTION_ATTR_SCHEMA); + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + if (typeof name !== "string") return undefined; + const names = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; + const args = names.map((n) => (typeof n === "string" ? arg(n) : undefined)); + if (args.some((a) => a === undefined)) return undefined; + return { kind: "call", name, ...(typeof schema === "string" ? { schema } : {}), args: args as ViewExprNode[] }; +} + +/** rc.21 part B (U14): the value object a `@grain` projection's rows are elements of, if it has one. */ +function grainValueObject(projection: MetaObject, base: MetaObject): MetaObject | undefined { + if (projection === base) return undefined; + const grain = projection.attr(OBJECT_PROJECTION_ATTR_GRAIN); + if (typeof grain !== "string") return undefined; + const field = base.fields().find((f) => f.name === grain); + const vo = field === undefined ? undefined : refTarget(field, FIELD_ATTR_OBJECT_REF); + return vo !== undefined && isMetaObject(vo) ? vo : undefined; +} + +/** Every `{ field }` name an expression tree reads, through every node kind. */ +function exprFieldNames(node: unknown, out: string[] = []): string[] { + if (!isPlainObject(node)) return out; + if (typeof node.field === "string") out.push(node.field); + for (const key of ["left", "right", "arg", EXPR_CAST, EXPR_CASE_OPERAND, EXPR_CASE_ELSE]) exprFieldNames(node[key], out); + if (Array.isArray(node.args)) for (const a of node.args) exprFieldNames(a, out); + if (Array.isArray(node[EXPR_CASE])) { + for (const arm of node[EXPR_CASE] as unknown[]) { + if (isPlainObject(arm)) { exprFieldNames(arm[EXPR_CASE_WHEN], out); exprFieldNames(arm[EXPR_CASE_THEN], out); } + } + } + return out; +} + +/** Every `{ field: "" }` operand of a filter, through and/or. */ +function filterOperandNames(filter: unknown, out: string[] = []): string[] { + if (!isPlainObject(filter)) return out; + for (const [key, val] of Object.entries(filter)) { + if (key === FILTER_AND || key === FILTER_OR) { + if (Array.isArray(val)) for (const sub of val) filterOperandNames(sub, out); + continue; + } + if (!isPlainObject(val)) continue; + for (const operand of Object.values(val)) if (isFieldOperand(operand)) out.push(operand[FILTER_OPERAND_FIELD]); + } + return out; +} + +/** + * rc.21 part B (U3, U4): the dotted names a projection's own origins read that are not its fields — + * an origin.computed expression's path refs, and an origin.first / origin.aggregate @filter's path + * operands. Each is a to-one path from the base the view joins without outputting it. + */ +function originPathKeys(projection: MetaObject): string[] { + const keys: string[] = []; + // G13: effective fields; ADR-0039: own — origin.* never inherits (ADR-0029). + for (const f of projection.fields()) { + for (const origin of f.ownChildren()) { + if (origin.type !== TYPE_ORIGIN) continue; + if (origin.subType === ORIGIN_SUBTYPE_COMPUTED) keys.push(...exprFieldNames(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))); + if (origin.subType === ORIGIN_SUBTYPE_FIRST || origin.subType === ORIGIN_SUBTYPE_AGGREGATE) { + keys.push(...filterOperandNames(origin.ownAttr(ORIGIN_FIRST_ATTR_FILTER))); + } + } + } + return keys.filter((k) => k.includes(".")); +} + export function shortAliasFor(entityName: string, used: Set): string { // Derive from the SHORT name — an entity ref may now be a resolutionKey ("pkg::Name", // #244); the alias must stay the first letter of the entity, so existing single-package @@ -1323,8 +1440,14 @@ function buildSelectSpec( root: MetaRoot, ctx: ExtractContext, usedAliases: Set, + /** rc.21 part B (U3, U4): the joined to-one paths an expression or an operand reads. */ + pathRefs: ReadonlyMap = new Map(), ): SelectSpec { const columns: SelectColumn[] = []; + const outerRow: OuterRow = { entity: base, alias: joinTree.baseAlias, paths: pathRefs }; + // rc.21 part B (U14): a @grain view's rows are the elements of the base's array field. + const grainVo = grainValueObject(projection, base); + const grainOrdinal = grainVo === undefined ? undefined : projection.attr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL); // Referrer package for resolving bare @from/@of/@via entity refs (FQN refs ignore it). const projPkg = packageOf(projection); @@ -1353,6 +1476,11 @@ function buildSelectSpec( const origin = field.ownChildren().find((c) => c.type === TYPE_ORIGIN); const dbCol = sourceColumnNameFor(field, ctx); + if (!origin && grainVo !== undefined && field.name === grainOrdinal) { + // rc.21 part B (U14): the element's 1-based position. + columns.push({ kind: "element", fieldName: field.name, dbColAlias: dbCol, castTo: fieldSqlType(field) }); + continue; + } if (!origin) { // rc.19 entity-derived: a field bound to a DERIVED base field has no base column; its // derivation is inlined on the base row. @@ -1385,6 +1513,11 @@ function buildSelectSpec( const fieldName = from.slice(dotIdx + 1); const targetEntity = resolveEntityRef(root, from.slice(0, dotIdx), projPkg); if (!targetEntity) continue; + if (grainVo !== undefined && targetEntity === grainVo) { + // rc.21 part B (U14): a member of the array element, cast to the field's column type. + columns.push({ kind: "element", fieldName: field.name, dbColAlias: dbCol, member: fieldName, castTo: fieldSqlType(field) }); + continue; + } const passthroughVia = origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) as string | undefined; const sourceAlias = originSourceAlias(joinTree, passthroughVia, targetEntity.resolutionKey(), root, projPkg, ctx); if (sourceAlias === undefined) continue; @@ -1430,7 +1563,7 @@ function buildSelectSpec( if (sourceAlias === undefined) continue; const joinedPk = primaryKeyColumn(relatedEntity, ctx); if (joinedPk === undefined) continue; - const pred = originScope(origin, filterAttr, relatedEntity, sourceAlias, ctx, { entity: base, alias: joinTree.baseAlias }); + const pred = originScope(origin, filterAttr, relatedEntity, sourceAlias, ctx, outerRow); if (pred === undefined) continue; // loader requires @filter on any/all columns.push({ kind: "predicateAgg", @@ -1529,7 +1662,7 @@ function buildSelectSpec( if (SCALAR_AGG_FUNCTIONS.has(agg)) { // Optional scoping filter — resolved against the aggregated entity (the @of // entity, reached at `sourceAlias`), e.g. max(version) over only active rows. - const filter = originScope(origin, filterAttr, targetEntity, sourceAlias, ctx, { entity: base, alias: joinTree.baseAlias }); + const filter = originScope(origin, filterAttr, targetEntity, sourceAlias, ctx, outerRow); columns.push({ kind: "aggregate", fieldName: field.name, @@ -1550,8 +1683,13 @@ function buildSelectSpec( } else if (origin.subType === ORIGIN_SUBTYPE_FIRST) { // #195 correlated latest-row — argmax-then-project. Resolves to a correlated // subquery (NOT a join). ADR-0039: own — origin.* never inherits (ADR-0029). - const first = buildFirstColumn(field, origin, base, joinTree.baseAlias, root, projPkg, usedAliases, ctx); + const first = buildFirstColumn(field, origin, base, joinTree.baseAlias, root, projPkg, usedAliases, ctx, pathRefs); if (first !== undefined) columns.push(first); + } else if (origin.subType === ORIGIN_SUBTYPE_FUNCTION) { + // rc.21 part B (U10): a call of a database function; its arguments may name other + // projection fields, so it resolves with the computed columns, in this column's place. + pendingComputed.set(field.name, { index: columns.length, origin, field }); + columns.push({ kind: "computed", fieldName: field.name, dbColAlias: dbCol, expr: { kind: "lit", value: null } }); } } @@ -1569,6 +1707,14 @@ function buildSelectSpec( resolving.add(name); const lookup = (ref: string): ResolvedRef | undefined => { if (ref === name) return undefined; // its own name is the base field's + // rc.21 part B (U3): a path of to-one hops from the base, joined but not output. + const path = ref.includes(".") && !fieldByName.has(ref) ? pathRefs.get(ref) : undefined; + if (path !== undefined) { + const expr: ViewExprNode = path.field.isDerived() + ? inlineEntityDerived(path.field, path.entity, path.alias, root, usedAliases, ctx, `Projection ${projection.name}: "${name}" path "${ref}"`) + : { kind: "col", ref: `${path.alias}.${sourceColumnNameFor(path.field, ctx)}` }; + return { expr, field: path.field }; + } const f = fieldByName.get(ref); const c = byName.get(ref); if (f === undefined || c === undefined) return undefined; @@ -1579,9 +1725,13 @@ function buildSelectSpec( if (c.kind === "passthrough") return { expr: { kind: "col", ref: `${c.sourceAlias}.${c.sourceColumn}` }, field: f }; if (c.kind === "computed") return { expr: c.expr, field: f }; if (c.kind === "first") return { expr: { kind: "first", column: c }, field: f }; - throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to "${ref}", an aggregate; a computed value cannot read one.`); + // rc.21 part B (U13): a scalar aggregate (or any/all) is read on the grouped row. + if (c.kind === "aggregate" || c.kind === "predicateAgg") return { expr: { kind: "agg", column: c }, field: f }; + throw new Error(`Projection ${projection.name}: origin.computed "${name}" refers to "${ref}", a collect; a computed value cannot read an array.`); }; - const expr = resolveExprNode(pending.origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), base, joinTree.baseAlias, ctx, lookup); + const expr = pending.origin.subType === ORIGIN_SUBTYPE_FUNCTION + ? functionCall(pending.origin, (arg) => resolveExprNode({ field: arg }, base, joinTree.baseAlias, ctx, lookup)) + : resolveExprNode(pending.origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR), base, joinTree.baseAlias, ctx, lookup); resolving.delete(name); pendingComputed.delete(name); if (expr === undefined) return undefined; @@ -1612,6 +1762,7 @@ function buildFirstColumn( projPkg: string, usedAliases: Set, ctx: ExtractContext, + paths?: ReadonlyMap, ): FirstColumn | undefined { const dbCol = sourceColumnNameFor(field, ctx); const of_ = origin.ownAttr(ORIGIN_FIRST_ATTR_OF) as string | undefined; @@ -1641,7 +1792,7 @@ function buildFirstColumn( // keeps the direct correlation below, so its SQL is unchanged. const firstVia = origin.ownAttr(ORIGIN_FIRST_ATTR_VIA); if (typeof firstVia === "string" && firstVia.split(".").length > 2) { - return firstAlongPath(field.name, dbCol, firstVia, ofField, childEntity, origin, root, projPkg, usedAliases, ctx, { entity: base, alias: baseAlias }) as FirstColumn; + return firstAlongPath(field.name, dbCol, firstVia, ofField, childEntity, origin, root, projPkg, usedAliases, ctx, { entity: base, alias: baseAlias, ...(paths !== undefined ? { paths } : {}) }) as FirstColumn; } const refs = findReferencesBetween(base, childEntity); // findReferencesBetween walks BOTH directions ([base,child] then [child,base]), @@ -1684,7 +1835,7 @@ function buildFirstColumn( const filterAttr = origin.ownAttr(ORIGIN_FIRST_ATTR_FILTER); const childScope = tphScopeOf(childEntity, ctx); const filter = andClauses( - originScope(origin, filterAttr, childEntity, childAlias, ctx, { entity: base, alias: baseAlias }), + originScope(origin, filterAttr, childEntity, childAlias, ctx, { entity: base, alias: baseAlias, ...(paths !== undefined ? { paths } : {}) }), childScope !== undefined ? tphScopeClause(childScope, childAlias) : undefined, ); return { @@ -1837,10 +1988,14 @@ export function inlineEntityDerived( } else if (origin?.subType === ORIGIN_SUBTYPE_FIRST) { const first = buildFirstColumn(field, origin, entity, alias, root, packageOf(entity), usedAliases, ctx); if (first !== undefined) return { kind: "first", column: { ...first, outerAlias: alias } }; + } else if (origin?.subType === ORIGIN_SUBTYPE_FUNCTION) { + // rc.21 part B (U10): the call, its arguments read on the reached row. + const call = functionCall(origin, (arg) => resolveExprNode({ field: arg }, entity, alias, ctx)); + if (call !== undefined) return call; } throw new Error( `${where}: "${entity.name}.${field.name}" is derived by ${origin === undefined ? "nothing" : `origin.${origin.subType}`}, ` + - `which a view cannot inline where it reaches the entity; only origin.computed and origin.first can be.`, + `which a view cannot inline where it reaches the entity; only origin.computed, origin.first and origin.function can be.`, ); } @@ -1864,7 +2019,7 @@ function countManyBranches(joinTree: JoinTree): number { return joinTree.joins.filter(hasMany).length; } -function buildGroupBy(spec: SelectSpec): string[] { +function buildGroupBy(spec: SelectSpec, baseAlias: string): string[] { // predicateAgg (bool_or/bool_and), collectAgg (array_agg) and collectObjectAgg // (jsonb_agg) are real aggregates and force GROUP BY too; computed/first are // scalar-per-row and never grouped. @@ -1873,9 +2028,54 @@ function buildGroupBy(spec: SelectSpec): string[] { || c.kind === "collectAgg" || c.kind === "collectObjectAgg", ); if (!hasAgg) return []; - return spec.columns + const keys = spec.columns .filter((c) => c.kind === "passthrough") .map((c) => `${c.sourceAlias}.${c.sourceColumn}`); + // rc.21 part B (U3, U13): every column a non-aggregate expression reads must be grouped, or + // depend on a grouped key. The base row's do (its primary key is grouped); a JOINED row's need + // not, now that an expression may read a joined column the view does not output (a path) or sit + // over an aggregate. So each joined column a computed expression or an origin.first's correlation + // reads outside an aggregate is grouped too, once. A base-only expression is unchanged. + const add = (ref: string): void => { + if (!ref.startsWith(`${baseAlias}.`) && !keys.includes(ref)) keys.push(ref); + }; + const firstRefs = (f: FirstColumn): void => { + const outer = f.outerAlias ?? baseAlias; + add(`${outer}.${f.referenceHolder === "source" ? f.fkColumn : f.pkColumn}`); + for (const v of filterColRefs(f.filter)) add(v); + }; + const walk = (e: ViewExprNode): void => { + if (e.kind === "col") add(e.ref); + else if (e.kind === "first") firstRefs(e.column); + else if (e.kind !== "agg") exprChildren(e).forEach(walk); + }; + for (const c of spec.columns) { + if (c.kind === "computed") walk(c.expr); + else if (c.kind === "first") firstRefs(c); + } + return keys; +} + +/** The outer-row columns (correlated operands) a filter compares with. */ +function filterColRefs(f: ViewFilterClause | undefined, out: string[] = []): string[] { + if (f === undefined) return out; + if (f.kind === "and" || f.kind === "or") for (const c of f.clauses) filterColRefs(c, out); + else if (f.kind === "cmp" && isPlainObject(f.value) && (f.value as { kind?: unknown }).kind === "colRef") { + out.push((f.value as unknown as ColRef).ref); + } + return out; +} + +/** A resolved expression node's sub-expressions. */ +function exprChildren(e: ViewExprNode): ViewExprNode[] { + switch (e.kind) { + case "cmp": return [e.left, e.right]; + case "nullTest": case "not": return [e.arg]; + case "logic": case "coalesce": case "fn": case "call": return [...e.args]; + case "cast": return [e.arg]; + case "case": return [...(e.operand !== undefined ? [e.operand] : []), ...e.whens.flatMap((w) => [w.when, w.then]), ...(e.else !== undefined ? [e.else] : [])]; + default: return []; + } } // --------------------------------------------------------------------------- @@ -1896,6 +2096,8 @@ export function extractViewSpec( projection: MetaObject, root: MetaRoot, ctx: ExtractContext, + /** rc.21 part B (U15): `member` — a union member's body, which needs no view of its own. */ + options: { readonly member?: boolean } = {}, ): ViewSpec { // #213 — a write-through entity (FR-024 §7) IS its own base: stored fields SELECT // from the base alias (o.*), derived (origin.*) fields from the joins. A plain @@ -1915,14 +2117,29 @@ export function extractViewSpec( const path = resolveFilterPath(base, key); if (path !== undefined && typeof path !== "string") filterPaths.set(key, path); } - const filterJoinPaths = [...filterPaths.values()] + // rc.21 part B (U3, U4): an expression's path refs and an origin filter's path operands join too. + const refPaths = new Map(); + if (!writeThrough) { + for (const key of originPathKeys(projection)) { + if (ownFieldNames.has(key) || refPaths.has(key)) continue; + const path = resolveFilterPath(base, key); + if (path !== undefined && typeof path !== "string") refPaths.set(key, path); + } + } + const filterJoinPaths = [...filterPaths.values(), ...refPaths.values()] .map((p) => walkViaPath(`${base.resolutionKey()}.${p.hops.join(".")}`, root, packageOf(projection), ctx)) .filter((p) => p.length > 0); const joinTree = buildJoinTree(projection, base, root, usedAliases, baseAlias, ctx, filterJoinPaths); - const selectSpec = buildSelectSpec(projection, base, joinTree, root, ctx, usedAliases); - const groupBy = buildGroupBy(selectSpec); + const pathRefs = new Map(); + for (const [key, path] of refPaths) { + const alias = aliasForHops(joinTree, path.hops); + if (alias === undefined) throw new Error(`Projection ${projection.name}: the path "${key}" did not join.`); + pathRefs.set(key, { alias, field: path.field as MetaField, entity: path.entity }); + } + const selectSpec = buildSelectSpec(projection, base, joinTree, root, ctx, usedAliases, pathRefs); + const groupBy = buildGroupBy(selectSpec, joinTree.baseAlias); - const view = viewName(projection, ctx); + const view = options.member === true ? projection.name : viewName(projection, ctx); warnOnJoinInflation(projection, view, joinTree, selectSpec); // #207 — a projection's OWN row-scope @filter lowers to the view's outer WHERE. @@ -1971,12 +2188,34 @@ export function extractViewSpec( const baseScope = writeThrough ? undefined : tphScopeOf(base, ctx); if (baseScope !== undefined) where = andClauses(where, tphScopeClause(baseScope, joinTree.baseAlias)); + // rc.21 part B (U14): one row per element of the base's jsonb array field. + const grainName = writeThrough ? undefined : projection.attr(OBJECT_PROJECTION_ATTR_GRAIN); + const grainField = typeof grainName === "string" ? base.fields().find((f) => f.name === grainName) : undefined; + if (typeof grainName === "string" && grainField === undefined) { + throw new Error(`Projection ${projection.name}: @grain "${grainName}" is not a field of "${base.name}".`); + } + // rc.21 part B (U15): the member bodies, each its own SELECT. ADR-0039: own — a union is ITS view. + const unionNames = writeThrough || options.member === true ? undefined : projection.ownAttr(OBJECT_PROJECTION_ATTR_UNION); + const members = unionNames === undefined ? [] : (Array.isArray(unionNames) ? unionNames : [unionNames]).map((name) => { + const member = resolveEntityRef(root, String(name), packageOf(projection)); + if (member === undefined) throw new Error(`Projection ${projection.name}: @union member "${String(name)}" does not resolve.`); + const spec = extractViewSpec(member, root, ctx, { member: true }); + const mine = selectSpec.columns.map((c) => c.dbColAlias).join(", "); + const theirs = spec.selectSpec.columns.map((c) => c.dbColAlias).join(", "); + if (mine !== theirs) { + throw new Error(`Projection ${projection.name}: @union member "${member.name}" has columns (${theirs}), not (${mine}).`); + } + return spec; + }); + return { viewName: view, joinTree, selectSpec, groupBy, ...(where !== undefined ? { where } : {}), + ...(grainField !== undefined ? { grain: { column: sourceColumnNameFor(grainField, ctx), alias: "mo_el" } } : {}), + ...(members.length > 0 ? { union: { all: projection.ownAttr(OBJECT_PROJECTION_ATTR_UNION_ALL) === true, members } } : {}), }; } diff --git a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts index fb850bc4c7..d05e951a2a 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-ddl-emit.ts @@ -1,7 +1,7 @@ import { DEFAULT_DB_SCHEMA_POSTGRES } from "@metaobjectsdev/metadata"; import { pgType, type SqlType } from "@metaobjectsdev/migrate-ts/expected"; import type { - JoinNode, ViewSpec, ViewFilterClause, ViewExprNode, ViewOrderKey, SelectColumn, ColRef, + JoinNode, ViewSpec, ViewFilterClause, ViewExprNode, ViewOrderKey, SelectColumn, ColRef, CastTarget, AggregateColumn, GrainColumn, } from "./view-spec.js"; import { isRelativeNow } from "./report-spec.js"; import { relativeNowSql } from "./time-sql.js"; @@ -153,7 +153,95 @@ function renderExpr(node: ViewExprNode, options: EmitOptions): string { const otherwise = node.else !== undefined ? ` ELSE ${renderExpr(node.else, options)}` : ""; return `(${head}${arms}${otherwise} END)`; } + case "fn": + return renderFn(node.name, node.args.map((a) => renderExpr(a, options)), node.args, dialect); + case "cast": + return `CAST(${renderExpr(node.arg, options)} AS ${castTypeSql(node.to, dialect)})`; + case "agg": + return aggregateSql(node.column, options); + case "call": { + if (dialect !== "postgres") { + throw new Error(`view-ddl-emit: origin.function "${node.name}" calls a database function, which SQLite does not have.`); + } + const fn = `${quoteIfNeeded(node.schema ?? DEFAULT_DB_SCHEMA_POSTGRES)}.${quoteIfNeeded(node.name)}`; + return `${fn}(${node.args.map((a) => renderExpr(a, options)).join(", ")})`; + } + } +} + +/** + * rc.21 part B (U11, U13): one function of the closed set, in the dialect's spelling. Where SQLite + * has no function of the same meaning it is spelled from ones it has; where it cannot be, the + * emitter refuses rather than write SQL that means something else. + */ +function renderFn(name: string, args: readonly string[], nodes: readonly ViewExprNode[], dialect: EmitOptions["dialect"]): string { + const pg = dialect === "postgres"; + const list = args.join(", "); + switch (name) { + case "lower": return `LOWER(${list})`; + case "upper": return `UPPER(${list})`; + case "btrim": return pg ? `BTRIM(${list})` : `TRIM(${list})`; + case "replace": return `REPLACE(${list})`; + case "nullif": return `NULLIF(${list})`; + case "length": return pg ? `CHAR_LENGTH(${list})` : `LENGTH(${list})`; + case "substring": return `SUBSTR(${list})`; + case "left": return pg ? `LEFT(${list})` : `SUBSTR(${args[0]}, 1, ${args[1]})`; + case "right": return pg ? `RIGHT(${list})` : `(CASE WHEN ${args[1]} > 0 THEN SUBSTR(${args[0]}, -(${args[1]})) ELSE '' END)`; + case "concat": + return pg ? `CONCAT(${list})` : `(${args.map((a) => `COALESCE(CAST(${a} AS TEXT), '')`).join(" || ")})`; + case "concatWs": { + if (pg) return `CONCAT_WS(${list})`; + // Each non-null value is prefixed with the separator, and the first separator dropped. + const [sep, ...rest] = args; + const joined = rest.map((a) => `COALESCE(${sep} || CAST(${a} AS TEXT), '')`).join(" || "); + return `(CASE WHEN ${sep} IS NULL THEN NULL ELSE SUBSTR(${joined}, LENGTH(${sep}) + 1) END)`; + } + case "splitPart": { + if (pg) return `SPLIT_PART(${list})`; + // SQLite has no split_part. The first part is spelled with instr/substr; any other is refused. + const n = nodes[2]; + if (n?.kind !== "lit" || n.value !== 1) { + throw new Error("view-ddl-emit: splitPart on SQLite is lowered only for the first part (a literal 1); SQLite has no split_part."); + } + const [str, delim] = args; + return `(CASE WHEN INSTR(${str}, ${delim}) = 0 THEN ${str} ELSE SUBSTR(${str}, 1, INSTR(${str}, ${delim}) - 1) END)`; + } + case "greatest": + case "least": { + if (pg) return `${name.toUpperCase()}(${list})`; + if (args.length === 1) return args[0]!; + // SQLite's scalar max/min return NULL if any argument is; Postgres's skip NULLs. Each slot + // falls back to the others, so the result is the max (min) of the non-null values, NULL + // only when every one is. + const slots = args.map((a, i) => `COALESCE(${[a, ...args.filter((_, j) => j !== i)].join(", ")})`); + return `${name === "greatest" ? "MAX" : "MIN"}(${slots.join(", ")})`; + } } + throw new Error(`view-ddl-emit: unknown expression function "${name}".`); +} + +/** rc.21 part B (U12): the column type a cast names, in the dialect's spelling. */ +function castTypeSql(to: CastTarget, dialect: EmitOptions["dialect"]): string { + const pg = dialect === "postgres"; + switch (to.subType) { + case "string": { + if (!pg) return "TEXT"; + const sp = to.spelling; + if (sp?.kind === "char") return `CHARACTER(${sp.length ?? 1})`; + if (sp?.kind === "varchar") return sp.length !== undefined ? `VARCHAR(${sp.length})` : "VARCHAR"; + return "TEXT"; + } + case "int": return pg ? "INTEGER" : "INTEGER"; + case "long": return pg ? "BIGINT" : "INTEGER"; + case "double": return pg ? "DOUBLE PRECISION" : "REAL"; + case "float": return pg ? "REAL" : "REAL"; + case "decimal": return "NUMERIC"; + case "boolean": return pg ? "BOOLEAN" : "INTEGER"; + case "date": return pg ? "DATE" : "TEXT"; + case "timestamp": return pg ? "TIMESTAMPTZ" : "TEXT"; + case "uuid": return pg ? "UUID" : "TEXT"; + } + throw new Error(`view-ddl-emit: a cast to "${to.subType}" has no column type.`); } /** @@ -319,39 +407,12 @@ function renderColumn(c: SelectColumn, options: EmitOptions, baseAlias: string): return `${cast(`${c.sourceAlias}.${quoteIfNeeded(c.sourceColumn)}`, c.castTo, dialect)} AS ${alias}`; } - if (c.kind === "aggregate") { - const src = `${c.sourceAlias}.${quoteIfNeeded(c.sourceColumn)}`; - // aggregate — use DISTINCT for count() over joined PKs to avoid join inflation. - // A scoping @filter renders as postgres `FILTER (WHERE …)`; sqlite (no aggregate - // FILTER pre-3.30) uses the portable `CASE WHEN … END` argument form. - const cond = c.filter ? renderFilterCond(c.filter, options) : undefined; - if (c.agg === "count") { - if (cond && dialect === "sqlite") return `COUNT(DISTINCT CASE WHEN ${cond} THEN ${src} END) AS ${alias}`; - if (cond) return `COUNT(DISTINCT ${src}) FILTER (WHERE ${cond}) AS ${alias}`; - return `COUNT(DISTINCT ${src}) AS ${alias}`; - } - const fn = c.agg.toUpperCase(); - if (cond && dialect === "sqlite") return `${fn}(CASE WHEN ${cond} THEN ${src} END) AS ${alias}`; - if (cond) return `${fn}(${src}) FILTER (WHERE ${cond}) AS ${alias}`; - return `${fn}(${src}) AS ${alias}`; + if (c.kind === "aggregate" || c.kind === "predicateAgg") { + return `${aggregateSql(c, options)} AS ${alias}`; } - if (c.kind === "predicateAgg") { - // #195 any/all. The phantom-row guard (joined.pk IS NOT NULL) EXCLUDES null-extended - // LEFT-JOIN non-matches, so the empty-related-set pins hold: any=false / all=true. - const pred = renderFilterCond(c.pred, options); - const guard = `${c.sourceAlias}.${quoteIfNeeded(c.joinedPkColumn)} IS NOT NULL`; - if (dialect === "sqlite") { - // No boolean aggregates: MAX≡bool_or, MIN≡bool_and over 1/0. The outer CASE yields - // NULL (not 0) for phantom rows so MIN/MAX ignore them — the COALESCE default then - // supplies the empty-set pin (0 for any, 1 for all). - const fn = c.quant === "any" ? "MAX" : "MIN"; - const empty = c.quant === "any" ? "0" : "1"; - return `COALESCE(${fn}(CASE WHEN ${guard} THEN (CASE WHEN ${pred} THEN 1 ELSE 0 END) END), ${empty}) AS ${alias}`; - } - const fn = c.quant === "any" ? "bool_or" : "bool_and"; - const empty = c.quant === "any" ? "FALSE" : "TRUE"; - return `COALESCE(${fn}(${pred}) FILTER (WHERE ${guard}), ${empty}) AS ${alias}`; + if (c.kind === "element") { + return `${grainElementSql(c, options)} AS ${alias}`; } if (c.kind === "collectAgg") { @@ -408,6 +469,60 @@ function renderColumn(c: SelectColumn, options: EmitOptions, baseAlias: string): return renderFirst(c, options, baseAlias); } +/** A scalar aggregate or an any/all column's expression (no alias): a column, or (U13) read by a computed. */ +function aggregateSql(c: AggregateColumn, options: EmitOptions): string { + const dialect = options.dialect; + if (c.kind === "aggregate") { + const src = `${c.sourceAlias}.${quoteIfNeeded(c.sourceColumn)}`; + // aggregate — use DISTINCT for count() over joined PKs to avoid join inflation. + // A scoping @filter renders as postgres `FILTER (WHERE …)`; sqlite (no aggregate + // FILTER pre-3.30) uses the portable `CASE WHEN … END` argument form. + const cond = c.filter ? renderFilterCond(c.filter, options) : undefined; + if (c.agg === "count") { + if (cond && dialect === "sqlite") return `COUNT(DISTINCT CASE WHEN ${cond} THEN ${src} END)`; + if (cond) return `COUNT(DISTINCT ${src}) FILTER (WHERE ${cond})`; + return `COUNT(DISTINCT ${src})`; + } + const fn = c.agg.toUpperCase(); + if (cond && dialect === "sqlite") return `${fn}(CASE WHEN ${cond} THEN ${src} END)`; + if (cond) return `${fn}(${src}) FILTER (WHERE ${cond})`; + return `${fn}(${src})`; + } + // #195 any/all. The phantom-row guard (joined.pk IS NOT NULL) EXCLUDES null-extended + // LEFT-JOIN non-matches, so the empty-related-set pins hold: any=false / all=true. + const pred = renderFilterCond(c.pred, options); + const guard = `${c.sourceAlias}.${quoteIfNeeded(c.joinedPkColumn)} IS NOT NULL`; + if (dialect === "sqlite") { + // No boolean aggregates: MAX≡bool_or, MIN≡bool_and over 1/0. The outer CASE yields + // NULL (not 0) for phantom rows so MIN/MAX ignore them — the COALESCE default then + // supplies the empty-set pin (0 for any, 1 for all). + const fn = c.quant === "any" ? "MAX" : "MIN"; + const empty = c.quant === "any" ? "0" : "1"; + return `COALESCE(${fn}(CASE WHEN ${guard} THEN (CASE WHEN ${pred} THEN 1 ELSE 0 END) END), ${empty})`; + } + const fn = c.quant === "any" ? "bool_or" : "bool_and"; + const empty = c.quant === "any" ? "FALSE" : "TRUE"; + return `COALESCE(${fn}(${pred}) FILTER (WHERE ${guard}), ${empty})`; +} + +/** The alias of a `@grain` view's element relation (its `value` and position). */ +const GRAIN_ALIAS = "mo_el"; + +/** rc.21 part B (U14): a grain element member, or the element's 1-based position. */ +function grainElementSql(c: GrainColumn, options: EmitOptions): string { + const pg = options.dialect === "postgres"; + if (c.member === undefined) { + // WITH ORDINALITY is a bigint; a field.int position is cast to it. + if (!pg) return `(${GRAIN_ALIAS}.key + 1)`; + return c.castTo.kind === "integer" && c.castTo.bits === 64 ? `${GRAIN_ALIAS}.ordinality` : `CAST(${GRAIN_ALIAS}.ordinality AS ${pgType(c.castTo)})`; + } + const key = c.member.replace(/'/g, "''"); + if (!pg) return `json_extract(${GRAIN_ALIAS}.value, '$.${key.replace(/"/g, '""')}')`; + const text = `(${GRAIN_ALIAS}.value ->> '${key}')`; + return c.castTo.kind === "text" && c.castTo.maxLength === undefined && c.castTo.variant === undefined + ? text : `CAST(${text} AS ${pgType(c.castTo)})`; +} + /** A TPH scope's comparison after its column: ` = v` for one value, ` IN (a, b)` for several. */ export function tphScopeSql(values: readonly (string | number)[], literal: (v: string | number) => string): string { return values.length === 1 ? ` = ${literal(values[0]!)}` : ` IN (${values.map(literal).join(", ")})`; @@ -450,10 +565,30 @@ function renderJoin( } export function emitViewDdl(spec: ViewSpec, options: EmitOptions): string { + // rc.21 part B (U15): the member bodies follow this one, UNIONed. Each reads its own base. + const members = (spec.union?.members ?? []).map((m) => { + const table = options.joinTables[m.joinTree.baseEntity]; + if (table === undefined) throw new Error(`view-ddl-emit: no table name registered for union member base "${m.joinTree.baseEntity}".`); + return emitViewBody(m, { ...options, baseTableName: table }); + }); + const joiner = spec.union?.all === true ? "\n UNION ALL\n" : "\n UNION\n"; + const body = [emitViewBody(spec, options), ...members].join(joiner); + if (options.bodyOnly) return body; + return `CREATE VIEW ${quoteIfNeeded(spec.viewName)} AS +${body};`; +} + +/** One SELECT of a view: its columns, base, grain, joins, WHERE and GROUP BY. */ +function emitViewBody(spec: ViewSpec, options: EmitOptions): string { const cols = spec.selectSpec.columns .map((c) => " " + renderColumn(c, options, spec.joinTree.baseAlias)) .join(",\n"); - const fromClause = ` FROM ${viewRelation(spec.joinTree.baseEntity, options.baseTableName, options)} ${spec.joinTree.baseAlias}`; + // rc.21 part B (U14): a @grain view reads one row per element of the base row's jsonb array. + const grain = spec.grain === undefined ? "" + : options.dialect === "postgres" + ? ` CROSS JOIN LATERAL jsonb_array_elements(${spec.joinTree.baseAlias}.${quoteIfNeeded(spec.grain.column)}) WITH ORDINALITY AS ${GRAIN_ALIAS}(value, ordinality)` + : ` CROSS JOIN json_each(${spec.joinTree.baseAlias}.${quoteIfNeeded(spec.grain.column)}) ${GRAIN_ALIAS}`; + const fromClause = ` FROM ${viewRelation(spec.joinTree.baseEntity, options.baseTableName, options)} ${spec.joinTree.baseAlias}${grain}`; const joinsClause = spec.joinTree.joins .map((j) => renderJoin(j, spec.joinTree.baseAlias, options)) .join("\n"); @@ -485,8 +620,5 @@ ${spec.selectSpec.columns FROM ( ${grouped} ) ${GROUPED_ALIAS}`; - - if (options.bodyOnly) return body; - return `CREATE VIEW ${quoteIfNeeded(spec.viewName)} AS -${body};`; + return body; } diff --git a/server/typescript/packages/codegen-ts/src/projection/view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/view-spec.ts index 8141647694..098a9b4ef8 100644 --- a/server/typescript/packages/codegen-ts/src/projection/view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/view-spec.ts @@ -91,7 +91,25 @@ export type ViewExprNode = readonly operand?: ViewExprNode; readonly whens: readonly { readonly when: ViewExprNode; readonly then: ViewExprNode }[]; readonly else?: ViewExprNode; - }; + } + // rc.21 part B (U11, U13): one of the closed function set beside coalesce (lower, upper, btrim, + // splitPart, concat, concatWs, substring, replace, left, right, length, nullif, greatest, least). + | { readonly kind: "fn"; readonly name: string; readonly args: readonly ViewExprNode[] } + // rc.21 part B (U12): a cast to a field subtype's column type (`spelling`: a text @dbColumnType). + | { readonly kind: "cast"; readonly arg: ViewExprNode; readonly to: CastTarget } + // rc.21 part B (U13): a scalar origin.aggregate of the projection, read on the grouped row. + | { readonly kind: "agg"; readonly column: AggregateColumn } + // rc.21 part B (U10): a call of a database function the project owns (origin.function). + | { readonly kind: "call"; readonly schema?: string; readonly name: string; readonly args: readonly ViewExprNode[] }; + +/** A cast's target: a field subtype, and (for a string) a text @dbColumnType spelling. */ +export interface CastTarget { + readonly subType: string; + readonly spelling?: { readonly kind: "text" | "varchar" | "char"; readonly length?: number }; +} + +/** An aggregate column a computed expression may read (U13): a scalar reduce or an any/all. */ +export type AggregateColumn = Extract; /** rc.19 correlated-filter: a filter operand that is a column of the base row (`alias.column`). */ export interface ColRef { @@ -107,6 +125,7 @@ export interface ViewOrderKey { /** One column of the SELECT list. */ export type SelectColumn = + | GrainColumn | { readonly kind: "passthrough"; readonly fieldName: string; // projection field name @@ -219,6 +238,19 @@ export type SelectColumn = readonly outerAlias?: string; }; +/** + * rc.21 part B (U14): a member of the array element a `@grain` projection's row is, read from the + * element (`->>` on Postgres, `json_extract` on SQLite) and cast to the member's column type; or, + * with `member` undefined, the element's 1-based position (`@grainOrdinal`). + */ +export interface GrainColumn { + readonly kind: "element"; + readonly fieldName: string; + readonly dbColAlias: string; + readonly member?: string; + readonly castTo: SqlType; +} + /** An `origin.first` column. */ export type FirstColumn = Extract; @@ -250,4 +282,15 @@ export interface ViewSpec { * `@filter`, which scopes the rows a single aggregate spans. Undefined = no filter. */ readonly where?: ViewFilterClause; + /** + * rc.21 part B (U14): one row per element of the base row's jsonb array column `column` + * (`CROSS JOIN LATERAL jsonb_array_elements(...) WITH ORDINALITY` / `json_each`), its element + * and position under `alias`. A row with no element is not returned. + */ + readonly grain?: { readonly column: string; readonly alias: string }; + /** + * rc.21 part B (U15): the bodies UNIONed after this one, each the same shape; `all` keeps + * duplicate rows (UNION ALL), else they are removed (UNION). + */ + readonly union?: { readonly all: boolean; readonly members: readonly ViewSpec[] }; } diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts new file mode 100644 index 0000000000..6c598a9148 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts @@ -0,0 +1,68 @@ +// rc.21 part B: the shared model of the view-vocabulary tests (golden SQL and live Postgres). +export const RC21B_ENTITIES: unknown[] = [ + { "object.entity": { name: "Region", children: [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + ] } }, + { "object.value": { name: "Contact", children: [ + { "field.string": { name: "kind" } }, + { "field.string": { name: "value" } }, + { "field.boolean": { name: "preferred" } }, + { "field.int": { name: "rank" } }, + ] } }, + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "firstName" } }, + { "field.string": { name: "lastName" } }, + { "field.string": { name: "zip" } }, + { "field.long": { name: "regionId" } }, + { "field.long": { name: "mailingAddressId" } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, + { "field.string": { name: "loyaltyTier", children: [ + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"] } } ] } }, + ] } }, + { "object.entity": { name: "Address", children: [ + { "source.rdb": { "@table": "addresses" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.string": { name: "street" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } }, + ] } }, + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, + { "field.int": { name: "cumulativeStatus" } }, + { "field.string": { name: "externalRef" } }, + { "field.timestamp": { name: "updatedAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } }, + ] } }, + { "object.entity": { name: "OrderEvent", children: [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "orderId", "@required": true } }, + { "field.long": { name: "customerId" } }, + { "field.int": { name: "cumulativeStatus" } }, + { "field.timestamp": { name: "createdAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } }, + ] } }, +]; + +/** The same model without the origin.function field (SQLite has no stored functions). */ +export function withoutFunction(entities: unknown[]): unknown[] { + const clone = JSON.parse(JSON.stringify(entities)) as Record[] }>[]; + for (const e of clone) { + const ent = e["object.entity"]; + if (ent?.children) ent.children = ent.children.filter((c) => c["field.string"]?.name !== "loyaltyTier"); + } + return clone; +} diff --git a/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts index 1a2d28fe82..5a5e89b377 100644 --- a/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/tier2-vocabulary.test.ts @@ -80,12 +80,18 @@ describe("computed-over-joined — an expression reads other projection fields", expect(sql).toContain("NOT (s.name IS NOT NULL) AS unnamed"); }); - test("an aggregate is not readable from an expression", async () => { - const errors = await errorsOf(view("Agg", [ + // rc.21 part B (U13): a scalar aggregate is readable (on the grouped row); a collect is not. + test("a scalar aggregate is readable from an expression; a collect is not", async () => { + const sql = await sqlOf(view("Agg", [ { "field.long": { name: "entries", children: [{ "origin.aggregate": { "@agg": "count", "@of": "CaseHistory.id", "@via": "Case.caseHistory" } }] } }, { "field.boolean": { name: "busy", children: [{ "origin.computed": { "@expr": { op: "gt", left: { field: "entries" }, right: { value: 3 } } } }] } }, ])); - expect(errors.some((e) => e.includes("entries"))).toBe(true); + expect(sql).toContain("COUNT(DISTINCT c0.id) > 3 AS busy"); + const errors = await errorsOf(view("Collect", [ + { "field.long": { name: "ids", isArray: true, children: [{ "origin.aggregate": { "@agg": "collect", "@of": "CaseHistory.id", "@via": "Case.caseHistory" } }] } }, + { "field.boolean": { name: "busy", children: [{ "origin.computed": { "@expr": { op: "isNull", arg: { field: "ids" } } } }] } }, + ])); + expect(errors.some((e) => e.includes("ids"))).toBe(true); }); }); diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts new file mode 100644 index 0000000000..9bcd22f9a4 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -0,0 +1,196 @@ +// rc.21 part B — the view vocabulary on a real Postgres: a cast (with a text @dbColumnType +// spelling), the closed function set, a path ref, a correlated path operand, an expression over an +// aggregate, an origin.function, a @grain view, and a @union. Each view is created by the +// production pipeline (build → diff → emit → apply), queried, and a second migrate is a no-op. + +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { buildExpectedSchema, diff, emit, introspectPostgres, postgresViewReplaceProbe, splitSqlStatements } from "@metaobjectsdev/migrate-ts"; +import { buildProjectionViews } from "@metaobjectsdev/codegen-ts"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { Kysely, PostgresDialect, sql } from "kysely"; +import { Pool } from "pg"; +import { startPostgres, type RunningPg } from "../src/postgres-container.ts"; + +const MODEL = { "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "Region", children: [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "code", "@dbColumnType": "character(3)" } }, + { "field.string": { name: "label", "@dbColumnType": "varchar" } }, + { "field.string": { name: "note", "@dbColumnType": "varchar(20)" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.value": { name: "Contact", children: [ + { "field.string": { name: "kind" } }, + { "field.boolean": { name: "preferred" } }, + { "field.int": { name: "rank" } } ] } }, + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "firstName" } }, + { "field.string": { name: "lastName" } }, + { "field.string": { name: "zip" } }, + { "field.long": { name: "regionId" } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, + { "field.string": { name: "loyaltyTier", children: [ + { "origin.function": { "@function": "loyalty_tier", "@schema": "app", "@args": ["id", "zip"] } } ] } } ] } }, + { "object.entity": { name: "Address", children: [ + { "source.rdb": { "@table": "addresses" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.string": { name: "street" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, + { "field.int": { name: "cumulativeStatus" } }, + { "field.string": { name: "externalRef" } }, + { "field.timestamp": { name: "updatedAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { name: "OrderEvent", children: [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "orderId", "@required": true } }, + { "field.long": { name: "customerId" } }, + { "field.int": { name: "cumulativeStatus" } }, + { "field.timestamp": { name: "createdAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, + { "object.projection": { name: "OrderRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_order_row" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + { "field.string": { name: "ref", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "externalRef" }, { cast: { field: "id" }, as: "string" } ] } } } ] } }, + { "field.string": { name: "nothing", children: [ { "origin.computed": { "@expr": { cast: { value: null }, as: "string", dbColumnType: "varchar" } } } ] } }, + { "field.int": { name: "outcome", children: [ { "origin.computed": { "@expr": { case: [ { when: { op: "eq", left: { field: "cumulativeStatus" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } } ], else: { field: "cumulativeStatus" } } } } ] } }, + { "field.string": { name: "zip5", children: [ { "origin.computed": { "@expr": { fn: "splitPart", args: [ { field: "customerId.zip" }, { value: "-" }, { value: 1 } ] } } } ] } }, + { "field.string": { name: "fullName", children: [ { "origin.computed": { "@expr": { fn: "btrim", args: [ { fn: "concatWs", args: [ { value: " " }, { field: "customerId.firstName" }, { field: "customerId.lastName" } ] } ] } } } ] } }, + { "field.string": { name: "initials", children: [ { "origin.computed": { "@expr": { fn: "upper", args: [ { fn: "concat", args: [ { fn: "left", args: [ { field: "customerId.firstName" }, { value: 1 } ] }, { fn: "right", args: [ { fn: "lower", args: [ { field: "customerId.lastName" } ] }, { value: 1 } ] } ] } ] } } } ] } }, + { "field.int": { name: "refLength", children: [ { "origin.computed": { "@expr": { fn: "length", args: [ { fn: "replace", args: [ { fn: "substring", args: [ { field: "externalRef" }, { value: 2 }, { value: 3 } ] }, { value: "X" }, { value: "" } ] } ] } } } ] } }, + { "field.string": { name: "noRef", children: [ { "origin.computed": { "@expr": { fn: "nullif", args: [ { field: "externalRef" }, { value: "NONE" } ] } } } ] } }, + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }, + { "field.timestamp": { name: "lastEvent", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + { "field.timestamp": { name: "firstAtStatus", children: [ { "origin.aggregate": { "@agg": "min", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents", "@filter": { cumulativeStatus: { eq: { field: "cumulativeStatus" } } } } } ] } }, + { "field.timestamp": { name: "touched", children: [ { "origin.computed": { "@expr": { fn: "greatest", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, + { "field.timestamp": { name: "earliest", children: [ { "origin.computed": { "@expr": { fn: "least", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, + { "field.long": { name: "eventByCustomer", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, + { "identity.primary": { name: "id", extends: "Order.id" } } ] } }, + { "object.projection": { name: "CustomerContact", "@grain": "contacts", "@grainOrdinal": "position", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_customer_contact" } }, + { "field.long": { name: "customerId", extends: "Customer.id" } }, + { "field.int": { name: "position" } }, + { "field.string": { name: "kind", children: [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } }, + { "field.boolean": { name: "preferred", children: [ { "origin.passthrough": { "@from": "Contact.preferred" } } ] } }, + { "field.int": { name: "rank", children: [ { "origin.passthrough": { "@from": "Contact.rank" } } ] } } ] } }, + { "object.projection": { name: "PersonBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Customer.id" } }, + { "field.string": { name: "label", children: [ { "origin.computed": { "@expr": { fn: "lower", args: [ { field: "lastName" } ] } } } ] } } ] } }, + { "object.projection": { name: "AddressBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Address.customerId" } }, + { "field.string": { name: "label", children: [ { "origin.computed": { "@expr": { fn: "lower", args: [ { field: "street" } ] } } } ] } } ] } }, + { "object.projection": { name: "People", extends: "PersonBranch", "@union": ["AddressBranch"], children: [ + { "source.rdb": { "@kind": "view", "@table": "v_people" } } ] } }, + { "object.projection": { name: "PeopleAll", extends: "PersonBranch", "@union": ["AddressBranch"], "@unionAll": true, children: [ + { "source.rdb": { "@kind": "view", "@table": "v_people_all" } } ] } }, +] } }; + +let pg: RunningPg; +let k: Kysely>; + +beforeAll(async () => { + pg = await startPostgres(); + k = new Kysely>({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: pg.connectionUri }) }) }); +}, 120_000); + +afterAll(async () => { + await k.destroy(); + await pg.stop(); +}, 60_000); + +async function migrate() { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(MODEL))]); + expect(errors).toEqual([]); + const expected = buildExpectedSchema(root, { views: buildProjectionViews(root, { dialect: "postgres" }) }); + const run = async () => diff({ expected, actual: await introspectPostgres(k), dialect: "postgres", viewReplaceProbe: postgresViewReplaceProbe(k) }); + const first = await run(); + expect(first.blocked).toEqual([]); + const { up } = emit(first.changes, { dialect: "postgres" }); + for (const stmt of splitSqlStatements(up)) await sql.raw(stmt.endsWith(";") ? stmt : `${stmt};`).execute(k); + return run; +} + +const rows = async (q: string) => (await sql.raw(q).execute(k)).rows as Record[]; + +describe("rc.21 part B view vocabulary — live Postgres", () => { + test("every construct creates, reads the expected rows, and a second migrate is a no-op", async () => { + await sql.raw("DROP SCHEMA IF EXISTS app CASCADE").execute(k); + await sql.raw("CREATE SCHEMA app").execute(k); + // The function the project owns: owned SQL, created before the view that calls it. + await sql.raw(`CREATE FUNCTION app.loyalty_tier(bigint, text) RETURNS text LANGUAGE sql IMMUTABLE + AS $$ SELECT CASE WHEN $1 % 2 = 0 THEN 'gold' ELSE 'silver' END || ':' || left($2, 2) $$`).execute(k); + const again = await migrate(); + + // U2: the text spellings are the column types. + const types = await rows(`SELECT column_name, data_type, character_maximum_length FROM information_schema.columns + WHERE table_name = 'regions' AND column_name IN ('code', 'label', 'note') ORDER BY column_name`); + expect(types).toEqual([ + { column_name: "code", data_type: "character", character_maximum_length: 3 }, + { column_name: "label", data_type: "character varying", character_maximum_length: null }, + { column_name: "note", data_type: "character varying", character_maximum_length: 20 }, + ]); + const nothingType = await rows(`SELECT data_type FROM information_schema.columns WHERE table_name = 'v_order_row' AND column_name = 'nothing'`); + expect(nothingType).toEqual([{ data_type: "character varying" }]); + + await sql.raw(` + INSERT INTO regions (id, code, label, note) VALUES (1, 'NE', 'north east', 'n'); + INSERT INTO customers (id, first_name, last_name, zip, region_id, contacts) VALUES + (10, 'Ada', 'Lovelace', '02139-4307', 1, '[{"kind":"email","preferred":true,"rank":1},{"kind":"phone","preferred":false,"rank":2}]'), + (11, ' Alan', 'Turing ', '12345', 1, '[]'), + (12, NULL, 'Hopper', NULL, NULL, NULL); + INSERT INTO addresses (id, customer_id, street) VALUES (100, 10, 'Lovelace'), (101, 11, 'Main St'); + INSERT INTO orders (id, customer_id, status, cumulative_status, external_ref, updated_at) VALUES + (1, 10, 1, 0, NULL, '2026-01-05T00:00:00Z'), + (2, 11, 0, 7, 'AXXBCD', '2026-03-01T00:00:00Z'), + (3, 12, 0, 0, 'NONE', NULL); + INSERT INTO order_events (id, order_id, customer_id, cumulative_status, created_at) VALUES + (1000, 1, 10, 0, '2026-01-01T00:00:00Z'), + (1001, 1, 10, 0, '2026-02-01T00:00:00Z'), + (1002, 1, 99, 3, '2026-01-02T00:00:00Z'), + (1003, 2, 11, 7, '2026-02-15T00:00:00Z'); + `).execute(k); + + const order = await rows(`SELECT id, ref, nothing, outcome, zip5, full_name, initials, ref_length, no_ref, tier, + (last_event AT TIME ZONE 'UTC')::text AS last_event, (first_at_status AT TIME ZONE 'UTC')::text AS first_at_status, + (touched AT TIME ZONE 'UTC')::text AS touched, (earliest AT TIME ZONE 'UTC')::text AS earliest, event_by_customer FROM v_order_row ORDER BY id`); + expect(order).toEqual([ + { id: "1", ref: "1", nothing: null, outcome: 1, zip5: "02139", full_name: "Ada Lovelace", initials: "AE", ref_length: null, no_ref: null, + tier: "gold:02", last_event: "2026-02-01 00:00:00", first_at_status: "2026-01-01 00:00:00", + touched: "2026-02-01 00:00:00", earliest: "2026-01-05 00:00:00", event_by_customer: "1000" }, + { id: "2", ref: "AXXBCD", nothing: null, outcome: 7, zip5: "12345", full_name: "Alan Turing", initials: " ", ref_length: 1, no_ref: "AXXBCD", + tier: "silver:12", last_event: "2026-02-15 00:00:00", first_at_status: "2026-02-15 00:00:00", + touched: "2026-03-01 00:00:00", earliest: "2026-02-15 00:00:00", event_by_customer: "1003" }, + { id: "3", ref: "NONE", nothing: null, outcome: 0, zip5: null, full_name: "Hopper", initials: "R", ref_length: 3, no_ref: null, + tier: null, last_event: null, first_at_status: null, touched: null, earliest: null, event_by_customer: null }, + ]); + + // U14: one row per element; a customer with an empty or NULL array has none. + expect(await rows(`SELECT customer_id, position, kind, preferred, rank FROM v_customer_contact ORDER BY customer_id, position`)).toEqual([ + { customer_id: "10", position: 1, kind: "email", preferred: true, rank: 1 }, + { customer_id: "10", position: 2, kind: "phone", preferred: false, rank: 2 }, + ]); + + // U15: UNION removes the duplicate ('lovelace' as a customer and as a street); UNION ALL keeps it. + expect(await rows(`SELECT person_id, label FROM v_people ORDER BY person_id, label`)).toEqual([ + { person_id: "10", label: "lovelace" }, { person_id: "11", label: "main st" }, + { person_id: "11", label: "turing " }, { person_id: "12", label: "hopper" }, + ]); + expect((await rows(`SELECT count(*)::int AS n FROM v_people_all`))[0]).toEqual({ n: 5 }); + + const followup = await again(); + expect(followup.changes).toEqual([]); + }, 120_000); +}); diff --git a/server/typescript/packages/metadata/src/attr-schema-validate.ts b/server/typescript/packages/metadata/src/attr-schema-validate.ts index 28e5f3d4b2..dac1f2c8bc 100644 --- a/server/typescript/packages/metadata/src/attr-schema-validate.ts +++ b/server/typescript/packages/metadata/src/attr-schema-validate.ts @@ -58,13 +58,16 @@ import { FIELD_ATTR_INT_VALUE_MAP, FIELD_ATTR_STRING_VALUE_MAP, ENUM_MEMBER_PATTERN, + FIELD_ATTR_MAX_LENGTH, + FIELD_SUBTYPE_STRING, } from "./core/field/field-constants.js"; import { isSharedEnumDeclaration } from "./core/field/shared-enum.js"; import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_VALUES, - DB_COLUMN_TYPE_LEGAL_SUBTYPES, - type DbColumnTypeValue, + DB_COLUMN_TYPE_SIZED_SPELLINGS, + dbColumnTypeLegalSubtypes, + parseDbColumnType, } from "./persistence/db/db-constants.js"; export interface AttrSchemaValidationResult { @@ -561,21 +564,33 @@ function validateNode( // one was pairing-checked on its declaring node; own-attrs-only policy). const ownValue = node.ownAttrs().get(FIELD_ATTR_DB_COLUMN_TYPE); if (typeof ownValue === "string") { - const legalSubtypes = (DB_COLUMN_TYPE_VALUES as readonly string[]).includes(ownValue) - ? DB_COLUMN_TYPE_LEGAL_SUBTYPES[ownValue as DbColumnTypeValue] - : undefined; + const legalSubtypes = dbColumnTypeLegalSubtypes(ownValue); if (legalSubtypes === undefined || !legalSubtypes.includes(node.subType)) { errors.push( new ParseError( `${nodeLabel(node)} attribute '@${FIELD_ATTR_DB_COLUMN_TYPE}' value ` + `'${ownValue}' is not legal on field.${node.subType}. ` + `Legal @${FIELD_ATTR_DB_COLUMN_TYPE} pairings: ` + - `${DB_COLUMN_TYPE_VALUES.map( - (v) => `${v} (field.${DB_COLUMN_TYPE_LEGAL_SUBTYPES[v].join("/field.")})`, + `${[...DB_COLUMN_TYPE_VALUES, ...DB_COLUMN_TYPE_SIZED_SPELLINGS].map( + (v) => `${v} (field.${FIELD_SUBTYPE_STRING})`, ).join(", ")}.`, { code: "ERR_BAD_ATTR_VALUE", source: node.source }, ), ); + } else { + // rc.21 part B (U2): a sized spelling holds n characters, so a longer @maxLength would let + // the app accept a value the column refuses. ADR-0039: resolving — @maxLength may be inherited. + const parsed = parseDbColumnType(ownValue); + const max = node.attr(FIELD_ATTR_MAX_LENGTH); + if (parsed !== undefined && "length" in parsed && parsed.length !== undefined && typeof max === "number" && max > parsed.length) { + errors.push( + new ParseError( + `${nodeLabel(node)} declares @${FIELD_ATTR_MAX_LENGTH}: ${max} over '@${FIELD_ATTR_DB_COLUMN_TYPE}: ${ownValue}', ` + + `which holds ${parsed.length}; a value the field accepts would not fit the column.`, + { code: "ERR_BAD_ATTR_VALUE", source: node.source }, + ), + ); + } } } } diff --git a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts index 10ae77a383..ae4787dd88 100644 --- a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts @@ -73,7 +73,7 @@ export const ATTR_DEFINITION: ProviderDefinition = { "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] }; diff --git a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts index f5f3f45c55..4c02468b61 100644 --- a/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts +++ b/server/typescript/packages/metadata/src/core/attr/meta-attr-expression.ts @@ -31,6 +31,11 @@ import { DATA_TYPE_OBJECT, type DataType } from "../../data-type.js"; import { ATTR_SUBTYPE_EXPRESSION } from "./attr-constants.js"; import { registerAttrClass } from "../../attr-class-map.js"; import { FILTER_RELATIVE_NOW, FILTER_RELATIVE_START_OF } from "../reporting/reporting-constants.js"; +import { + FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_UUID, + FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP, FIELD_SUBTYPE_ENUM, FIELD_SUBTYPE_CURRENCY, +} from "../field/field-constants.js"; +import { parseDbColumnType } from "../../persistence/db/db-constants.js"; // --- Expression-only op/fn names (the comparison + and/or/isNull names are the // --- shared filter vocabulary above; these three are new). --- @@ -46,6 +51,115 @@ export const EXPR_CASE_OPERAND = "operand"; // rc.19 `now`: { now: "", startOf? } — the relative-date value, as a leaf. export const EXPR_NOW = FILTER_RELATIVE_NOW; export const EXPR_NOW_START_OF = FILTER_RELATIVE_START_OF; +// rc.21 part B (U12): { cast: , as: "", dbColumnType?: "" }. +export const EXPR_CAST = "cast"; +export const EXPR_CAST_AS = "as"; +export const EXPR_CAST_DB_COLUMN_TYPE = "dbColumnType"; +// rc.21 part B (U11, U13): the closed, typed function set beside coalesce. +export const EXPR_FN_GREATEST = "greatest"; +export const EXPR_FN_LEAST = "least"; +export const EXPR_FN_NULLIF = "nullif"; +export const EXPR_FN_LOWER = "lower"; +export const EXPR_FN_UPPER = "upper"; +export const EXPR_FN_BTRIM = "btrim"; +export const EXPR_FN_SPLIT_PART = "splitPart"; +export const EXPR_FN_CONCAT = "concat"; +export const EXPR_FN_CONCAT_WS = "concatWs"; +export const EXPR_FN_SUBSTRING = "substring"; +export const EXPR_FN_REPLACE = "replace"; +export const EXPR_FN_LEFT = "left"; +export const EXPR_FN_RIGHT = "right"; +export const EXPR_FN_LENGTH = "length"; + +/** A function parameter's kind: a string, an integer, any scalar, or the type the "same" ones share. */ +type ParamKind = "string" | "int" | "scalar" | "same"; +/** One function's signature: its arity, each parameter's kind (the last repeats), and its result. */ +interface FnSignature { + readonly min: number; + readonly max: number; // Infinity for variadic + readonly params: readonly ParamKind[]; + readonly result: "string" | "int" | "same"; + /** The "same" type must be orderable (greatest / least). */ + readonly ordered?: boolean; +} +const VARIADIC = Number.POSITIVE_INFINITY; +/** + * rc.21 part B: every expression function, by name. A closed set — never free SQL. Each lowers to + * the dialect's own function (Postgres and SQLite spellings live in the view emitter). + */ +export const EXPR_FUNCTIONS: Readonly> = { + [EXPR_FN_COALESCE]: { min: 1, max: VARIADIC, params: ["same"], result: "same" }, + [EXPR_FN_GREATEST]: { min: 1, max: VARIADIC, params: ["same"], result: "same", ordered: true }, + [EXPR_FN_LEAST]: { min: 1, max: VARIADIC, params: ["same"], result: "same", ordered: true }, + [EXPR_FN_NULLIF]: { min: 2, max: 2, params: ["same", "same"], result: "same" }, + [EXPR_FN_LOWER]: { min: 1, max: 1, params: ["string"], result: "string" }, + [EXPR_FN_UPPER]: { min: 1, max: 1, params: ["string"], result: "string" }, + [EXPR_FN_BTRIM]: { min: 1, max: 2, params: ["string", "string"], result: "string" }, + [EXPR_FN_SPLIT_PART]: { min: 3, max: 3, params: ["string", "string", "int"], result: "string" }, + [EXPR_FN_CONCAT]: { min: 1, max: VARIADIC, params: ["scalar"], result: "string" }, + [EXPR_FN_CONCAT_WS]: { min: 2, max: VARIADIC, params: ["string", "scalar"], result: "string" }, + [EXPR_FN_SUBSTRING]: { min: 2, max: 3, params: ["string", "int", "int"], result: "string" }, + [EXPR_FN_REPLACE]: { min: 3, max: 3, params: ["string", "string", "string"], result: "string" }, + [EXPR_FN_LEFT]: { min: 2, max: 2, params: ["string", "int"], result: "string" }, + [EXPR_FN_RIGHT]: { min: 2, max: 2, params: ["string", "int"], result: "string" }, + [EXPR_FN_LENGTH]: { min: 1, max: 1, params: ["string"], result: "int" }, +}; + +/** The field subtypes a cast may name in `as`. */ +export const EXPR_CAST_TARGETS: readonly string[] = [ + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, +]; +const NUMERIC_SUBTYPES: ReadonlySet = new Set([ + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, +]); +const INTEGER_SUBTYPES: ReadonlySet = new Set([FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG]); +const NON_SCALAR_SUBTYPES: ReadonlySet = new Set([FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP]); + +/** + * Why a value of `from` cannot be cast to `to`, or undefined when it can. `intStoredEnum` is + * whether the operand is an enum field stored as an integer (`@intValueMap`). The same table in + * every port: a cast never makes a value of a kind the source cannot hold. + */ +export function castProblem(from: string | undefined, to: string, intStoredEnum: boolean): string | undefined { + if (from === undefined) return undefined; // a null literal casts to anything + if (NON_SCALAR_SUBTYPES.has(from)) return `a field.${from} value cannot be cast`; + if (from === to) return undefined; + if (from === FIELD_SUBTYPE_ENUM) { + if (to === FIELD_SUBTYPE_STRING) return intStoredEnum ? "an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int" : undefined; + if (INTEGER_SUBTYPES.has(to)) return intStoredEnum ? undefined : "only an enum stored as an integer (@intValueMap) can be cast to a number"; + return `an enum cannot be cast to ${to}`; + } + if (to === FIELD_SUBTYPE_STRING) return undefined; + if (from === FIELD_SUBTYPE_STRING) return undefined; // the database parses it + if (NUMERIC_SUBTYPES.has(to)) return NUMERIC_SUBTYPES.has(from) || from === FIELD_SUBTYPE_BOOLEAN ? undefined : `a ${from} cannot be cast to ${to}`; + if (to === FIELD_SUBTYPE_BOOLEAN) return INTEGER_SUBTYPES.has(from) ? undefined : `a ${from} cannot be cast to boolean`; + if (to === FIELD_SUBTYPE_DATE || to === FIELD_SUBTYPE_TIMESTAMP) { + return from === FIELD_SUBTYPE_DATE || from === FIELD_SUBTYPE_TIMESTAMP ? undefined : `a ${from} cannot be cast to ${to}`; + } + return `a ${from} cannot be cast to ${to}`; +} + +/** The function names an expression tree calls, and whether it casts, for the CHECK-condition subset. */ +export function exprViewOnlyNode(node: unknown): string | undefined { + if (!isObj(node)) return undefined; + if (EXPR_CAST in node) return EXPR_CAST; + if (EXPR_CASE in node) return EXPR_CASE; + if (EXPR_NOW in node) return EXPR_NOW; + if ("fn" in node && node.fn !== EXPR_FN_COALESCE) return String(node.fn); + if (typeof node.field === "string" && node.field.includes(".")) return `the path "${node.field}"`; + for (const key of ["left", "right", "arg"]) { + const hit = exprViewOnlyNode(node[key]); + if (hit !== undefined) return hit; + } + if (Array.isArray(node.args)) { + for (const a of node.args) { + const hit = exprViewOnlyNode(a); + if (hit !== undefined) return hit; + } + } + return undefined; +} const COMPARISON_OPS: ReadonlySet = new Set([ FILTER_OP_EQ, FILTER_OP_NE, FILTER_OP_GT, FILTER_OP_GTE, FILTER_OP_LT, FILTER_OP_LTE, @@ -60,9 +174,10 @@ export type ExprNode = | { op: string; left: ExprNode; right: ExprNode } // comparison | { op: string; arg: ExprNode } // isNull / isNotNull / not | { op: string; args: ExprNode[] } // and / or - | { fn: string; args: ExprNode[] } // coalesce + | { fn: string; args: ExprNode[] } // coalesce and the rc.21 function set | { case: { when: ExprNode; then: ExprNode }[]; else?: ExprNode; operand?: ExprNode } // rc.19 case - | { now: string; startOf?: string }; // rc.19 now + | { now: string; startOf?: string } // rc.19 now + | { cast: ExprNode; as: string; dbColumnType?: string }; // rc.21 cast function isObj(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); @@ -100,10 +215,33 @@ export function validateExprNode(node: unknown): string[] { if (EXPR_CASE_OPERAND in node) errs.push(...validateExprNode(node[EXPR_CASE_OPERAND])); return errs; } + if (EXPR_CAST in node) { + const extra = Object.keys(node).filter((k) => k !== EXPR_CAST && k !== EXPR_CAST_AS && k !== EXPR_CAST_DB_COLUMN_TYPE); + if (extra.length > 0) return [`expression '${EXPR_CAST}' takes only '${EXPR_CAST_AS}' and '${EXPR_CAST_DB_COLUMN_TYPE}' beside it, not ${extra.join(", ")}`]; + const to = node[EXPR_CAST_AS]; + if (typeof to !== "string" || !EXPR_CAST_TARGETS.includes(to)) { + return [`'${EXPR_CAST}' requires '${EXPR_CAST_AS}': one of ${EXPR_CAST_TARGETS.join(", ")}`]; + } + if (EXPR_CAST_DB_COLUMN_TYPE in node) { + const spelling = node[EXPR_CAST_DB_COLUMN_TYPE]; + const parsed = typeof spelling === "string" ? parseDbColumnType(spelling) : undefined; + if (parsed === undefined || parsed.kind === "uuid" || parsed.kind === "jsonb" || to !== FIELD_SUBTYPE_STRING) { + return [`'${EXPR_CAST}' '${EXPR_CAST_DB_COLUMN_TYPE}' is a text spelling of @dbColumnType (text, varchar, character varying, varchar(n), character varying(n), character(n)) with '${EXPR_CAST_AS}: ${FIELD_SUBTYPE_STRING}'`]; + } + } + return validateExprNode(node[EXPR_CAST]); + } if ("fn" in node) { - if (node.fn !== EXPR_FN_COALESCE) return [`unknown expression fn '${String(node.fn)}'`]; - return Array.isArray(node.args) && node.args.length >= 1 - ? node.args.flatMap(validateExprNode) : [`'${EXPR_FN_COALESCE}' requires a non-empty args array`]; + const sig = typeof node.fn === "string" ? EXPR_FUNCTIONS[node.fn] : undefined; + if (sig === undefined || !Object.prototype.hasOwnProperty.call(EXPR_FUNCTIONS, node.fn as string)) { + return [`unknown expression fn '${String(node.fn)}'`]; + } + const name = node.fn as string; + if (!Array.isArray(node.args) || node.args.length < Math.max(sig.min, 1)) { + return [sig.min <= 1 ? `'${name}' requires a non-empty args array` : `'${name}' requires at least ${sig.min} args`]; + } + if (node.args.length > sig.max) return [`'${name}' takes at most ${sig.max} args, got ${node.args.length}`]; + return node.args.flatMap(validateExprNode); } if ("op" in node) { const op = node.op; @@ -122,7 +260,7 @@ export function validateExprNode(node: unknown): string[] { } return [`unknown expression op '${op}'`]; } - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"]; + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}"]; } /** The subtype of a scalar literal (coarse: an integer number → int, else double). */ @@ -147,7 +285,12 @@ export interface InferResult { * arg subType. Also enforces per-operand op legality against `OPS_BY_SUBTYPE` * (the same bands filters use), so e.g. `gt` on a boolean operand is rejected. */ -export function inferExprType(node: ExprNode, resolveField: (name: string) => string | undefined): InferResult { +export function inferExprType( + node: ExprNode, + resolveField: (name: string) => string | undefined, + /** rc.21 cast: whether a `{ field }` names an enum stored as an integer (`@intValueMap`). */ + isIntStoredEnum: (name: string) => boolean = () => false, +): InferResult { const structural = validateExprNode(node); if (structural.length) return { type: undefined, errors: structural }; const n = node as Record; @@ -164,11 +307,11 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st if (EXPR_CASE in n) { const errors: string[] = []; const arms = n[EXPR_CASE] as { when: ExprNode; then: ExprNode }[]; - const operand = EXPR_CASE_OPERAND in n ? inferExprType(n[EXPR_CASE_OPERAND] as ExprNode, resolveField) : undefined; + const operand = EXPR_CASE_OPERAND in n ? inferExprType(n[EXPR_CASE_OPERAND] as ExprNode, resolveField, isIntStoredEnum) : undefined; if (operand !== undefined) errors.push(...operand.errors); const results: (string | undefined)[] = []; for (const arm of arms) { - const w = inferExprType(arm.when, resolveField); + const w = inferExprType(arm.when, resolveField, isIntStoredEnum); errors.push(...w.errors); if (operand === undefined && w.type !== undefined && w.type !== FIELD_SUBTYPE_BOOLEAN) { errors.push(`a searched '${EXPR_CASE}' needs a boolean '${EXPR_CASE_WHEN}', got ${w.type}`); @@ -176,12 +319,12 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st if (operand?.type !== undefined && w.type !== undefined && w.type !== operand.type) { errors.push(`a simple '${EXPR_CASE}' compares its ${operand.type} '${EXPR_CASE_OPERAND}' with a ${w.type} '${EXPR_CASE_WHEN}'`); } - const t = inferExprType(arm.then, resolveField); + const t = inferExprType(arm.then, resolveField, isIntStoredEnum); errors.push(...t.errors); results.push(t.type); } if (EXPR_CASE_ELSE in n) { - const e = inferExprType(n[EXPR_CASE_ELSE] as ExprNode, resolveField); + const e = inferExprType(n[EXPR_CASE_ELSE] as ExprNode, resolveField, isIntStoredEnum); errors.push(...e.errors); results.push(e.type); } @@ -193,21 +336,48 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st return { type: unified, errors }; } - if ("fn" in n) { // coalesce - const argResults = (n.args as ExprNode[]).map((a) => inferExprType(a, resolveField)); + if (EXPR_CAST in n) { + const inner = n[EXPR_CAST] as ExprNode; + const operand = inferExprType(inner, resolveField, isIntStoredEnum); + const to = n[EXPR_CAST_AS] as string; + const innerObj = inner as Record; + const fieldRef = typeof innerObj.field === "string" ? innerObj.field : undefined; + const problem = castProblem(operand.type, to, fieldRef !== undefined && isIntStoredEnum(fieldRef)); + return { type: to, errors: problem === undefined ? operand.errors : [...operand.errors, `'${EXPR_CAST}': ${problem}`] }; + } + if ("fn" in n) { + const name = n.fn as string; + const sig = EXPR_FUNCTIONS[name]!; + const argResults = (n.args as ExprNode[]).map((a) => inferExprType(a, resolveField, isIntStoredEnum)); const errors = argResults.flatMap((a) => a.errors); - const argTypes = argResults.map((a) => a.type).filter((t): t is string => t !== undefined); - const unified = argTypes[0]; - if (unified !== undefined && argTypes.some((t) => t !== unified)) { - errors.push(`'${EXPR_FN_COALESCE}' arguments have differing types (${[...new Set(argTypes)].join(", ")})`); + const same: string[] = []; + argResults.forEach((a, i) => { + const kind = sig.params[Math.min(i, sig.params.length - 1)]!; + if (a.type === undefined) return; // a null literal fits any parameter + if (kind === "same") same.push(a.type); + else if (kind === "string" && a.type !== FIELD_SUBTYPE_STRING) { + errors.push(`'${name}' argument ${i + 1} must be a string, got ${a.type}`); + } else if (kind === "int" && !INTEGER_SUBTYPES.has(a.type)) { + errors.push(`'${name}' argument ${i + 1} must be an integer, got ${a.type}`); + } else if (kind === "scalar" && NON_SCALAR_SUBTYPES.has(a.type)) { + errors.push(`'${name}' argument ${i + 1} must be a scalar, got ${a.type}`); + } + }); + const unified = same[0]; + if (unified !== undefined && same.some((t) => t !== unified)) { + errors.push(`'${name}' arguments have differing types (${[...new Set(same)].join(", ")})`); } - return { type: unified, errors }; + if (sig.ordered && unified !== undefined && (unified === FIELD_SUBTYPE_BOOLEAN || NON_SCALAR_SUBTYPES.has(unified))) { + errors.push(`'${name}' needs ordered arguments, got ${unified}`); + } + const type = sig.result === "same" ? unified : sig.result === "int" ? FIELD_SUBTYPE_INT : FIELD_SUBTYPE_STRING; + return { type, errors }; } const op = n.op as string; if (COMPARISON_OPS.has(op)) { - const l = inferExprType(n.left as ExprNode, resolveField); - const r = inferExprType(n.right as ExprNode, resolveField); + const l = inferExprType(n.left as ExprNode, resolveField, isIntStoredEnum); + const r = inferExprType(n.right as ExprNode, resolveField, isIntStoredEnum); const errors = [...l.errors, ...r.errors]; if (l.type !== undefined && !opsForSubType(l.type).includes(op as FilterOp)) { errors.push(`op '${op}' is not legal for a ${l.type} operand`); @@ -215,13 +385,13 @@ export function inferExprType(node: ExprNode, resolveField: (name: string) => st return { type: FIELD_SUBTYPE_BOOLEAN, errors }; } if (NULL_OPS.has(op)) { - return { type: FIELD_SUBTYPE_BOOLEAN, errors: inferExprType(n.arg as ExprNode, resolveField).errors }; + return { type: FIELD_SUBTYPE_BOOLEAN, errors: inferExprType(n.arg as ExprNode, resolveField, isIntStoredEnum).errors }; } if (op === EXPR_OP_NOT || VARIADIC_LOGIC_OPS.has(op)) { const kids = op === EXPR_OP_NOT ? [n.arg as ExprNode] : (n.args as ExprNode[]); const errors: string[] = []; for (const k of kids) { - const kt = inferExprType(k, resolveField); + const kt = inferExprType(k, resolveField, isIntStoredEnum); errors.push(...kt.errors); if (kt.type !== undefined && kt.type !== FIELD_SUBTYPE_BOOLEAN) { errors.push(`op '${op}' requires boolean operands, got ${kt.type}`); diff --git a/server/typescript/packages/metadata/src/core/object/object-constants.ts b/server/typescript/packages/metadata/src/core/object/object-constants.ts index 4666d902ee..33c3fd2ff2 100644 --- a/server/typescript/packages/metadata/src/core/object/object-constants.ts +++ b/server/typescript/packages/metadata/src/core/object/object-constants.ts @@ -56,6 +56,11 @@ export const OBJECT_ATTR_DB_SET_NAME = "dbSetName"; * but resolves against the projection's OWN declared fields rather than one * aggregated entity. An aggregate-derived field is not addressable (fail-closed). */ export const OBJECT_PROJECTION_ATTR_FILTER = "filter"; +// rc.21 part B: a projection UNIONed with others (U15), and one with a row per array element (U14). +export const OBJECT_PROJECTION_ATTR_UNION = "union"; +export const OBJECT_PROJECTION_ATTR_UNION_ALL = "unionAll"; +export const OBJECT_PROJECTION_ATTR_GRAIN = "grain"; +export const OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL = "grainOrdinal"; // --------------------------------------------------------------------------- // FR-044 — object.report attrs diff --git a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts index 7615d6e12f..50c0974f30 100644 --- a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts @@ -198,6 +198,39 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { + "type": "attr", + "subType": "string", + "name": "union", + "isArray": true, + "min": 0, + "max": 1, + "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." + }, + { + "type": "attr", + "subType": "boolean", + "name": "unionAll", + "min": 0, + "max": 1, + "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." + }, + { + "type": "attr", + "subType": "string", + "name": "grain", + "min": 0, + "max": 1, + "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." + }, + { + "type": "attr", + "subType": "string", + "name": "grainOrdinal", + "min": 0, + "max": 1, + "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." + }, { "type": "attr", "subType": "string", diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts index d2934b959c..970c5ea3f2 100644 --- a/server/typescript/packages/metadata/src/index.ts +++ b/server/typescript/packages/metadata/src/index.ts @@ -96,7 +96,10 @@ export { } from "./core/requirement/resolve-claim.js"; export * from "./core/relationship/relationship-constants.js"; export * from "./core/query/query-constants.js"; -export { EXPR_OP_IS_NOT_NULL, EXPR_OP_NOT, EXPR_FN_COALESCE, type ExprNode } from "./core/attr/meta-attr-expression.js"; +export { + EXPR_OP_IS_NOT_NULL, EXPR_OP_NOT, EXPR_FN_COALESCE, EXPR_CAST, EXPR_CAST_AS, EXPR_CAST_DB_COLUMN_TYPE, EXPR_FUNCTIONS, EXPR_CAST_TARGETS, + castProblem, exprViewOnlyNode, type ExprNode, +} from "./core/attr/meta-attr-expression.js"; export * from "./persistence/source/source-constants.js"; export * from "./persistence/origin/origin-constants.js"; export * from "./template/template-constants.js"; diff --git a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts index ad31e8eb53..75968a48cd 100644 --- a/server/typescript/packages/metadata/src/loader/meta-data-loader.ts +++ b/server/typescript/packages/metadata/src/loader/meta-data-loader.ts @@ -26,7 +26,7 @@ import type { LoaderWarning } from "../source.js"; import { codeSource, resolvedSource } from "../source.js"; import { parseJson } from "../parser-json.js"; import { validateDataGridSortFields, validateFilterableHasIndex, validateFilterableHasSupportedOps, validateSortableHasSupportedSubtype, validateOriginPaths, validateDerivedFieldProvidability, validateDataGridFilterValues, validateFieldObjectStorage, validateFieldMap, - validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; + validateEnumMaxLength, validateIdentitySequence, validateCrossFieldValidators, validateDbCheck, validateTemplatePayloadRefs, validateFieldDefaults, validateRelationships, validateOneSideReferenceResolution, validateM2MJunctionPairing, validateIndexLookupFields, validateProjectionFilter, validateOriginSegmentsAndCorrelation, validateProjectionUnionAndGrain, validateRetiredRequirementLinks, validateColumnNameCollisions } from "./validation-passes.js"; import { validateReporting } from "./reporting-validation.js"; import { runRegisteredValidation } from "./validation-registry.js"; import { validateSourceRoles } from "../persistence/source/validate-source-roles.js"; @@ -663,6 +663,8 @@ export class MetaDataLoader { // an aggregate-derived or dangling ref is fail-closed (ERR_BAD_ATTR_FILTER). errors.push(...validateProjectionFilter(root)); errors.push(...validateOriginSegmentsAndCorrelation(root)); + // rc.21 part B — @union shapes and @grain projections. + errors.push(...validateProjectionUnionAndGrain(root)); // FR-044 — reporting vocabulary cross-node rules (dimensions, measures, // segments, reports, relative-date filter values). diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 4844b376a3..632892e112 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -70,6 +70,10 @@ import { OBJECT_SUBTYPE_ENTITY, OBJECT_SUBTYPE_VALUE, OBJECT_SUBTYPE_PROJECTION, + OBJECT_PROJECTION_ATTR_UNION, + OBJECT_PROJECTION_ATTR_UNION_ALL, + OBJECT_PROJECTION_ATTR_GRAIN, + OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, } from "../core/object/object-constants.js"; import { MetaSource } from "../persistence/source/meta-source.js"; import { resolveColumnName } from "../naming.js"; @@ -85,6 +89,7 @@ import { FIELD_ATTR_OBJECT_REF, FIELD_ATTR_STORAGE, STORAGE_FLATTENED, + STORAGE_JSONB, FIELD_ATTR_DEFAULT, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, @@ -108,7 +113,7 @@ import { FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, } from "../core/field/field-constants.js"; -import { FIELD_ATTR_FLATTENED_COLUMN_PREFIX, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START } from "../persistence/db/db-constants.js"; +import { FIELD_ATTR_COLUMN, FIELD_ATTR_FLATTENED_COLUMN_PREFIX, FIELD_ATTR_DB_INDEXED, IDENTITY_ATTR_EXPR, IDENTITY_ATTR_SEQUENCE_NAME, IDENTITY_ATTR_SEQUENCE_START } from "../persistence/db/db-constants.js"; import { IDENTITY_ATTR_FIELDS, IDENTITY_SUBTYPE_REFERENCE, @@ -119,6 +124,11 @@ import { ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, + ORIGIN_FUNCTION_ATTR_FUNCTION, + ORIGIN_FUNCTION_ATTR_SCHEMA, + ORIGIN_FUNCTION_ATTR_ARGS, + ORIGIN_FUNCTION_IDENTIFIER, ORIGIN_PASSTHROUGH_ATTR_FROM, ORIGIN_PASSTHROUGH_ATTR_VIA, ORIGIN_PASSTHROUGH_ATTR_CONVERT, @@ -145,6 +155,7 @@ import { import { inferExprType, validateExprNode, + exprViewOnlyNode, type ExprNode, } from "../core/attr/meta-attr-expression.js"; import { SORT_ORDER_VALUES } from "../core/query/query-constants.js"; @@ -1369,6 +1380,24 @@ export function validateOriginPaths(root: MetaData): ParseError[] { continue; } const fromTarget = _validateFromPath(from, root, obj, field.name, origin.source, errors); + // rc.21 part B (U14): on a @grain projection, a @from on the grain field's value object + // reads a member of the array element; there is no path to walk. + if (fromTarget !== undefined && fromTarget.entity === _grainValueObject(obj, root)) { + const convert = origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_CONVERT) === true; + _checkPassthroughType(field, fromTarget.field, from, convert, obj, origin.source, errors); + const member = fromTarget.field as { resolvedIsArray?: () => boolean }; + if (member.resolvedIsArray?.() === true || fromTarget.field.subType === FIELD_SUBTYPE_OBJECT || fromTarget.field.subType === FIELD_SUBTYPE_MAP) { + errors.push(new ParseError( + `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" is not a scalar member of the @grain element.`, + { code: "ERR_INVALID_ORIGIN", source: origin.source })); + } + if (origin.ownAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) !== undefined) { + errors.push(new ParseError( + `origin.passthrough on ${obj.name}.${field.name}: @from "${from}" reads the @grain element, which takes no @via.`, + { code: "ERR_INVALID_ORIGIN", source: origin.source })); + } + continue; + } // FR-024 B6 — extends/origin agreement (host-agnostic; runs whether // @via is explicit, inferred, or a base-relation column). if (fromTarget !== undefined) { @@ -1622,18 +1651,33 @@ export function validateOriginPaths(root: MetaData): ParseError[] { const base = _deriveBaseEntity(obj, root, field.name, src, errors); if (base === undefined) continue; // rc.19 computed-over-joined: a ref names one of the projection's own fields first (a - // passthrough — joined or not —, an origin.first or another origin.computed), else a base - // field. Never itself, never an aggregate (it would need the grouped row). - const resolveField = (name: string): string | undefined => { + // passthrough — joined or not —, an origin.first, another origin.computed or, rc.21 U13, a + // scalar origin.aggregate, read on the grouped row), else a base field, else (rc.21 U3, a + // projection only) a PATH of to-one hops from the base and a field of the entity reached, + // joined but not output. Never itself; never a collect (an array). + const fieldNode = (name: string): MetaData | undefined => { if (obj !== base && name !== field.name) { const own = obj.children().find((f) => f.type === TYPE_FIELD && f.name === name); - const ownOrigin = own?.ownChildren().find((c) => c.type === TYPE_ORIGIN); - if (own !== undefined && ownOrigin?.subType !== ORIGIN_SUBTYPE_AGGREGATE) return own.subType; - if (own !== undefined) return undefined; + if (own !== undefined) return own; } - return base.children().find((f) => f.type === TYPE_FIELD && f.name === name)?.subType; + const baseField = base.children().find((f) => f.type === TYPE_FIELD && f.name === name); + if (baseField !== undefined || obj === base || !name.includes(".")) return baseField; + const path = resolveFilterPath(base as MetaObject, name); + return path !== undefined && typeof path !== "string" ? path.field : undefined; + }; + const resolveField = (name: string): string | undefined => { + const node = fieldNode(name); + if (node === undefined) return undefined; + const nodeOrigin = node.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (node !== field && nodeOrigin?.subType === ORIGIN_SUBTYPE_AGGREGATE + && nodeOrigin.ownAttr(ORIGIN_AGGREGATE_ATTR_AGG) === AGG_COLLECT) return undefined; + return node.subType; + }; + const isIntStoredEnum = (name: string): boolean => { + const node = fieldNode(name); + return node?.subType === FIELD_SUBTYPE_ENUM && node.attr(FIELD_ATTR_INT_VALUE_MAP) !== undefined; }; - const inferred = inferExprType(expr as ExprNode, resolveField); + const inferred = inferExprType(expr as ExprNode, resolveField, isIntStoredEnum); if (inferred.errors.length > 0) { for (const m of inferred.errors) { errors.push(new ParseError( @@ -1693,6 +1737,8 @@ export function validateOriginPaths(root: MetaData): ParseError[] { _validateOrderByKeys( origin.ownAttr(ORIGIN_ATTR_ORDER_BY), ofTarget?.entity, obj, field.name, "origin.first", src, errors); + } else if (origin.subType === ORIGIN_SUBTYPE_FUNCTION) { + _validateFunctionOrigin(origin, obj, field, root, errors); } } } @@ -1700,6 +1746,49 @@ export function validateOriginPaths(root: MetaData): ParseError[] { return errors; } +/** + * rc.21 part B (U10) — origin.function: a call of a database function the project owns. Its name + * and schema are plain identifiers (never free SQL); each argument names a scalar field of the + * host (an entity), or of the projection (not an aggregate, not the field itself) or its base. + */ +function _validateFunctionOrigin(origin: MetaData, obj: MetaData, field: MetaData, root: MetaData, errors: ParseError[]): void { + const src = origin.source; + const where = `origin.function on ${obj.name}.${field.name}`; + // ADR-0039: own — origin.* never inherits (ADR-0029). + for (const attr of [ORIGIN_FUNCTION_ATTR_FUNCTION, ORIGIN_FUNCTION_ATTR_SCHEMA]) { + const v = origin.ownAttr(attr); + if (v !== undefined && (typeof v !== "string" || !ORIGIN_FUNCTION_IDENTIFIER.test(v))) { + errors.push(new ParseError( + `${where}: @${attr} ${JSON.stringify(v)} is not a plain identifier ([A-Za-z_][A-Za-z0-9_]*); a function is named, never written as SQL.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + } + const raw = origin.ownAttr(ORIGIN_FUNCTION_ATTR_ARGS); + const args = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; + const isProjection = obj.subType === OBJECT_SUBTYPE_PROJECTION; + const base = isProjection ? _deriveBaseEntity(obj, root, field.name, src, []) : obj; + for (const name of args) { + const own = typeof name === "string" && name !== field.name + ? obj.children().find((c) => c.type === TYPE_FIELD && c.name === name) : undefined; + const ownOrigin = own?.ownChildren().find((c) => c.type === TYPE_ORIGIN); + const arg = own ?? (typeof name === "string" && base !== undefined + ? base.children().find((c) => c.type === TYPE_FIELD && c.name === name) : undefined); + if (arg === undefined || name === field.name) { + errors.push(new ParseError( + `${where}: @args names "${String(name)}", which is not a field of ${isProjection ? `the projection or its base entity` : `"${obj.name}"`}.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } else if (ownOrigin?.subType === ORIGIN_SUBTYPE_AGGREGATE) { + errors.push(new ParseError( + `${where}: @args names "${String(name)}", an origin.aggregate; a function takes values of the row, not of the group.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } else if (arg.subType === FIELD_SUBTYPE_OBJECT || arg.subType === FIELD_SUBTYPE_MAP || (arg as { resolvedIsArray?: () => boolean }).resolvedIsArray?.()) { + errors.push(new ParseError( + `${where}: @args names "${String(name)}", a field.${arg.subType}${(arg as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() ? " array" : ""}; a function argument is a scalar.`, + { code: "ERR_INVALID_ORIGIN", source: src })); + } + } +} + // --------------------------------------------------------------------------- // FR-024 B6 — derived-field providability (spec §7 population doctrine). // @@ -1746,8 +1835,8 @@ export function validateDerivedFieldProvidability(root: MetaData): ParseError[] if (origin === undefined) continue; // rc.19 entity-derived: a derived field a projection reaches (its @filter or a passthrough // @from) is lowered inline there, so it needs no read source. Only the inlinable origins. - if ((origin.subType === ORIGIN_SUBTYPE_FIRST || origin.subType === ORIGIN_SUBTYPE_COMPUTED) - && reached.has(field)) continue; + if ((origin.subType === ORIGIN_SUBTYPE_FIRST || origin.subType === ORIGIN_SUBTYPE_COMPUTED + || origin.subType === ORIGIN_SUBTYPE_FUNCTION) && reached.has(field)) continue; errors.push( new ParseError( `derived field "${obj.name}.${field.name}" carries an origin.* but entity "${obj.name}" declares no ` + @@ -1795,6 +1884,15 @@ export function projectionReachedEntityFields(root: MetaData): Set { const target = _validateFromPath(from, root, obj, field.name, origin.source, silent); if (target !== undefined) reached.add(target.field); } + // rc.21 part B (U3): a computed expression's path ref reaches the field at its end. + for (const origin of field.ownChildren().filter((c) => c.type === TYPE_ORIGIN && c.subType === ORIGIN_SUBTYPE_COMPUTED)) { + if (base === undefined || base === obj) continue; + for (const name of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) { + if (!name.includes(".")) continue; + const path = resolveFilterPath(base as MetaObject, name); + if (path !== undefined && typeof path !== "string") reached.add(path.field); + } + } } } return reached; @@ -1831,7 +1929,7 @@ export function validateOriginSegmentsAndCorrelation(root: MetaData): ParseError const silent: ParseError[] = []; const base = _deriveBaseEntity(obj, root, field.name, origin.source, silent); if (base === undefined) continue; - checkCorrelatedOperands(filter, base, where, origin.source, errors); + checkCorrelatedOperands(filter, base, where, origin.source, errors, obj.subType === OBJECT_SUBTYPE_PROJECTION); } } } @@ -1860,11 +1958,13 @@ function originRelatedEntity(origin: MetaData, obj: MetaData, root: MetaData): M return current; } -function checkCorrelatedOperands(filter: unknown, base: MetaData, where: string, source: ErrorSource, errors: ParseError[]): void { +function checkCorrelatedOperands( + filter: unknown, base: MetaData, where: string, source: ErrorSource, errors: ParseError[], onProjection: boolean, +): void { if (typeof filter !== "object" || filter === null || Array.isArray(filter)) return; for (const [key, clause] of Object.entries(filter as Record)) { if (key === FILTER_COMPOSE_AND || key === FILTER_COMPOSE_OR) { - if (Array.isArray(clause)) for (const sub of clause) checkCorrelatedOperands(sub, base, where, source, errors); + if (Array.isArray(clause)) for (const sub of clause) checkCorrelatedOperands(sub, base, where, source, errors, onProjection); continue; } if (typeof clause !== "object" || clause === null || Array.isArray(clause)) continue; @@ -1887,8 +1987,17 @@ function checkCorrelatedOperands(filter: unknown, base: MetaData, where: string, { code: "ERR_BAD_ATTR_FILTER", source }, )); } else if (typeof name !== "string" || !base.children().some((c) => c.type === TYPE_FIELD && c.name === name)) { + // rc.21 part B (U4): on a projection, the operand may be a PATH of to-one hops from the base + // row and a field of the entity reached ("taskId.caseId"), joined on the outer row. + const path = typeof name === "string" && name.includes(".") && onProjection + ? resolveFilterPath(base as MetaObject, name) : undefined; + if (path !== undefined && typeof path !== "string") continue; errors.push(new ParseError( - `${where}: @filter on "${key}" names base-row field "${String(name)}", which "${base.name}" does not declare.`, + typeof path === "string" + ? `${where}: @filter on "${key}" compares with the base-row path "${name}": ${path}.` + : typeof name === "string" && name.includes(".") && !onProjection + ? `${where}: @filter on "${key}" compares with the path "${name}"; a path operand is legal only on a projection, whose view joins it.` + : `${where}: @filter on "${key}" names base-row field "${String(name)}", which "${base.name}" does not declare.`, { code: "ERR_BAD_ATTR_FILTER", source }, )); } @@ -1910,8 +2019,16 @@ function expressionFieldRefs(node: unknown, out: string[] = []): string[] { if (typeof node !== "object" || node === null) return out; const n = node as Record; if (typeof n["field"] === "string") out.push(n["field"]); - for (const key of ["left", "right", "arg"]) expressionFieldRefs(n[key], out); + for (const key of ["left", "right", "arg", "cast", "operand", "else"]) expressionFieldRefs(n[key], out); for (const key of ["args"]) if (Array.isArray(n[key])) for (const a of n[key] as unknown[]) expressionFieldRefs(a, out); + if (Array.isArray(n["case"])) { + for (const arm of n["case"] as unknown[]) { + if (typeof arm === "object" && arm !== null) { + expressionFieldRefs((arm as Record)["when"], out); + expressionFieldRefs((arm as Record)["then"], out); + } + } + } return out; } @@ -1931,6 +2048,13 @@ const _CONDITION_NUMBER_SUBTYPES = new Set([ * - no comparison has a null literal: `x = NULL` is never true, so use isNull / isNotNull. */ function conditionProblem(condition: unknown, obj: MetaObject): string | undefined { + // rc.21 part B: a CHECK holds the condition's SQL, rendered by every port's CHECK emitter, which + // takes fields, literals, comparisons, null tests, and / or / not and coalesce. The rest of the + // expression grammar (case, now, cast, the other functions, paths) is for views only. + const viewOnly = exprViewOnlyNode(condition); + if (viewOnly !== undefined) { + return `uses ${viewOnly}, which a CHECK condition cannot hold: it takes fields, literals, comparisons, null tests, and / or / not, and coalesce.`; + } const fields = new Map(obj.fields().map((f) => [f.name, f] as const)); const inferred = inferExprType(condition as ExprNode, (name) => fields.get(name)?.subType); if (inferred.errors.length > 0) return `is not a valid expression: ${inferred.errors.join("; ")}.`; @@ -3092,6 +3216,112 @@ function entityFieldAggregates(f: MetaData): boolean { return origin !== undefined && origin.subType === ORIGIN_SUBTYPE_AGGREGATE; } +/** rc.21 part B (U14): the value object a `@grain` projection's rows are elements of, if it has one. */ +function _grainValueObject(obj: MetaData, root: MetaData): MetaData | undefined { + if (obj.subType !== OBJECT_SUBTYPE_PROJECTION) return undefined; + const grain = obj.attr(OBJECT_PROJECTION_ATTR_GRAIN); + if (typeof grain !== "string") return undefined; + const base = _deriveBaseEntity(obj, root, "@grain", obj.source, []); + const field = base?.children().find((c) => c.type === TYPE_FIELD && c.name === grain); + return field === undefined ? undefined : refTarget(field, FIELD_ATTR_OBJECT_REF); +} + +/** + * rc.21 part B — the projection shapes beside a plain view: + * - `@union` names projections whose rows join this one's: each must be an object.projection + * other than this one, with the same effective fields in order (name, subtype, array-ness and + * @column) — ERR_BAD_ATTR_VALUE otherwise; `@unionAll` needs `@union`; + * - `@grain` names a base-entity field.object array stored as jsonb; such a projection holds no + * origin.aggregate, and `@grainOrdinal` names one of its own field.int / field.long fields with + * no origin. + */ +export function validateProjectionUnionAndGrain(root: MetaData): ParseError[] { + const errors: ParseError[] = []; + for (const obj of root.children().filter((c) => c.type === TYPE_OBJECT && c.subType === OBJECT_SUBTYPE_PROJECTION)) { + const bad = (message: string): void => { + errors.push(new ParseError(`object.projection ${obj.name}: ${message}`, { code: "ERR_BAD_ATTR_VALUE", source: obj.source })); + }; + // ADR-0039: own — a projection's @union, @grain names ITS view's shape; an extender declares its own. + const union = obj.ownAttr(OBJECT_PROJECTION_ATTR_UNION); + if (obj.ownAttr(OBJECT_PROJECTION_ATTR_UNION_ALL) !== undefined && union === undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION_ALL} needs @${OBJECT_PROJECTION_ATTR_UNION}.`); + } + if (union !== undefined) { + const referrerPkg = obj.package ?? obj.fileDefaultPackage ?? ""; + const mine = obj.children().filter((c) => c.type === TYPE_FIELD); + for (const name of Array.isArray(union) ? union : [union]) { + const member = typeof name === "string" ? resolveObjectRef(root, name, referrerPkg).node : undefined; + if (member === undefined || member.type !== TYPE_OBJECT || member.subType !== OBJECT_SUBTYPE_PROJECTION) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} names "${String(name)}", which is not an object.projection.`); + continue; + } + if (member === obj) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} names the projection itself.`); + continue; + } + const theirs = member.children().filter((c) => c.type === TYPE_FIELD); + const describe = (f: MetaData): string => { + const arr = (f as { resolvedIsArray?: () => boolean }).resolvedIsArray?.() === true ? "[]" : ""; + const col = f.attr(FIELD_ATTR_COLUMN); + return `${f.name}: field.${f.subType}${arr}${typeof col === "string" ? ` @column ${col}` : ""}`; + }; + const a = mine.map(describe); + const b = theirs.map(describe); + if (a.length !== b.length || a.some((x, i) => x !== b[i])) { + bad(`@${OBJECT_PROJECTION_ATTR_UNION} member "${member.name}" has a different shape: ` + + `(${b.join(", ")}) where this view is (${a.join(", ")}). A union's members have the same fields, in order.`); + } + } + } + const grain = obj.ownAttr(OBJECT_PROJECTION_ATTR_GRAIN); + const ordinal = obj.ownAttr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL); + if (ordinal !== undefined && grain === undefined) bad(`@${OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} needs @${OBJECT_PROJECTION_ATTR_GRAIN}.`); + if (typeof grain === "string") { + const base = _deriveBaseEntity(obj, root, "@grain", obj.source, []); + const field = base?.children().find((c) => c.type === TYPE_FIELD && c.name === grain); + const isArray = (field as { resolvedIsArray?: () => boolean } | undefined)?.resolvedIsArray?.() === true; + const storage = field?.attr(FIELD_ATTR_STORAGE); + if (field === undefined || field.subType !== FIELD_SUBTYPE_OBJECT || !isArray || (storage !== undefined && storage !== STORAGE_JSONB) + || refTarget(field, FIELD_ATTR_OBJECT_REF) === undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_GRAIN} "${grain}" must name a field.object array (isArray, jsonb storage, with @objectRef) of the base entity${base === undefined ? "" : ` "${base.name}"`}.`); + } + for (const f of obj.children().filter((c) => c.type === TYPE_FIELD)) { + if (f.ownChildren().some((c) => c.type === TYPE_ORIGIN && c.subType === ORIGIN_SUBTYPE_AGGREGATE)) { + bad(`"${f.name}" is an origin.aggregate; a @grain view has one row per element and groups nothing.`); + } + } + if (ordinal !== undefined) { + const f = obj.children().find((c) => c.type === TYPE_FIELD && c.name === ordinal); + if (f === undefined || (f.subType !== FIELD_SUBTYPE_INT && f.subType !== FIELD_SUBTYPE_LONG) + || f.ownChildren().some((c) => c.type === TYPE_ORIGIN) || f.superRef !== undefined) { + bad(`@${OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} "${String(ordinal)}" must name a field.int or field.long of the projection, with no origin and no extends.`); + } + } + } + } + return errors; +} + +/** + * rc.21 part B (U13): whether an origin.computed reads an origin.aggregate of its projection, + * directly or through another computed. Such a value exists only on the grouped row, so a WHERE + * (the view @filter) cannot hold it. + */ +function computedReadsAggregate(f: MetaData, obj: MetaData, seen: Set = new Set()): boolean { + if (seen.has(f.name)) return false; + seen.add(f.name); + // ADR-0039: own — origin.* never inherits (ADR-0029). + const origin = f.ownChildren().find((c) => c.type === TYPE_ORIGIN); + if (origin?.subType !== ORIGIN_SUBTYPE_COMPUTED) return false; + for (const name of expressionFieldRefs(origin.ownAttr(ORIGIN_COMPUTED_ATTR_EXPR))) { + if (name === f.name) continue; + const other = obj.children().find((c) => c.type === TYPE_FIELD && c.name === name); + if (other === undefined) continue; + if (entityFieldAggregates(other) || computedReadsAggregate(other, obj, seen)) return true; + } + return false; +} + /** Every field key of a (desugared) filter, through and/or. */ function filterKeys(filter: unknown, out: string[] = []): string[] { if (typeof filter !== "object" || filter === null || Array.isArray(filter)) return out; @@ -3126,7 +3356,7 @@ export function validateProjectionFilter(root: MetaData): ParseError[] { const derived = origin !== undefined && origin.subType !== ORIGIN_SUBTYPE_PASSTHROUGH && - origin.subType !== ORIGIN_SUBTYPE_COMPUTED; + (origin.subType !== ORIGIN_SUBTYPE_COMPUTED || computedReadsAggregate(f, obj)); // opsForField, not opsForSubType — an int-backed field.enum (@intValueMap) // stores as an integer, so `like` is not in its band. fields.set(f.name, { derived, ops: opsForField(f) }); diff --git a/server/typescript/packages/metadata/src/persistence/db/db-constants.ts b/server/typescript/packages/metadata/src/persistence/db/db-constants.ts index 3ec3dfcdf5..72838fd33b 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-constants.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-constants.ts @@ -58,28 +58,75 @@ export const DB_COLUMN_TYPE_JSONB = "jsonb"; */ export const FIELD_ATTR_LOCAL_TIME = "localTime"; +/** rc.21 part B (U2): the text column spellings `@dbColumnType` takes on a field.string. */ +export const DB_COLUMN_TYPE_TEXT = "text"; +export const DB_COLUMN_TYPE_VARCHAR = "varchar"; +export const DB_COLUMN_TYPE_CHARACTER_VARYING = "character varying"; + /** - * The closed set of legal `@dbColumnType` values (raw-dialect passthrough deferred). + * The closed set of legal bare `@dbColumnType` values (raw-dialect passthrough deferred). * dbColumnType slim-and-derive (ADR-0036 Wave 1, decision 4): the native-array * overrides `uuid_array`/`text_array` are fully removed — native `uuid[]`/`text[]` * are DERIVED from a field subtype + `isArray`, never declared via an escape hatch. * Wave 2 (decision 1) retires `timestamp_with_tz` entirely — tz-awareness moves to - * `field.timestamp` (instant by default) + `@localTime` (the naive opt-out). The - * legal set is now just `{ uuid, jsonb }`, both on field.string. + * `field.timestamp` (instant by default) + `@localTime` (the naive opt-out). + * rc.21 part B (U2) adds the text spellings: `text`, an unbounded `varchar` / `character + * varying`, and the sized `varchar(n)`, `character varying(n)` and `character(n)` + * ({@link parseDbColumnType}), all on field.string. */ export const DB_COLUMN_TYPE_VALUES = [ DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + DB_COLUMN_TYPE_TEXT, + DB_COLUMN_TYPE_VARCHAR, + DB_COLUMN_TYPE_CHARACTER_VARYING, ] as const; export type DbColumnTypeValue = (typeof DB_COLUMN_TYPE_VALUES)[number]; +/** The sized spellings, as written in a message: `n` is a positive integer. */ +export const DB_COLUMN_TYPE_SIZED_SPELLINGS = ["varchar(n)", "character varying(n)", "character(n)"] as const; + /** * Legal `@dbColumnType` value → the field subtypes it may be applied to (ADR-0013, * R6 Plan 2b). Any other (subtype × value) pairing — or an unrecognized value — is * an ERR_BAD_ATTR_VALUE. Keyed by value; the value-set is enforced by membership in - * this map. Subtype names are the bare FIELD_SUBTYPE_* constants (string). + * this map. Subtype names are the bare FIELD_SUBTYPE_* constants (string). The sized + * spellings are field.string's too. */ export const DB_COLUMN_TYPE_LEGAL_SUBTYPES: Readonly> = { [DB_COLUMN_TYPE_UUID]: [FIELD_SUBTYPE_STRING], [DB_COLUMN_TYPE_JSONB]: [FIELD_SUBTYPE_STRING], + [DB_COLUMN_TYPE_TEXT]: [FIELD_SUBTYPE_STRING], + [DB_COLUMN_TYPE_VARCHAR]: [FIELD_SUBTYPE_STRING], + [DB_COLUMN_TYPE_CHARACTER_VARYING]: [FIELD_SUBTYPE_STRING], } as const; + +/** A parsed `@dbColumnType`: what the column is, and its declared length for a sized spelling. */ +export type ParsedDbColumnType = + | { readonly kind: "uuid" } + | { readonly kind: "jsonb" } + | { readonly kind: "text" } + | { readonly kind: "varchar"; readonly length?: number } + | { readonly kind: "char"; readonly length: number }; + +/** + * rc.21 part B (U2): parse a `@dbColumnType` value, or undefined for one that is not legal. The + * spellings are Postgres's own, matched exactly (lowercase, one space): `varchar` and `character + * varying` are the one unbounded varying type, `varchar(n)` and `character varying(n)` the sized + * one, `character(n)` the fixed-length one. Every port parses them alike. + */ +export function parseDbColumnType(value: string): ParsedDbColumnType | undefined { + if (value === DB_COLUMN_TYPE_UUID) return { kind: "uuid" }; + if (value === DB_COLUMN_TYPE_JSONB) return { kind: "jsonb" }; + if (value === DB_COLUMN_TYPE_TEXT) return { kind: "text" }; + if (value === DB_COLUMN_TYPE_VARCHAR || value === DB_COLUMN_TYPE_CHARACTER_VARYING) return { kind: "varchar" }; + const sized = /^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$/.exec(value); + if (sized === null) return undefined; + const length = Number(sized[2]); + return sized[1] === "character" ? { kind: "char", length } : { kind: "varchar", length }; +} + +/** The field subtypes a `@dbColumnType` value is legal on, or undefined for a value that is not legal. */ +export function dbColumnTypeLegalSubtypes(value: string): readonly string[] | undefined { + return parseDbColumnType(value) === undefined ? undefined : [FIELD_SUBTYPE_STRING]; +} diff --git a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts index 55920a3b9b..0d397c0a23 100644 --- a/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/db/db-definition.embedded.ts @@ -35,11 +35,7 @@ export const DB_DEFINITION: ProviderDefinition = { "name": "dbColumnType", "min": 0, "max": 1, - "allowedValues": [ - "uuid", - "jsonb" - ], - "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." + "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts index aec0b4d2ab..58fca964bd 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-constants.ts @@ -27,6 +27,8 @@ export const ORIGIN_SUBTYPE_AGGREGATE = "aggregate"; // by @orderBy along @via, projecting @of (argmax-then-project). export const ORIGIN_SUBTYPE_COMPUTED = "computed"; export const ORIGIN_SUBTYPE_FIRST = "first"; +// rc.21 part B (U10): a value computed by a database function the project owns. +export const ORIGIN_SUBTYPE_FUNCTION = "function"; export const ORIGIN_SUBTYPES = [ SUBTYPE_BASE, @@ -34,6 +36,7 @@ export const ORIGIN_SUBTYPES = [ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ] as const; export type OriginSubType = (typeof ORIGIN_SUBTYPES)[number]; @@ -46,6 +49,7 @@ export const ASSEMBLY_ORIGIN_SUBTYPES = [ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ] as const; // passthrough attrs @@ -81,6 +85,13 @@ export const ORIGIN_FIRST_ATTR_OF = "of"; export const ORIGIN_FIRST_ATTR_VIA = "via"; export const ORIGIN_FIRST_ATTR_FILTER = "filter"; +// rc.21 part B (U10) origin.function attrs: the function's name, its schema, and its arguments. +export const ORIGIN_FUNCTION_ATTR_FUNCTION = "function"; +export const ORIGIN_FUNCTION_ATTR_SCHEMA = "schema"; +export const ORIGIN_FUNCTION_ATTR_ARGS = "args"; +/** A plain SQL identifier: what @function and @schema may hold (never free SQL). */ +export const ORIGIN_FUNCTION_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/; + // aggregate function vocabulary. // // AGGREGATE_FUNCTIONS is the NUMERIC/ORDINAL reduce set — each maps directly to a diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index 4b0e3618a2..ab1561f855 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -138,6 +138,39 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { + "type": "attr", + "subType": "string", + "name": "function", + "min": 1, + "max": 1, + "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." + }, + { + "type": "attr", + "subType": "string", + "name": "schema", + "min": 0, + "max": 1, + "description": "The schema the function lives in, a plain identifier. Absent: public." + }, + { + "type": "attr", + "subType": "string", + "name": "args", + "isArray": true, + "min": 0, + "max": 1, + "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." + } + ] + }, { "type": "origin", "subType": "first", diff --git a/server/typescript/packages/metadata/test/types/origin.test.ts b/server/typescript/packages/metadata/test/types/origin.test.ts index 5d5c0ed1bb..e97ba19986 100644 --- a/server/typescript/packages/metadata/test/types/origin.test.ts +++ b/server/typescript/packages/metadata/test/types/origin.test.ts @@ -24,9 +24,9 @@ describe("origin type constants", () => { expect(ORIGIN_SUBTYPE_PASSTHROUGH).toBe("passthrough"); expect(ORIGIN_SUBTYPE_AGGREGATE).toBe("aggregate"); }); - test("ORIGIN_SUBTYPES contains base + passthrough + aggregate + computed + first", () => { + test("ORIGIN_SUBTYPES contains base + passthrough + aggregate + computed + first + function", () => { // FR-037 R2 (#336) retired `collection` to reserved-not-registered. - expect(ORIGIN_SUBTYPES).toEqual([SUBTYPE_BASE, "passthrough", "aggregate", "computed", "first"]); + expect(ORIGIN_SUBTYPES).toEqual([SUBTYPE_BASE, "passthrough", "aggregate", "computed", "first", "function"]); }); test("passthrough attrs are camelCase", () => { expect(ORIGIN_PASSTHROUGH_ATTR_FROM).toBe("from"); diff --git a/server/typescript/packages/migrate-ts/src/emit/postgres.ts b/server/typescript/packages/migrate-ts/src/emit/postgres.ts index 45c66d4367..44333c9ce1 100644 --- a/server/typescript/packages/migrate-ts/src/emit/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/emit/postgres.ts @@ -585,7 +585,10 @@ function identityOptions(c: Pick): string { export function pgType(t: SqlType): string { switch (t.kind) { - case "text": return t.maxLength !== undefined ? `VARCHAR(${t.maxLength})` : "TEXT"; + case "text": + if (t.variant === "char") return `CHARACTER(${t.maxLength ?? 1})`; + if (t.maxLength !== undefined) return `VARCHAR(${t.maxLength})`; + return t.variant === "varchar" ? "VARCHAR" : "TEXT"; case "integer": return t.bits === 64 ? "BIGINT" : "INTEGER"; case "real": return "DOUBLE PRECISION"; case "real4": return "REAL"; diff --git a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts index 61ab0fe8ab..526ded54f7 100644 --- a/server/typescript/packages/migrate-ts/src/emit/sqlite.ts +++ b/server/typescript/packages/migrate-ts/src/emit/sqlite.ts @@ -547,7 +547,10 @@ export function sqliteType(t: SqlType, identity: ColumnDescriptor["identity"]): if (identity === "increment") return "INTEGER"; if (identity === "uuid") return "TEXT"; switch (t.kind) { - case "text": return t.maxLength !== undefined ? `VARCHAR(${t.maxLength})` : "TEXT"; + case "text": + if (t.variant === "char") return `CHARACTER(${t.maxLength ?? 1})`; + if (t.maxLength !== undefined) return `VARCHAR(${t.maxLength})`; + return t.variant === "varchar" ? "VARCHAR" : "TEXT"; // Use INTEGER for 64-bit and INT for 32-bit — SQLite preserves the declared type // in pragma_table_info, enabling round-trip fidelity (see introspect/sqlite.ts). case "integer": return t.bits === 64 ? "INTEGER" : "INT"; diff --git a/server/typescript/packages/migrate-ts/src/expected-schema.ts b/server/typescript/packages/migrate-ts/src/expected-schema.ts index c89b0da5d0..98870d5490 100644 --- a/server/typescript/packages/migrate-ts/src/expected-schema.ts +++ b/server/typescript/packages/migrate-ts/src/expected-schema.ts @@ -63,6 +63,7 @@ import { FIELD_ATTR_DB_COLUMN_TYPE, DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + parseDbColumnType, FIELD_ATTR_LOCAL_TIME, FIELD_ATTR_LENIENT, STORAGE_FLATTENED, @@ -1790,6 +1791,11 @@ function subtypeToSqlType(field: MetaData): SqlType { case DB_COLUMN_TYPE_UUID: return { kind: "uuid" }; case DB_COLUMN_TYPE_JSONB: return { kind: "json" }; } + // rc.21 part B (U2): the text spellings. A sized one is the declared length. + const parsed = parseDbColumnType(dbColumnType); + if (parsed?.kind === "text") return { kind: "text" }; + if (parsed?.kind === "varchar") return parsed.length !== undefined ? { kind: "text", maxLength: parsed.length } : { kind: "text", variant: "varchar" }; + if (parsed?.kind === "char") return { kind: "text", maxLength: parsed.length, variant: "char" }; } // Native array columns are DERIVED from `isArray` (dbColumnType slim-and-derive diff --git a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts index 30dd7a93fe..764a0bf9b0 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/postgres.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/postgres.ts @@ -124,7 +124,13 @@ export function pgTypeToSqlType( return { kind: "text", maxLength: parseInt(varcharMatch[1] ?? "0", 10) }; } if (dt === "character varying" || dt === "varchar") { - return maxLength != null ? { kind: "text", maxLength } : { kind: "text" }; + return maxLength != null ? { kind: "text", maxLength } : { kind: "text", variant: "varchar" }; + } + // rc.21 part B (U2): the fixed-length character(n) (information_schema "character", udt bpchar). + const charMatch = /^(?:character|char|bpchar)\((\d+)\)$/.exec(dt); + if (charMatch) return { kind: "text", maxLength: parseInt(charMatch[1] ?? "1", 10), variant: "char" }; + if (dt === "character" || dt === "char" || dt === "bpchar") { + return { kind: "text", maxLength: maxLength ?? 1, variant: "char" }; } if (dt === "text") { return { kind: "text" }; diff --git a/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts b/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts index fc94ddffd4..d25ee8f8d5 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/sqlite-shared.ts @@ -63,8 +63,12 @@ export function sqliteTypeToSqlType(declaredType: string): SqlType { // Affinity rules per sqlite.org/datatype3.html — adapted to canonical SqlType. // text affinity - const varcharMatch = /^(?:VARCHAR|CHAR|CHARACTER|TEXT)\((\d+)\)$/.exec(t); + // rc.21 part B (U2): CHARACTER(n) is what the emitter writes for a fixed-length @dbColumnType. + const charMatch = /^CHARACTER\((\d+)\)$/.exec(t); + if (charMatch) return { kind: "text", maxLength: parseInt(charMatch[1] ?? "1", 10), variant: "char" }; + const varcharMatch = /^(?:VARCHAR|CHAR|TEXT)\((\d+)\)$/.exec(t); if (varcharMatch) return { kind: "text", maxLength: parseInt(varcharMatch[1] ?? "0", 10) }; + if (t === "VARCHAR") return { kind: "text", variant: "varchar" }; if (/TEXT|CLOB|VARCHAR|CHAR/.test(t)) return { kind: "text" }; // numeric affinity diff --git a/server/typescript/packages/migrate-ts/src/sql-type.ts b/server/typescript/packages/migrate-ts/src/sql-type.ts index 95a87ca29d..791cdfb56e 100644 --- a/server/typescript/packages/migrate-ts/src/sql-type.ts +++ b/server/typescript/packages/migrate-ts/src/sql-type.ts @@ -6,7 +6,10 @@ * Per spec §5.2. */ export type SqlType = - | { kind: "text"; maxLength?: number } + // rc.21 part B (U2): `variant` is the @dbColumnType spelling — "varchar" an unbounded + // `character varying` (Postgres treats it as text; the diff does not tell them apart), "char" a + // fixed-length `character(n)` (blank-padded, a different type). + | { kind: "text"; maxLength?: number; variant?: "varchar" | "char" } | { kind: "integer"; bits: 32 | 64 } | { kind: "real" } // DOUBLE PRECISION (float8) — field.double | { kind: "real4" } // REAL (float4, single precision) — field.float @@ -29,7 +32,10 @@ export type SqlType = */ export function describeSqlType(t: SqlType): string { switch (t.kind) { - case "text": return t.maxLength === undefined ? "text" : `text(${t.maxLength})`; + case "text": + if (t.variant === "char") return `character(${t.maxLength ?? 1})`; + if (t.variant === "varchar" && t.maxLength === undefined) return "varchar"; + return t.maxLength === undefined ? "text" : `text(${t.maxLength})`; case "integer": return t.bits === 64 ? "bigint" : "integer"; case "numeric": return t.precision === undefined ? "numeric" @@ -44,8 +50,12 @@ export function describeSqlType(t: SqlType): string { export function sqlTypeEquals(a: SqlType, b: SqlType): boolean { if (a.kind !== b.kind) return false; switch (a.kind) { - case "text": - return a.maxLength === (b as Extract).maxLength; + case "text": { + // An unbounded varchar and text are one type to Postgres (and to SQLite), so they compare + // equal; a fixed-length character(n) is a different one. + const bt = b as Extract; + return a.maxLength === bt.maxLength && (a.variant === "char") === (bt.variant === "char"); + } case "integer": return a.bits === (b as Extract).bits; case "numeric": { @@ -85,6 +95,8 @@ export function isWidening(from: SqlType, to: SqlType): boolean { switch (from.kind) { case "text": { const t = to as Extract; + // To or from a blank-padded character(n) is never a plain widening. + if ((from.variant === "char") !== (t.variant === "char")) return false; // unbounded → bounded: lossy if (from.maxLength === undefined) return false; // bounded → unbounded: widening diff --git a/spec/metamodel/attr.json b/spec/metamodel/attr.json index 0ccb0600b4..c05dab28b7 100644 --- a/spec/metamodel/attr.json +++ b/spec/metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/spec/metamodel/db.json b/spec/metamodel/db.json index 4b6a2d2452..e6b2898755 100644 --- a/spec/metamodel/db.json +++ b/spec/metamodel/db.json @@ -7,7 +7,7 @@ "children": [ { "type": "attr", "subType": "string", "name": "column", "min": 0, "max": 1, "description": "Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the \"naming\" setting in .metaobjects/config.json)." }, { "type": "attr", "subType": "boolean", "name": "db.indexed", "min": 0, "max": 1, "description": "When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means)." }, - { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "allowedValues": ["uuid", "jsonb"], "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } + { "type": "attr", "subType": "string", "name": "dbColumnType", "min": 0, "max": 1, "description": "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2." } ] }, { diff --git a/spec/metamodel/object.json b/spec/metamodel/object.json index ad1afce6de..7dbadfcd07 100644 --- a/spec/metamodel/object.json +++ b/spec/metamodel/object.json @@ -55,6 +55,10 @@ "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "implementedIn": ["csharp", "typescript"], "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." }, { "type": "attr", "subType": "string", "name": "dbSetName", "min": 0, "max": 1, "ports": ["csharp"], "description": "DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it." } ] diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index c4fde970f9..08e8584d24 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -42,6 +42,17 @@ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The structured expression tree computing this field's value from the base entity's own fields (closed node grammar; shares the filter op vocabulary). Its inferred root type must equal the field's declared subType (ERR_COMPUTED_TYPE_MISMATCH)." } ] }, + { + "type": "origin", + "subType": "function", + "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", + "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", + "children": [ + { "type": "attr", "subType": "string", "name": "function", "min": 1, "max": 1, "description": "The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase." }, + { "type": "attr", "subType": "string", "name": "schema", "min": 0, "max": 1, "description": "The schema the function lives in, a plain identifier. Absent: public." }, + { "type": "attr", "subType": "string", "name": "args", "isArray": true, "min": 0, "max": 1, "description": "The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments." } + ] + }, { "type": "origin", "subType": "first", From 7b0fefaf2c57726ac82839140cc40b88a370e76e Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 18:13:23 -0500 Subject: [PATCH 190/267] test(views): loader, golden-SQL, SQLite and conformance coverage for the rc.21 view vocabulary Loader accept and refuse cases for every construct; golden SQL on Postgres and SQLite, with the SQLite spellings run on a real SQLite; a conformance fixture that exercises the vocabulary and five error fixtures; regenerated metamodel docs, site reference and payload, and the registry coverage snapshot. Co-Authored-By: Claude Opus 5.5 --- examples/showcase/site-payload.json | 2 +- .../expected-errors.json | 15 + .../input/meta.views.json | 13 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.views.json | 8 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.views.json | 13 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.views.json | 12 + .../providers.json | 1 + .../expected-errors.json | 15 + .../input/meta.views.json | 18 + .../providers.json | 1 + .../expected.json | 498 ++++++++++++++++++ .../input/meta.views.json | 78 +++ .../providers.json | 1 + fixtures/metamodel-docs/expected/INDEX.md | 3 +- fixtures/metamodel-docs/expected/providers.md | 5 +- .../metamodel-docs/expected/types/attr.md | 2 +- .../metamodel-docs/expected/types/field.md | 38 +- .../metamodel-docs/expected/types/object.md | 4 + .../metamodel-docs/expected/types/origin.md | 20 + .../registry-conformance/coverage-report.json | 4 +- .../projection/rc21b-view-vocabulary.test.ts | 208 ++++++++ .../test/db-definition-completeness.test.ts | 5 +- .../object-definition-completeness.test.ts | 5 + .../origin-definition-completeness.test.ts | 6 + .../test/rc21b-view-vocabulary.test.ts | 203 +++++++ .../test/template-payload-target-210.test.ts | 2 + .../db-column-type-text-spellings.test.ts | 37 ++ .../integration/postgres-introspect.test.ts | 5 +- .../unit/introspect-postgres-helpers.test.ts | 4 +- site-reference/index.html | 7 +- site-reference/providers.html | 5 +- site-reference/types/attr.html | 2 +- site-reference/types/field.html | 76 +-- site-reference/types/object.html | 36 ++ site-reference/types/origin.html | 47 ++ 41 files changed, 1373 insertions(+), 74 deletions(-) create mode 100644 fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json create mode 100644 fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json create mode 100644 fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json create mode 100644 fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json create mode 100644 fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json create mode 100644 fixtures/conformance/error-db-column-type-sized-max-length/providers.json create mode 100644 fixtures/conformance/error-origin-function-free-sql/expected-errors.json create mode 100644 fixtures/conformance/error-origin-function-free-sql/input/meta.views.json create mode 100644 fixtures/conformance/error-origin-function-free-sql/providers.json create mode 100644 fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json create mode 100644 fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json create mode 100644 fixtures/conformance/error-projection-grain-not-object-array/providers.json create mode 100644 fixtures/conformance/error-projection-union-shape/expected-errors.json create mode 100644 fixtures/conformance/error-projection-union-shape/input/meta.views.json create mode 100644 fixtures/conformance/error-projection-union-shape/providers.json create mode 100644 fixtures/conformance/projection-view-vocabulary-rc21/expected.json create mode 100644 fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json create mode 100644 fixtures/conformance/projection-view-vocabulary-rc21/providers.json create mode 100644 server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts create mode 100644 server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts create mode 100644 server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json index 5637a5287c..d2b78de001 100644 --- a/examples/showcase/site-payload.json +++ b/examples/showcase/site-payload.json @@ -7,7 +7,7 @@ "metamodel": "1.3" }, "counts": { - "fixtures": 469, + "fixtures": 475, "corpora": 38, "baseTypes": 17 }, diff --git a/fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json b/fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json new file mode 100644 index 0000000000..16a68b392d --- /dev/null +++ b/fixtures/conformance/error-computed-cast-enum-not-int-stored/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection'].children[2]['field.int'].children[0]['origin.computed']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json b/fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json new file mode 100644 index 0000000000..6a6d328c77 --- /dev/null +++ b/fixtures/conformance/error-computed-cast-enum-not-int-stored/input/meta.views.json @@ -0,0 +1,13 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } }, + { "object.projection": { "name": "V", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.int": { "name": "k", "children": [ { "origin.computed": { "@expr": { "cast": { "field": "kind" }, "as": "int" } } } ] } } + ] } } +] } } diff --git a/fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json b/fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-computed-cast-enum-not-int-stored/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json b/fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json new file mode 100644 index 0000000000..2a8045ee08 --- /dev/null +++ b/fixtures/conformance/error-db-column-type-sized-max-length/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[2]['field.string']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json b/fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json new file mode 100644 index 0000000000..8da2de0e99 --- /dev/null +++ b/fixtures/conformance/error-db-column-type-sized-max-length/input/meta.views.json @@ -0,0 +1,8 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Region", "children": [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "code", "@dbColumnType": "character(3)", "@maxLength": 10 } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } } +] } } diff --git a/fixtures/conformance/error-db-column-type-sized-max-length/providers.json b/fixtures/conformance/error-db-column-type-sized-max-length/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-db-column-type-sized-max-length/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-origin-function-free-sql/expected-errors.json b/fixtures/conformance/error-origin-function-free-sql/expected-errors.json new file mode 100644 index 0000000000..61b9704fc4 --- /dev/null +++ b/fixtures/conformance/error-origin-function-free-sql/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_INVALID_ORIGIN", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[0]['object.entity'].children[3]['field.string'].children[0]['origin.function']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json b/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json new file mode 100644 index 0000000000..4f9f08c7ac --- /dev/null +++ b/fixtures/conformance/error-origin-function-free-sql/input/meta.views.json @@ -0,0 +1,13 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.function": { "@function": "tier_of(id); drop table customers", "@args": ["id"] } } ] } } + ] } }, + { "object.projection": { "name": "V", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Customer.id" } }, + { "field.string": { "name": "tier", "children": [ { "origin.passthrough": { "@from": "Customer.tier" } } ] } } + ] } } +] } } diff --git a/fixtures/conformance/error-origin-function-free-sql/providers.json b/fixtures/conformance/error-origin-function-free-sql/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-origin-function-free-sql/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json b/fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json new file mode 100644 index 0000000000..c522a29b12 --- /dev/null +++ b/fixtures/conformance/error-projection-grain-not-object-array/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[1]['object.projection']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json b/fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json new file mode 100644 index 0000000000..d95ea15aa2 --- /dev/null +++ b/fixtures/conformance/error-projection-grain-not-object-array/input/meta.views.json @@ -0,0 +1,12 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "tags", "isArray": true } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } }, + { "object.projection": { "name": "G", "@grain": "tags", "children": [ + { "source.rdb": { "@kind": "view", "@view": "g" } }, + { "field.long": { "name": "customerId", "extends": "Customer.id" } } + ] } } +] } } diff --git a/fixtures/conformance/error-projection-grain-not-object-array/providers.json b/fixtures/conformance/error-projection-grain-not-object-array/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-projection-grain-not-object-array/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/error-projection-union-shape/expected-errors.json b/fixtures/conformance/error-projection-union-shape/expected-errors.json new file mode 100644 index 0000000000..8f752c3ae4 --- /dev/null +++ b/fixtures/conformance/error-projection-union-shape/expected-errors.json @@ -0,0 +1,15 @@ +{ + "errors": [ + { + "code": "ERR_BAD_ATTR_VALUE", + "source": { + "format": "json", + "files": [ + "meta.views.json" + ], + "jsonPath": "$['metadata.root'].children[3]['object.projection']" + } + } + ], + "warnings": [] +} diff --git a/fixtures/conformance/error-projection-union-shape/input/meta.views.json b/fixtures/conformance/error-projection-union-shape/input/meta.views.json new file mode 100644 index 0000000000..89ec9dada7 --- /dev/null +++ b/fixtures/conformance/error-projection-union-shape/input/meta.views.json @@ -0,0 +1,18 @@ +{ "metadata.root": { "package": "acme::views", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "zip" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } + ] } }, + { "object.projection": { "name": "A", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Customer.id" } }, + { "field.string": { "name": "label", "extends": "Customer.zip" } } + ] } }, + { "object.projection": { "name": "B", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Customer.id" } } + ] } }, + { "object.projection": { "name": "U", "extends": "A", "@union": ["B"], "children": [ + { "source.rdb": { "@kind": "view", "@view": "u" } } + ] } } +] } } diff --git a/fixtures/conformance/error-projection-union-shape/providers.json b/fixtures/conformance/error-projection-union-shape/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/error-projection-union-shape/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/expected.json b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json new file mode 100644 index 0000000000..335403cc0e --- /dev/null +++ b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json @@ -0,0 +1,498 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { + "object.value": { + "name": "Contact", + "children": [ + { + "field.string": { + "name": "kind" + } + }, + { + "field.int": { + "name": "rank" + } + } + ] + } + }, + { + "object.entity": { + "name": "Customer", + "children": [ + { + "source.rdb": { + "@table": "customers" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.string": { + "name": "zip", + "@dbColumnType": "varchar(10)" + } + }, + { + "field.string": { + "name": "code", + "@dbColumnType": "character(3)" + } + }, + { + "field.string": { + "name": "note", + "@dbColumnType": "varchar" + } + }, + { + "field.object": { + "name": "contacts", + "isArray": true, + "@objectRef": "acme::views::Contact", + "@storage": "jsonb" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "field.string": { + "name": "tier", + "children": [ + { + "origin.function": { + "@args": [ + "id", + "zip" + ], + "@function": "tier_of", + "@schema": "app" + } + } + ] + } + } + ] + } + }, + { + "object.entity": { + "name": "Order", + "children": [ + { + "source.rdb": { + "@table": "orders" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.enum": { + "name": "status", + "@intValueMap": { + "Open": 0, + "Shipped": 1 + }, + "@values": [ + "Open", + "Shipped" + ] + } + }, + { + "field.int": { + "name": "cumulativeStatus" + } + }, + { + "field.timestamp": { + "name": "updatedAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "customerId", + "@fields": [ + "customerId" + ], + "@references": "acme::views::Customer" + } + } + ] + } + }, + { + "object.entity": { + "name": "OrderEvent", + "children": [ + { + "source.rdb": { + "@table": "order_events" + } + }, + { + "field.long": { + "name": "id" + } + }, + { + "field.long": { + "name": "orderId" + } + }, + { + "field.long": { + "name": "customerId" + } + }, + { + "field.timestamp": { + "name": "createdAt" + } + }, + { + "identity.primary": { + "name": "id", + "@fields": [ + "id" + ] + } + }, + { + "identity.reference": { + "name": "orderId", + "@fields": [ + "orderId" + ], + "@references": "acme::views::Order" + } + } + ] + } + }, + { + "object.projection": { + "name": "OrderRow", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_order_row" + } + }, + { + "field.long": { + "name": "id", + "extends": "acme::views::Order.id" + } + }, + { + "field.int": { + "name": "outcome", + "children": [ + { + "origin.computed": { + "@expr": { + "case": [ + { + "when": { + "op": "eq", + "left": { + "field": "cumulativeStatus" + }, + "right": { + "value": 0 + } + }, + "then": { + "cast": { + "field": "status" + }, + "as": "int" + } + } + ], + "else": { + "field": "cumulativeStatus" + } + } + } + } + ] + } + }, + { + "field.string": { + "name": "zip5", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "splitPart", + "args": [ + { + "field": "customerId.zip" + }, + { + "value": "-" + }, + { + "value": 1 + } + ] + } + } + } + ] + } + }, + { + "field.string": { + "name": "nothing", + "children": [ + { + "origin.computed": { + "@expr": { + "cast": { + "value": null + }, + "as": "string", + "dbColumnType": "varchar" + } + } + } + ] + } + }, + { + "field.string": { + "name": "tier", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Customer.tier", + "@via": "acme::views::Order.customerId" + } + } + ] + } + }, + { + "field.timestamp": { + "name": "lastEvent", + "children": [ + { + "origin.aggregate": { + "@agg": "max", + "@of": "acme::views::OrderEvent.createdAt", + "@via": "acme::views::Order.orderEvents" + } + } + ] + } + }, + { + "field.timestamp": { + "name": "touched", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "greatest", + "args": [ + { + "field": "updatedAt" + }, + { + "field": "lastEvent" + } + ] + } + } + } + ] + } + }, + { + "field.long": { + "name": "eventOfCustomer", + "children": [ + { + "origin.first": { + "@filter": { + "customerId": { + "eq": { + "field": "customerId.id" + } + } + }, + "@of": "acme::views::OrderEvent.id", + "@orderBy": [ + "createdAt" + ], + "@via": "acme::views::Order.orderEvents" + } + } + ] + } + }, + { + "identity.primary": { + "name": "id", + "extends": "acme::views::Order.id" + } + } + ] + } + }, + { + "object.projection": { + "name": "CustomerContact", + "@grain": "contacts", + "@grainOrdinal": "position", + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_customer_contact" + } + }, + { + "field.long": { + "name": "customerId", + "extends": "acme::views::Customer.id" + } + }, + { + "field.int": { + "name": "position" + } + }, + { + "field.string": { + "name": "kind", + "children": [ + { + "origin.passthrough": { + "@from": "acme::views::Contact.kind" + } + } + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "CustomerBranch", + "abstract": true, + "children": [ + { + "field.long": { + "name": "personId", + "extends": "acme::views::Customer.id" + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "fn": "lower", + "args": [ + { + "field": "zip" + } + ] + } + } + } + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "OrderBranch", + "abstract": true, + "children": [ + { + "field.long": { + "name": "personId", + "extends": "acme::views::Order.customerId" + } + }, + { + "field.string": { + "name": "label", + "children": [ + { + "origin.computed": { + "@expr": { + "cast": { + "field": "id" + }, + "as": "string" + } + } + } + ] + } + } + ] + } + }, + { + "object.projection": { + "name": "People", + "extends": "acme::views::CustomerBranch", + "@union": [ + "OrderBranch" + ], + "@unionAll": true, + "children": [ + { + "source.rdb": { + "@kind": "view", + "@view": "v_people" + } + } + ] + } + } + ] + } +} diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json new file mode 100644 index 0000000000..68401ce7fd --- /dev/null +++ b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json @@ -0,0 +1,78 @@ +{ + "metadata.root": { + "package": "acme::views", + "children": [ + { "object.value": { "name": "Contact", "children": [ + { "field.string": { "name": "kind" } }, + { "field.int": { "name": "rank" } } + ] } }, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "zip", "@dbColumnType": "varchar(10)" } }, + { "field.string": { "name": "code", "@dbColumnType": "character(3)" } }, + { "field.string": { "name": "note", "@dbColumnType": "varchar" } }, + { "field.object": { "name": "contacts", "@objectRef": "Contact", "isArray": true, "@storage": "jsonb" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "field.string": { "name": "tier", "children": [ + { "origin.function": { "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"] } } + ] } } + ] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "customerId" } }, + { "field.enum": { "name": "status", "@values": ["Open", "Shipped"], "@intValueMap": { "Open": 0, "Shipped": 1 } } }, + { "field.int": { "name": "cumulativeStatus" } }, + { "field.timestamp": { "name": "updatedAt" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "customerId", "@fields": "customerId", "@references": "Customer" } } + ] } }, + { "object.entity": { "name": "OrderEvent", "children": [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { "name": "id" } }, + { "field.long": { "name": "orderId" } }, + { "field.long": { "name": "customerId" } }, + { "field.timestamp": { "name": "createdAt" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } + ] } }, + { "object.projection": { "name": "OrderRow", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_order_row" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.int": { "name": "outcome", "children": [ { "origin.computed": { "@expr": { + "case": [ { "when": { "op": "eq", "left": { "field": "cumulativeStatus" }, "right": { "value": 0 } }, + "then": { "cast": { "field": "status" }, "as": "int" } } ], + "else": { "field": "cumulativeStatus" } } } } ] } }, + { "field.string": { "name": "zip5", "children": [ { "origin.computed": { "@expr": { + "fn": "splitPart", "args": [ { "field": "customerId.zip" }, { "value": "-" }, { "value": 1 } ] } } } ] } }, + { "field.string": { "name": "nothing", "children": [ { "origin.computed": { "@expr": { + "cast": { "value": null }, "as": "string", "dbColumnType": "varchar" } } } ] } }, + { "field.string": { "name": "tier", "children": [ { "origin.passthrough": { "@from": "Customer.tier", "@via": "Order.customerId" } } ] } }, + { "field.timestamp": { "name": "lastEvent", "children": [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + { "field.timestamp": { "name": "touched", "children": [ { "origin.computed": { "@expr": { + "fn": "greatest", "args": [ { "field": "updatedAt" }, { "field": "lastEvent" } ] } } } ] } }, + { "field.long": { "name": "eventOfCustomer", "children": [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", + "@orderBy": ["createdAt"], "@filter": { "customerId": { "eq": { "field": "customerId.id" } } } } } ] } }, + { "identity.primary": { "name": "id", "extends": "Order.id" } } + ] } }, + { "object.projection": { "name": "CustomerContact", "@grain": "contacts", "@grainOrdinal": "position", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_customer_contact" } }, + { "field.long": { "name": "customerId", "extends": "Customer.id" } }, + { "field.int": { "name": "position" } }, + { "field.string": { "name": "kind", "children": [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } } + ] } }, + { "object.projection": { "name": "CustomerBranch", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Customer.id" } }, + { "field.string": { "name": "label", "children": [ { "origin.computed": { "@expr": { "fn": "lower", "args": [ { "field": "zip" } ] } } } ] } } + ] } }, + { "object.projection": { "name": "OrderBranch", "abstract": true, "children": [ + { "field.long": { "name": "personId", "extends": "Order.customerId" } }, + { "field.string": { "name": "label", "children": [ { "origin.computed": { "@expr": { "cast": { "field": "id" }, "as": "string" } } } ] } } + ] } }, + { "object.projection": { "name": "People", "extends": "CustomerBranch", "@union": ["OrderBranch"], "@unionAll": true, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_people" } } + ] } } + ] + } +} diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/providers.json b/fixtures/conformance/projection-view-vocabulary-rc21/providers.json new file mode 100644 index 0000000000..f9bb435a37 --- /dev/null +++ b/fixtures/conformance/projection-view-vocabulary-rc21/providers.json @@ -0,0 +1 @@ +["metaobjects-core-types","metaobjects-db"] diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 394e925caa..02e5586e0f 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -19,7 +19,7 @@ children and the cardinality of that subtype. Documentation attributes | `attr.boolean` | A boolean-valued metadata attribute. Coerces to and validates as true/false. | [types/attr.md#attrboolean](types/attr.md#attrboolean) | | `attr.class` | A class-/type-reference-valued metadata attribute. String-backed (a fully-qualified class or type name) used by binding facets. | [types/attr.md#attrclass](types/attr.md#attrclass) | | `attr.double` | A double-precision floating-point-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrdouble](types/attr.md#attrdouble) | -| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | +| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | | `attr.filter` | A filter-expression-valued metadata attribute. Object-shaped value that desugars a preset filter to the canonical { field: { op: value } } form (scalar→eq, array→in, null→isNull; or/and recurse). | [types/attr.md#attrfilter](types/attr.md#attrfilter) | | `attr.int` | A 32-bit-integer-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrint](types/attr.md#attrint) | | `attr.intMap` | An object-shaped attribute whose values are all integers (e.g. field.enum's @intValueMap: {memberSymbol: int}). Generic shape check only; a consumer field type layers its own semantic rules (key-set membership, uniqueness) in its own content-rule validation. | [types/attr.md#attrintmap](types/attr.md#attrintmap) | @@ -65,6 +65,7 @@ children and the cardinality of that subtype. Documentation attributes | `origin.base` | Abstract base origin — the shared root subtype for field-level provenance. A field carrying any origin.* is derived ⇒ read-only wherever it lives. The base carries no attrs of its own; concrete subtypes add their provenance attrs. Not authored directly: a `origin.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/origin.md#originbase](types/origin.md#originbase) | | `origin.computed` | A row-level value computed from the base entity's own fields via a structured expression tree (@expr). No related rows, no @via. Read-only; the expression's inferred type must equal the field's declared subType. | [types/origin.md#origincomputed](types/origin.md#origincomputed) | | `origin.first` | The single related row selected by @orderBy along @via, projecting its @of column (argmax then project). Latest = @orderBy desc. Read-only; empty related set (after @filter) → null, so the field must not be @required. | [types/origin.md#originfirst](types/origin.md#originfirst) | +| `origin.function` | A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. | [types/origin.md#originfunction](types/origin.md#originfunction) | | `origin.passthrough` | A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). | [types/origin.md#originpassthrough](types/origin.md#originpassthrough) | | `relationship.aggregation` | A shared/independent containment — the parent groups the target but does not own its lifecycle (default @onDelete set-null). | [types/relationship.md#relationshipaggregation](types/relationship.md#relationshipaggregation) | | `relationship.association` | A plain reference to another entity — no ownership; the target has an independent lifecycle (default @onDelete restrict). | [types/relationship.md#relationshipassociation](types/relationship.md#relationshipassociation) | diff --git a/fixtures/metamodel-docs/expected/providers.md b/fixtures/metamodel-docs/expected/providers.md index c7f1133abe..bc53f39ae8 100644 --- a/fixtures/metamodel-docs/expected/providers.md +++ b/fixtures/metamodel-docs/expected/providers.md @@ -13,7 +13,7 @@ provider owns. This is the ownership lens over the same vocabulary Core metaobjects metamodel types and subtypes. -**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` +**Owns (registers):** `attr.base`, `attr.boolean`, `attr.class`, `attr.double`, `attr.expression`, `attr.filter`, `attr.int`, `attr.intMap`, `attr.long`, `attr.properties`, `attr.string`, `field.base`, `field.boolean`, `field.currency`, `field.date`, `field.decimal`, `field.double`, `field.duration`, `field.enum`, `field.float`, `field.inet`, `field.int`, `field.long`, `field.map`, `field.object`, `field.string`, `field.time`, `field.timestamp`, `field.uri`, `field.uuid`, `identity.primary`, `identity.reference`, `identity.secondary`, `layout.base`, `layout.dataGrid`, `object.base`, `object.entity`, `object.projection`, `object.report`, `object.value`, `origin.aggregate`, `origin.base`, `origin.computed`, `origin.first`, `origin.function`, `origin.passthrough`, `relationship.aggregation`, `relationship.association`, `relationship.base`, `relationship.composition`, `source.base`, `source.rdb`, `template.base`, `template.output`, `template.prompt`, `template.toolcall`, `validator.array`, `validator.atLeastOne`, `validator.base`, `validator.comparison`, `validator.length`, `validator.numeric`, `validator.presentIff`, `validator.regex`, `validator.required`, `validator.requiredWhen`, `view.base`, `view.checkbox`, `view.currency`, `view.date`, `view.dropdown`, `view.hidden`, `view.hotlink`, `view.image`, `view.month`, `view.number`, `view.password`, `view.radio`, `view.text`, `view.textarea`, `view.web` **Contributes attributes:** @@ -31,11 +31,12 @@ Core metaobjects metamodel types and subtypes. - `identity.secondary`: `@fields` - `object.base`: `@object`, `@objectAdapter` - `object.entity`: `@collectionName`, `@dbSetName`, `@discriminator`, `@discriminatorValue` -- `object.projection`: `@collectionName`, `@dbSetName`, `@filter` +- `object.projection`: `@collectionName`, `@dbSetName`, `@filter`, `@grain`, `@grainOrdinal`, `@union`, `@unionAll` - `object.report`: `@collectionName`, `@dbSetName`, `@dimensions`, `@filter`, `@from`, `@measures`, `@segment`, `@spine` - `origin.aggregate`: `@agg`, `@distinct`, `@filter`, `@of`, `@orderBy`, `@segment`, `@via` - `origin.computed`: `@expr` - `origin.first`: `@filter`, `@of`, `@orderBy`, `@segment`, `@via` +- `origin.function`: `@args`, `@function`, `@schema` - `origin.passthrough`: `@convert`, `@from`, `@via` - `relationship.aggregation`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` - `relationship.association`: `@cardinality`, `@objectRef`, `@onDelete`, `@onUpdate`, `@sourceRefField`, `@symmetric`, `@through` diff --git a/fixtures/metamodel-docs/expected/types/attr.md b/fixtures/metamodel-docs/expected/types/attr.md index a0e95d1a83..285bf6c6df 100644 --- a/fixtures/metamodel-docs/expected/types/attr.md +++ b/fixtures/metamodel-docs/expected/types/attr.md @@ -68,7 +68,7 @@ _No structural children._ ### attr.expression -A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159. +A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. **Owning provider:** metaobjects-core-types diff --git a/fixtures/metamodel-docs/expected/types/field.md b/fixtures/metamodel-docs/expected/types/field.md index 76131fbca2..a668829d11 100644 --- a/fixtures/metamodel-docs/expected/types/field.md +++ b/fixtures/metamodel-docs/expected/types/field.md @@ -22,7 +22,7 @@ Abstract base field — the shared root subtype that concrete field subtypes spe | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -55,7 +55,7 @@ True/false flag. Binds to the native boolean type; DB column is BOOLEAN. | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -91,7 +91,7 @@ Stores money as integer minor units (cents). Binds to long; the client formats v | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@currency` | string | no | `USD` | | metaobjects-core-types | ISO 4217 currency code for a currency-subtype field. Storage is integer minor units; defaults to 'USD' when omitted. | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -125,7 +125,7 @@ Calendar date (no time-of-day). Binds to the native date/temporal type; DB colum | `@autoSet` | string | no | | `onCreate`, `onUpdate` | metaobjects-db | Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -160,7 +160,7 @@ Precision-exact decimal (use @precision/@scale). Native TS binding is string (lo | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -195,7 +195,7 @@ Double-precision (64-bit) IEEE-754 floating point. Binds to the native double/nu | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -228,7 +228,7 @@ A fixed-length span of time: days, hours, minutes and seconds (ADR-0036/0037 — | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -266,7 +266,7 @@ String-backed enumeration constrained to a closed set of member symbols (@values | `@constraintName` | string | no | | | metaobjects-db | The database name of the CHECK constraint this enum's member list generates. Absent:
    __chk. Lets a model adopt a database whose CHECKs were named by hand. RDB-physical — contributed by the db provider. | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | | `@dbCheck` | boolean | no | | | metaobjects-db | false: this enum's member list generates no database CHECK (meta migrate and a generated EF model leave it out); the generated app-level validation still holds every write to the members. Absent: true. For a column whose legacy rows hold values outside the members, which a CHECK would refuse on their next UPDATE even NOT VALID. Refused with @constraintName (ERR_CONSTRAINT_NAME_WITHOUT_CHECK). RDB-physical — contributed by the db provider. | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@enumAlias` | properties | no | | | metaobjects-prompt | Map of alternate/off-vocabulary tokens to canonical enum members; feeds the FR-010 tolerant extract alias-fold. | | `@enumDoc` | properties | no | | | metaobjects-prompt | Map of enum member to a human-readable description; shown per-member in the FR-010 'guide'-style prompt fragment. | @@ -305,7 +305,7 @@ Single-precision floating point. Binds to the native double/number type (TS has | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -338,7 +338,7 @@ An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native t | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -372,7 +372,7 @@ An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native t | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -405,7 +405,7 @@ An IP-address string (IPv4 or IPv6) (ADR-0036/0037 — a concept with a native t | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -440,7 +440,7 @@ An open-keyed map (Record / dict[str,V]) stored in a single jsonb colu | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -477,7 +477,7 @@ A nested structured value (set @objectRef to the target object). Storage is gove | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -513,7 +513,7 @@ Variable-length text. Binds to the native string type; DB column is VARCHAR/TEXT | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -547,7 +547,7 @@ Time-of-day (no calendar date). Binds to the native date/temporal type; DB colum | `@autoSet` | string | no | | `onCreate`, `onUpdate` | metaobjects-db | Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -581,7 +581,7 @@ Date + time-of-day instant (optionally with timezone). Binds to the native date/ | `@autoSet` | string | no | | `onCreate`, `onUpdate` | metaobjects-db | Auto-set semantics for timestamp-like fields: 'onCreate' stamps on insert, 'onUpdate' stamps on every write. | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -615,7 +615,7 @@ A URI/URL string (ADR-0036/0037 — a concept with a native type + behavior, so | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | @@ -649,7 +649,7 @@ Logical UUID identity scalar. A bare scalar (no required attrs, no loader value- | --- | --- | --- | --- | --- | --- | --- | | `@column` | string | no | | | metaobjects-db | Physical column name for this field on an rdb source. Defaults to the field name under the project's naming.columns rule (the "naming" setting in .metaobjects/config.json). | | `@db.indexed` | boolean | no | | | metaobjects-db | When true, suppress the @filterable-without-index Loader warning (the field is indexed by other means). | -| `@dbColumnType` | string | no | | `uuid`, `jsonb` | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid \| jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | +| `@dbColumnType` | string | no | | | metaobjects-db | Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2. | | `@default` | any | no | | | metaobjects-core-types | Default value applied to the column when no value is supplied. Its type follows the field's own subtype (string / boolean / number / ...). Converted at consumption time via MetaField.defaultValue(). | | `@example` | string | no | | | metaobjects-prompt | FR-010: an example value for this field, shown in the generated output-format prompt fragment. | | `@filterable` | boolean | no | | | metaobjects-ui | When true, the field is exposed in generated CRUD filter allowlists (Project D filter layer). | diff --git a/fixtures/metamodel-docs/expected/types/object.md b/fixtures/metamodel-docs/expected/types/object.md index 5d55c34f09..72f141b682 100644 --- a/fixtures/metamodel-docs/expected/types/object.md +++ b/fixtures/metamodel-docs/expected/types/object.md @@ -84,8 +84,12 @@ A derived read-only representation of entities. Its fields are extends-bound / o | `@collectionName` | string | no | | | metaobjects-core-types | The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own). | | `@dbSetName` | string | no | | | metaobjects-core-types | DEPRECATED (rc.19): use @collectionName, which this is an alias of for one release; code generation warns where it reads it, and refuses an object declaring both. Every port loads and type-checks it. | | `@filter` | filter | no | | | metaobjects-core-types | Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19). | +| `@grain` | string | no | | | metaobjects-core-types | rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection. | +| `@grainOrdinal` | string | no | | | metaobjects-core-types | rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array. | | `@object` | string | no | | | metaobjects-core-types | The native class an object binds to (ADR-0001), in place of its default runtime class: on the JVM, a fully-qualified class name. Cross-port vocabulary only Java implements so far; every port loads and type-checks it, and the others do not act on it yet. | | `@objectAdapter` | string | no | | | metaobjects-core-types | JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it. | +| `@union` | string[] | no | | | metaobjects-core-types | rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless. | +| `@unionAll` | boolean | no | | | metaobjects-core-types | rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default. | **Allowed children** diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index beb7072f98..61f58f1cca 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -92,6 +92,26 @@ The single related row selected by @orderBy along @via, projecting its @of colum _No structural children._ +### origin.function + +A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. + +**Owning provider:** metaobjects-core-types + +**When to use:** A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql. + +**Attributes** + +| Attribute | Type | Required | Default | Allowed values | Provider | Description | +| --- | --- | --- | --- | --- | --- | --- | +| `@args` | string[] | no | | | metaobjects-core-types | The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments. | +| `@function` | string | yes | | | metaobjects-core-types | The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase. | +| `@schema` | string | no | | | metaobjects-core-types | The schema the function lives in, a plain identifier. Absent: public. | + +**Allowed children** + +_No structural children._ + ### origin.passthrough A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). diff --git a/fixtures/registry-conformance/coverage-report.json b/fixtures/registry-conformance/coverage-report.json index 565641e5c8..f6be4755f1 100644 --- a/fixtures/registry-conformance/coverage-report.json +++ b/fixtures/registry-conformance/coverage-report.json @@ -1,6 +1,6 @@ { - "registeredSubTypeCount": 79, - "exercisedSubTypeCount": 71, + "registeredSubTypeCount": 80, + "exercisedSubTypeCount": 72, "untestedSubTypes": [ "attr.boolean", "attr.class", diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts new file mode 100644 index 0000000000..49a85022c4 --- /dev/null +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -0,0 +1,208 @@ +// rc.21 part B — the view vocabulary, golden SQL per construct on Postgres and SQLite, and the +// SQLite spellings run on a real SQLite (the live Postgres run is integration-tests' +// view-vocabulary-rc21-pg.test.ts). + +import { describe, test, expect } from "bun:test"; +import { Database } from "bun:sqlite"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildProjectionViews } from "../../src/projection/build-projection-views.js"; +import { RC21B_ENTITIES, withoutFunction } from "./rc21b-view-vocabulary.fixture.js"; + +const orderRow = (fields: unknown[]) => ({ "object.projection": { name: "OrderRow", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_order_row" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + ...fields, + { "identity.primary": { name: "id", extends: "Order.id" } } ] } }); +const computed = (name: string, subType: string, expr: unknown) => + ({ [`field.${subType}`]: { name, children: [ { "origin.computed": { "@expr": expr } } ] } }); + +async function views(dialect: "postgres" | "sqlite", ...projections: unknown[]): Promise> { + // The origin.function field must be reached (an entity has no read source for it), so only the + // tests that read it keep it. + const reachesFunction = JSON.stringify(projections).includes("loyaltyTier"); + const entities = reachesFunction ? RC21B_ENTITIES : withoutFunction(RC21B_ENTITIES); + const doc = { "metadata.root": { package: "acme", children: [...entities, ...projections] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(errors).toEqual([]); + return new Map(buildProjectionViews(root, { dialect }).map((v) => [v.name, v.sql])); +} +const one = async (dialect: "postgres" | "sqlite", projection: unknown) => [...(await views(dialect, projection)).values()][0]!; + +describe("U12 cast and U2 a typed NULL of an unbounded varchar", () => { + const p = orderRow([ + computed("ref", "string", { fn: "coalesce", args: [{ field: "externalRef" }, { cast: { field: "id" }, as: "string" }] }), + computed("nothing", "string", { cast: { value: null }, as: "string", dbColumnType: "varchar" }), + computed("code", "string", { cast: { field: "externalRef" }, as: "string", dbColumnType: "character(3)" }), + ]); + test("postgres", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("COALESCE(o.external_ref, CAST(o.id AS TEXT)) AS ref"); + expect(sql).toContain("CAST(NULL AS VARCHAR) AS nothing"); + expect(sql).toContain("CAST(o.external_ref AS CHARACTER(3)) AS code"); + }); + test("sqlite", async () => { + const sql = await one("sqlite", p); + expect(sql).toContain("COALESCE(o.external_ref, CAST(o.id AS TEXT)) AS ref"); + expect(sql).toContain("CAST(NULL AS TEXT) AS nothing"); + }); +}); + +describe("U8 an int-stored enum and an int in one case, through the cast", () => { + test("postgres", async () => { + const sql = await one("postgres", orderRow([computed("outcome", "int", { + case: [{ when: { op: "eq", left: { field: "cumulativeStatus" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } }], + else: { field: "cumulativeStatus" } })])); + expect(sql).toContain("(CASE WHEN o.cumulative_status = 0 THEN CAST(o.status AS INTEGER) ELSE o.cumulative_status END) AS outcome"); + }); +}); + +describe("U11 string functions, and U3 a path the view does not output", () => { + const p = orderRow([ + computed("zip5", "string", { fn: "splitPart", args: [{ field: "customerId.zip" }, { value: "-" }, { value: 1 }] }), + computed("fullName", "string", { fn: "btrim", args: [{ fn: "concatWs", args: [{ value: " " }, { field: "customerId.firstName" }, { field: "customerId.lastName" }] }] }), + computed("tag", "string", { fn: "concat", args: [{ fn: "lower", args: [{ field: "externalRef" }] }, { value: "#" }, { field: "id" }] }), + computed("mid", "string", { fn: "replace", args: [{ fn: "substring", args: [{ field: "externalRef" }, { value: 2 }, { value: 3 }] }, { value: "X" }, { value: "" }] }), + computed("ends", "string", { fn: "concat", args: [{ fn: "left", args: [{ field: "externalRef" }, { value: 1 }] }, { fn: "right", args: [{ field: "externalRef" }, { value: 1 }] }] }), + computed("len", "int", { fn: "length", args: [{ fn: "upper", args: [{ field: "externalRef" }] }] }), + computed("noRef", "string", { fn: "nullif", args: [{ field: "externalRef" }, { value: "NONE" }] }), + ]); + test("postgres: each function by its own name, and the path joined, not output", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("SPLIT_PART(c.zip, '-', 1) AS zip5"); + expect(sql).toContain("BTRIM(CONCAT_WS(' ', c.first_name, c.last_name)) AS full_name"); + expect(sql).toContain("CONCAT(LOWER(o.external_ref), '#', o.id) AS tag"); + expect(sql).toContain("REPLACE(SUBSTR(o.external_ref, 2, 3), 'X', '') AS mid"); + expect(sql).toContain("CONCAT(LEFT(o.external_ref, 1), RIGHT(o.external_ref, 1)) AS ends"); + expect(sql).toContain("CHAR_LENGTH(UPPER(o.external_ref)) AS len"); + expect(sql).toContain("NULLIF(o.external_ref, 'NONE') AS no_ref"); + expect(sql).toContain("LEFT OUTER JOIN public.customers c ON c.id = o.customer_id"); + expect(sql).not.toMatch(/AS zip\b/); + }); + test("sqlite: the same values from SQLite's own functions", async () => { + const sql = await one("sqlite", p); + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, cumulative_status INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("INSERT INTO customers (id, first_name, last_name, zip) VALUES (10, 'Ada', 'Lovelace', '02139-4307'), (11, NULL, 'Hopper', '12345')"); + db.run("INSERT INTO orders (id, customer_id, external_ref) VALUES (1, 10, 'AXXBCD'), (2, 11, 'NONE'), (3, NULL, NULL)"); + db.run(`CREATE VIEW v AS ${sql}`); + expect(db.query("SELECT id, zip5, full_name, tag, mid, ends, len, no_ref FROM v ORDER BY id").all()).toEqual([ + { id: 1, zip5: "02139", full_name: "Ada Lovelace", tag: "axxbcd#1", mid: "B", ends: "AD", len: 6, no_ref: "AXXBCD" }, + { id: 2, zip5: "12345", full_name: "Hopper", tag: "none#2", mid: "ONE", ends: "NE", len: 4, no_ref: null }, + { id: 3, zip5: null, full_name: "", tag: "#3", mid: null, ends: "", len: null, no_ref: null }, + ]); + }); + test("sqlite: splitPart beyond the first part is refused, not mis-spelled", async () => { + await expect(one("sqlite", orderRow([computed("p2", "string", { fn: "splitPart", args: [{ field: "externalRef" }, { value: "-" }, { value: 2 }] })]))) + .rejects.toThrow(/splitPart on SQLite is lowered only for the first part/); + }); +}); + +describe("U13 greatest / least over an aggregate, and U4 a correlated path operand", () => { + const p = orderRow([ + { "field.timestamp": { name: "lastEvent", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + computed("touched", "timestamp", { fn: "greatest", args: [{ field: "updatedAt" }, { field: "lastEvent" }] }), + computed("earliest", "timestamp", { fn: "least", args: [{ field: "updatedAt" }, { field: "lastEvent" }] }), + { "field.long": { name: "eventByCustomer", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], + "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, + ]); + test("postgres", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("GREATEST(o.updated_at, MAX(o0.created_at)) AS touched"); + expect(sql).toContain("LEAST(o.updated_at, MAX(o0.created_at)) AS earliest"); + expect(sql).toContain("WHERE o1.order_id = o.id AND o1.customer_id = c.id ORDER BY"); + expect(sql).toContain("GROUP BY o.id, c.id"); + }); + test("sqlite: greatest / least skip NULLs as Postgres does", async () => { + const sql = await one("sqlite", p); + expect(sql).toContain("MAX(COALESCE(o.updated_at, MAX(o0.created_at)), COALESCE(MAX(o0.created_at), o.updated_at)) AS touched"); + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, cumulative_status INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("CREATE TABLE order_events (id INTEGER PRIMARY KEY, order_id INTEGER, customer_id INTEGER, cumulative_status INTEGER, created_at TEXT)"); + db.run("INSERT INTO customers (id) VALUES (10)"); + db.run("INSERT INTO orders (id, customer_id, updated_at) VALUES (1, 10, '2026-01-05'), (2, 10, NULL), (3, 10, '2026-01-01')"); + db.run("INSERT INTO order_events (id, order_id, customer_id, created_at) VALUES (100, 1, 10, '2026-02-01'), (101, 2, 9, '2026-03-01'), (102, 2, 10, '2026-03-02')"); + db.run(`CREATE VIEW v AS ${sql}`); + expect(db.query("SELECT id, touched, earliest, event_by_customer FROM v ORDER BY id").all()).toEqual([ + { id: 1, touched: "2026-02-01", earliest: "2026-01-05", event_by_customer: 100 }, + { id: 2, touched: "2026-03-02", earliest: "2026-03-02", event_by_customer: 102 }, + { id: 3, touched: "2026-01-01", earliest: "2026-01-01", event_by_customer: null }, + ]); + }); +}); + +describe("U10 origin.function", () => { + test("postgres: the declared call, its arguments read on the reached row", async () => { + const sql = await one("postgres", orderRow([ + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])); + expect(sql).toContain("app.loyalty_tier(c.id, c.zip) AS tier"); + }); + test("a SQLite view refuses it: SQLite has no stored functions", async () => { + const doc = { "metadata.root": { package: "acme", children: [...RC21B_ENTITIES, orderRow([ + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }])] } }; + const { root } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + expect(() => buildProjectionViews(root, { dialect: "sqlite" })).toThrow(/calls a database function, which SQLite does not have/); + }); +}); + +describe("U14 @grain — one row per array element", () => { + const p = { "object.projection": { name: "CustomerContact", "@grain": "contacts", "@grainOrdinal": "position", children: [ + { "source.rdb": { "@kind": "view", "@table": "v_customer_contact" } }, + { "field.long": { name: "customerId", extends: "Customer.id" } }, + { "field.int": { name: "position" } }, + { "field.string": { name: "kind", children: [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } }, + { "field.int": { name: "rank", children: [ { "origin.passthrough": { "@from": "Contact.rank" } } ] } } ] } }; + test("postgres", async () => { + const sql = await one("postgres", p); + expect(sql).toContain("FROM public.customers c CROSS JOIN LATERAL jsonb_array_elements(c.contacts) WITH ORDINALITY AS mo_el(value, ordinality)"); + expect(sql).toContain("CAST(mo_el.ordinality AS INTEGER) AS position"); + expect(sql).toContain("(mo_el.value ->> 'kind') AS kind"); + expect(sql).toContain("CAST((mo_el.value ->> 'rank') AS INTEGER) AS rank"); + }); + test("sqlite", async () => { + const sql = await one("sqlite", p); + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); + db.run(`INSERT INTO customers (id, contacts) VALUES (1, '[{"kind":"email","rank":1},{"kind":"phone","rank":2}]'), (2, '[]'), (3, NULL)`); + db.run(`CREATE VIEW v AS ${sql}`); + expect(db.query("SELECT customer_id, position, kind, rank FROM v ORDER BY customer_id, position").all()).toEqual([ + { customer_id: 1, position: 1, kind: "email", rank: 1 }, + { customer_id: 1, position: 2, kind: "phone", rank: 2 }, + ]); + }); +}); + +describe("U15 @union", () => { + const branches = [ + { "object.projection": { name: "PersonBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Customer.id" } }, + computed("label", "string", { fn: "lower", args: [{ field: "lastName" }] }) ] } }, + { "object.projection": { name: "AddressBranch", abstract: true, children: [ + { "field.long": { name: "personId", extends: "Address.customerId" } }, + computed("label", "string", { fn: "lower", args: [{ field: "street" }] }) ] } }, + ]; + const union = (all: boolean) => ({ "object.projection": { name: "People", extends: "PersonBranch", "@union": ["AddressBranch"], + ...(all ? { "@unionAll": true } : {}), children: [ { "source.rdb": { "@kind": "view", "@table": "v_people" } } ] } }); + test("postgres: UNION by default, UNION ALL on request, and each branch reads its own base", async () => { + const sql = (await views("postgres", ...branches, union(false))).get("v_people")!; + expect(sql).toBe([ + " SELECT\n c.id AS person_id,\n LOWER(c.last_name) AS label\n FROM public.customers c", + " UNION", + " SELECT\n a.customer_id AS person_id,\n LOWER(a.street) AS label\n FROM public.addresses a", + ].join("\n")); + expect((await views("postgres", ...branches, union(true))).get("v_people")).toContain("\n UNION ALL\n"); + }); + test("sqlite: removes duplicates, or keeps them", async () => { + for (const all of [false, true]) { + const sql = (await views("sqlite", ...branches, union(all))).get("v_people")!; + const db = new Database(":memory:"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE addresses (id INTEGER PRIMARY KEY, customer_id INTEGER, street TEXT)"); + db.run("INSERT INTO customers (id, last_name) VALUES (1, 'Main')"); + db.run("INSERT INTO addresses (id, customer_id, street) VALUES (9, 1, 'main'), (10, 2, 'Elm')"); + db.run(`CREATE VIEW v AS ${sql}`); + expect((db.query("SELECT count(*) AS n FROM v").get() as { n: number }).n).toBe(all ? 3 : 2); + } + }); +}); diff --git a/server/typescript/packages/metadata/test/db-definition-completeness.test.ts b/server/typescript/packages/metadata/test/db-definition-completeness.test.ts index 4b26ddd99a..20c10f2feb 100644 --- a/server/typescript/packages/metadata/test/db-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/db-definition-completeness.test.ts @@ -78,9 +78,10 @@ describe("db provider (data-driven) — attr placement", () => { } }); - test("@dbColumnType description renders the legal-value list (uuid | jsonb — timestamp_with_tz retired)", () => { + test("@dbColumnType description renders the legal-value list (uuid, jsonb and the rc.21 text spellings — timestamp_with_tz retired)", () => { const attr = registry.find(TYPE_FIELD, "string")!.attributes.find((a) => a.name === "dbColumnType")!; - expect(attr.description).toContain("uuid | jsonb"); + expect(attr.description).toContain("uuid (a native Postgres uuid column"); + expect(attr.description).toContain("character(n)"); }); test("@localTime is on field.timestamp ONLY (ADR-0036 Wave 2)", () => { diff --git a/server/typescript/packages/metadata/test/object-definition-completeness.test.ts b/server/typescript/packages/metadata/test/object-definition-completeness.test.ts index 86d35c3dbe..d337babc54 100644 --- a/server/typescript/packages/metadata/test/object-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/object-definition-completeness.test.ts @@ -73,6 +73,11 @@ const NORMALIZE: Record = { // to a view-level WHERE); mirrors origin.aggregate's filter-attr placement. const PROJECTION_FILTER: Record = { filter: { valueType: "filter", required: false }, + // rc.21 part B: @union / @unionAll (U15), @grain / @grainOrdinal (U14). + union: { valueType: "string", required: false }, + unionAll: { valueType: "boolean", required: false }, + grain: { valueType: "string", required: false }, + grainOrdinal: { valueType: "string", required: false }, }; // FR-044 — object.report carries its six declaration attrs (five, plus the optional @spine). The array-valued ones diff --git a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts index 67883f6501..ba011a3212 100644 --- a/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts +++ b/server/typescript/packages/metadata/test/origin-definition-completeness.test.ts @@ -69,6 +69,12 @@ const EXPECTED: Record> = { // rc.19 origin-segment. segment: { valueType: "string", required: false }, }, + // rc.21 part B (U10). + function: { + function: { valueType: "string", required: true }, + schema: { valueType: "string", required: false }, + args: { valueType: "string", required: false }, + }, }; describe("origin provider externalization — completeness", () => { diff --git a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts new file mode 100644 index 0000000000..10822f607c --- /dev/null +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -0,0 +1,203 @@ +// rc.21 part B — the view vocabulary at load: each construct is accepted where it means +// something and refused, with its code, where it does not. + +import { describe, expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "../src/index.js"; + +const ENTITIES = [ + { "object.value": { name: "Contact", children: [ + { "field.string": { name: "kind" } }, { "field.int": { name: "rank" } }, + { "field.object": { name: "nested", "@objectRef": "Note" } } ] } }, + { "object.value": { name: "Note", children: [ { "field.string": { name: "text" } } ] } }, + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "zip" } }, + { "field.string": { name: "tags", isArray: true } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, + { "field.object": { name: "primary", "@objectRef": "Contact" } }, + { "identity.primary": { name: "id", "@fields": "id" } } ] } }, + { "object.entity": { name: "Order", children: [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "customerId" } }, + { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, + { "field.enum": { name: "kind", "@values": ["A", "B"] } }, + { "field.int": { name: "n" } }, + { "field.string": { name: "ref" } }, + { "field.timestamp": { name: "at" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { name: "OrderEvent", children: [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "orderId" } }, + { "field.long": { name: "customerId" } }, + { "field.timestamp": { name: "createdAt" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, +]; + +const orderView = (fields: unknown[], extra: Record = {}) => ({ "object.projection": { name: "V", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@table": "v" } }, + { "field.long": { name: "id", extends: "Order.id" } }, + ...fields, + { "identity.primary": { name: "id", extends: "Order.id" } } ] } }); +const computed = (name: string, subType: string, expr: unknown) => + ({ [`field.${subType}`]: { name, children: [ { "origin.computed": { "@expr": expr } } ] } }); + +async function load(...extra: unknown[]): Promise<{ code: string; message: string }[]> { + const doc = { "metadata.root": { package: "acme", children: [...ENTITIES, ...extra] } }; + const { errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + return errors.map((e) => ({ code: String((e as { code?: string }).code), message: e.message })); +} +const ok = async (...extra: unknown[]) => expect(await load(...extra)).toEqual([]); +const refused = async (code: string, pattern: RegExp, ...extra: unknown[]) => { + const errors = await load(...extra); + expect(errors.some((e) => e.code === code && pattern.test(e.message))).toBe(true); +}; + +describe("U2 — @dbColumnType text spellings", () => { + const entity = (attr: Record) => ({ "object.entity": { name: "R", children: [ + { "source.rdb": { "@table": "r" } }, { "field.long": { name: "id" } }, + { "field.string": { name: "c", ...attr } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } }); + test("text, varchar, character varying and the sized spellings load on a field.string", async () => { + for (const t of ["text", "varchar", "character varying", "varchar(12)", "character varying(12)", "character(3)"]) { + await ok(entity({ "@dbColumnType": t })); + } + }); + test("a misspelling, a zero length, another subtype and a @maxLength over n are refused", async () => { + await refused("ERR_BAD_ATTR_VALUE", /'VARCHAR' is not legal/, entity({ "@dbColumnType": "VARCHAR" })); + await refused("ERR_BAD_ATTR_VALUE", /'character\(0\)' is not legal/, entity({ "@dbColumnType": "character(0)" })); + await refused("ERR_BAD_ATTR_VALUE", /@maxLength: 10 over '@dbColumnType: character\(3\)'/, entity({ "@dbColumnType": "character(3)", "@maxLength": 10 })); + await refused("ERR_BAD_ATTR_VALUE", /'varchar' is not legal on field.int/, { "object.entity": { name: "R", children: [ + { "source.rdb": { "@table": "r" } }, { "field.long": { name: "id" } }, + { "field.int": { name: "c", "@dbColumnType": "varchar" } }, { "identity.primary": { name: "id", "@fields": "id" } } ] } }); + }); +}); + +describe("U11, U12, U13 — the function set and the cast", () => { + test("typed functions and casts load", async () => { + await ok(orderView([ + computed("a", "string", { fn: "splitPart", args: [{ field: "ref" }, { value: "-" }, { value: 1 }] }), + computed("b", "string", { fn: "concatWs", args: [{ value: " " }, { field: "ref" }, { field: "n" }] }), + computed("c", "int", { fn: "length", args: [{ fn: "btrim", args: [{ field: "ref" }] }] }), + computed("d", "string", { cast: { field: "id" }, as: "string" }), + computed("e", "int", { cast: { field: "status" }, as: "int" }), + computed("f", "string", { cast: { value: null }, as: "string", dbColumnType: "varchar(4)" }), + computed("g", "timestamp", { fn: "greatest", args: [{ field: "at" }, { value: null }] }), + computed("h", "string", { fn: "nullif", args: [{ field: "ref" }, { value: "" }] }), + ])); + }); + test("an unknown function, a bad arity and a wrong argument type are refused", async () => { + await refused("ERR_UNKNOWN_EXPR_NODE", /unknown expression fn 'initcap'/, orderView([computed("a", "string", { fn: "initcap", args: [{ field: "ref" }] })])); + await refused("ERR_UNKNOWN_EXPR_NODE", /'splitPart' requires at least 3 args/, orderView([computed("a", "string", { fn: "splitPart", args: [{ field: "ref" }] })])); + await refused("ERR_INVALID_ORIGIN", /'lower' argument 1 must be a string, got int/, orderView([computed("a", "string", { fn: "lower", args: [{ field: "n" }] })])); + await refused("ERR_INVALID_ORIGIN", /'greatest' arguments have differing types/, orderView([computed("a", "int", { fn: "greatest", args: [{ field: "n" }, { field: "id" }] })])); + await refused("ERR_INVALID_ORIGIN", /'greatest' needs ordered arguments/, orderView([computed("a", "boolean", { fn: "greatest", args: [{ value: true }, { value: false }] })])); + }); + test("a cast the source cannot hold is refused (U8: an enum casts to int only when int-stored)", async () => { + await refused("ERR_INVALID_ORIGIN", /only an enum stored as an integer/, orderView([computed("a", "int", { cast: { field: "kind" }, as: "int" })])); + await refused("ERR_INVALID_ORIGIN", /cast it to int/, orderView([computed("a", "string", { cast: { field: "status" }, as: "string" })])); + await refused("ERR_UNKNOWN_EXPR_NODE", /requires 'as': one of/, orderView([computed("a", "string", { cast: { field: "id" }, as: "enum" })])); + await refused("ERR_UNKNOWN_EXPR_NODE", /'dbColumnType' is a text spelling/, orderView([computed("a", "string", { cast: { field: "id" }, as: "string", dbColumnType: "uuid" })])); + await refused("ERR_INVALID_ORIGIN", /a timestamp cannot be cast to int/, orderView([computed("a", "int", { cast: { field: "at" }, as: "int" })])); + }); + test("an int-stored enum and an int still differ in a case without the cast", async () => { + await refused("ERR_INVALID_ORIGIN", /'case' results have differing types/, orderView([computed("a", "int", { + case: [{ when: { op: "eq", left: { field: "n" }, right: { value: 0 } }, then: { field: "status" } }], else: { field: "n" } })])); + await ok(orderView([computed("a", "int", { + case: [{ when: { op: "eq", left: { field: "n" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } }], else: { field: "n" } })])); + }); + test("an expression over an aggregate loads, and is not filterable", async () => { + const last = { "field.timestamp": { name: "last", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }; + await ok(orderView([last, computed("touched", "timestamp", { fn: "greatest", args: [{ field: "at" }, { field: "last" }] })])); + await refused("ERR_BAD_ATTR_FILTER", /touched/, orderView([last, computed("touched", "timestamp", { fn: "greatest", args: [{ field: "at" }, { field: "last" }] })], + { "@filter": { touched: { isNull: false } } })); + }); + test("a CHECK @condition refuses the view-only nodes", async () => { + await refused("ERR_BAD_ATTR_VALUE", /uses lower, which a CHECK condition cannot hold/, { "object.entity": { name: "W", children: [ + { "source.rdb": { "@table": "w" } }, { "field.long": { name: "id" } }, { "field.string": { name: "a" } }, { "field.string": { name: "b" } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "validator.requiredWhen": { name: "r", "@field": "b", "@condition": { op: "eq", left: { fn: "lower", args: [{ field: "a" }] }, right: { value: "x" } } } } ] } }); + }); +}); + +describe("U3, U4 — paths in an expression and in a correlated operand", () => { + test("a path ref and a path operand load on a projection", async () => { + await ok(orderView([ + computed("zip5", "string", { fn: "left", args: [{ field: "customerId.zip" }, { value: 5 }] }), + { "field.long": { name: "ev", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], + "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, + ])); + }); + test("a path that does not resolve is refused", async () => { + await refused("ERR_INVALID_ORIGIN", /does not resolve/, orderView([computed("z", "string", { field: "customerId.nope" })])); + await refused("ERR_BAD_ATTR_FILTER", /base-row path "customerId.nope"/, orderView([ + { "field.long": { name: "ev", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], + "@filter": { customerId: { eq: { field: "customerId.nope" } } } } } ] } }])); + }); +}); + +describe("U10 — origin.function", () => { + const withFn = (fn: Record) => ({ "object.entity": { name: "Customer2", children: [ + { "source.rdb": { "@table": "customers2" } }, { "field.long": { name: "id" } }, { "field.string": { name: "zip" } }, + { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true } }, + { "identity.primary": { name: "id", "@fields": "id" } }, + { "field.string": { name: "tier", children: [ { "origin.function": fn } ] } } ] } }); + const reach = { "object.projection": { name: "P2", children: [ + { "source.rdb": { "@kind": "view", "@table": "p2" } }, + { "field.long": { name: "id", extends: "Customer2.id" } }, + { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer2.tier" } } ] } }, + { "identity.primary": { name: "id", extends: "Customer2.id" } } ] } }; + test("a declared call on an entity, reached by a projection, loads", async () => { + await ok(withFn({ "@function": "tier_of", "@schema": "app", "@args": ["id", "zip"] }), reach); + }); + test("free SQL, an unknown argument and a non-scalar argument are refused", async () => { + await refused("ERR_INVALID_ORIGIN", /is not a plain identifier/, withFn({ "@function": "tier_of(1); drop table x", "@args": [] }), reach); + await refused("ERR_INVALID_ORIGIN", /@args names "nope"/, withFn({ "@function": "tier_of", "@args": ["nope"] }), reach); + await refused("ERR_INVALID_ORIGIN", /a field.object array; a function argument is a scalar/, withFn({ "@function": "tier_of", "@args": ["contacts"] }), reach); + }); + test("an unreached function field on an entity with no read source is refused", async () => { + await refused("ERR_DERIVED_FIELD_NO_READ_SOURCE", /tier/, withFn({ "@function": "tier_of", "@args": ["id"] })); + }); +}); + +describe("U14 — @grain", () => { + const grain = (extra: Record, fields: unknown[]) => ({ "object.projection": { name: "G", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@table": "g" } }, + { "field.long": { name: "customerId", extends: "Customer.id" } }, + ...fields ] } }); + const kind = { "field.string": { name: "kind", children: [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } }; + test("one row per element loads, with a position", async () => { + await ok(grain({ "@grain": "contacts", "@grainOrdinal": "pos" }, [{ "field.int": { name: "pos" } }, kind])); + }); + test("a scalar array, a single object, a nested member, an aggregate and a bad ordinal are refused", async () => { + await refused("ERR_BAD_ATTR_VALUE", /@grain "tags" must name a field.object array/, grain({ "@grain": "tags" }, [kind])); + await refused("ERR_BAD_ATTR_VALUE", /@grain "primary" must name a field.object array/, grain({ "@grain": "primary" }, [kind])); + await refused("ERR_INVALID_ORIGIN", /is not a scalar member of the @grain element/, grain({ "@grain": "contacts" }, + [{ "field.object": { name: "nested", "@objectRef": "Note", children: [ { "origin.passthrough": { "@from": "Contact.nested" } } ] } }])); + await refused("ERR_BAD_ATTR_VALUE", /a @grain view has one row per element/, grain({ "@grain": "contacts" }, [kind, + { "field.long": { name: "n", children: [ { "origin.aggregate": { "@agg": "count", "@of": "Order.id", "@via": "Customer.orders" } } ] } }])); + await refused("ERR_BAD_ATTR_VALUE", /@grainOrdinal "pos" must name a field.int or field.long/, grain({ "@grain": "contacts", "@grainOrdinal": "pos" }, + [{ "field.string": { name: "pos" } }, kind])); + }); +}); + +describe("U15 — @union", () => { + const branch = (name: string, entity: string, idField: string, label: Record) => ({ "object.projection": { name, abstract: true, children: [ + { "field.long": { name: "personId", extends: `${entity}.${idField}` } }, label ] } }); + const label = (from: string) => ({ "field.string": { name: "label", children: [ { "origin.computed": { "@expr": { fn: "lower", args: [{ field: from }] } } } ] } }); + const union = (extra: Record) => ({ "object.projection": { name: "U", extends: "A", ...extra, children: [ + { "source.rdb": { "@kind": "view", "@table": "u" } } ] } }); + test("projections of one shape union", async () => { + await ok(branch("A", "Customer", "id", label("zip")), branch("B", "Order", "customerId", label("ref")), union({ "@union": ["B"], "@unionAll": true })); + }); + test("a different shape, a non-projection, itself and @unionAll alone are refused", async () => { + await refused("ERR_BAD_ATTR_VALUE", /member "B" has a different shape/, branch("A", "Customer", "id", label("zip")), + branch("B", "Order", "customerId", { "field.int": { name: "label", children: [ { "origin.computed": { "@expr": { field: "n" } } } ] } }), union({ "@union": ["B"] })); + await refused("ERR_BAD_ATTR_VALUE", /names "Order", which is not an object.projection/, branch("A", "Customer", "id", label("zip")), union({ "@union": ["Order"] })); + await refused("ERR_BAD_ATTR_VALUE", /names the projection itself/, branch("A", "Customer", "id", label("zip")), union({ "@union": ["U"] })); + await refused("ERR_BAD_ATTR_VALUE", /@unionAll needs @union/, branch("A", "Customer", "id", label("zip")), union({ "@unionAll": true })); + }); +}); diff --git a/server/typescript/packages/metadata/test/template-payload-target-210.test.ts b/server/typescript/packages/metadata/test/template-payload-target-210.test.ts index d0a8737a2d..195a410524 100644 --- a/server/typescript/packages/metadata/test/template-payload-target-210.test.ts +++ b/server/typescript/packages/metadata/test/template-payload-target-210.test.ts @@ -80,6 +80,8 @@ describe("#210 — assembly origins are illegal on an object.value host", () => aggregate: { "origin.aggregate": { "@agg": "count", "@of": "t::ai::Author.id", "@via": "t::ai::Author.books" } }, computed: { "origin.computed": { "@expr": { op: "isNotNull", arg: { field: "name" } } } }, first: { "origin.first": { "@of": "t::ai::Author.name", "@via": "t::ai::Author.posts", "@orderBy": ["name:desc"] } }, + // rc.21 part B (U10). + function: { "origin.function": { "@function": "f" } }, }; test("the originNode table covers exactly the ASSEMBLY_ORIGIN_SUBTYPES set (drift guard)", () => { diff --git a/server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts b/server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts new file mode 100644 index 0000000000..98a5f1ffc9 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/db-column-type-text-spellings.test.ts @@ -0,0 +1,37 @@ +// rc.21 part B (U2): the text @dbColumnType spellings are the column types `meta migrate` creates; +// an unbounded varchar and text compare as one type, a character(n) as its own. + +import { expect, test } from "bun:test"; +import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata"; +import { buildExpectedSchema } from "../src/expected-schema.js"; +import { pgType } from "../src/emit/postgres.js"; +import { sqliteType } from "../src/emit/sqlite.js"; +import { sqlTypeEquals, isWidening } from "../src/sql-type.js"; +import { pgTypeToSqlType } from "../src/introspect/postgres.js"; +import { sqliteTypeToSqlType } from "../src/introspect/sqlite-shared.js"; + +test("each spelling is its column type on Postgres and SQLite", async () => { + const spellings = ["text", "varchar", "character varying", "varchar(12)", "character varying(12)", "character(3)"]; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [ + { "object.entity": { name: "R", children: [ + { "source.rdb": { "@table": "r" } }, { "field.long": { name: "id" } }, + ...spellings.map((t, i) => ({ "field.string": { name: `c${i}`, "@dbColumnType": t } })), + { "identity.primary": { name: "id", "@fields": "id" } } ] } } ] } }))]); + expect(errors).toEqual([]); + const cols = buildExpectedSchema(root, { dialect: "postgres" }).tables[0]!.columns.filter((c) => c.name !== "id"); + expect(cols.map((c) => pgType(c.sqlType))).toEqual(["TEXT", "VARCHAR", "VARCHAR", "VARCHAR(12)", "VARCHAR(12)", "CHARACTER(3)"]); + expect(cols.map((c) => sqliteType(c.sqlType, undefined))).toEqual(["TEXT", "VARCHAR", "VARCHAR", "VARCHAR(12)", "VARCHAR(12)", "CHARACTER(3)"]); +}); + +test("introspection reads them back to the same types", () => { + expect(sqlTypeEquals(pgTypeToSqlType("character varying", null), { kind: "text", variant: "varchar" })).toBe(true); + expect(pgTypeToSqlType("character", 3)).toEqual({ kind: "text", maxLength: 3, variant: "char" }); + expect(sqliteTypeToSqlType("CHARACTER(3)")).toEqual({ kind: "text", maxLength: 3, variant: "char" }); + expect(sqliteTypeToSqlType("VARCHAR")).toEqual({ kind: "text", variant: "varchar" }); +}); + +test("an unbounded varchar equals text; character(n) equals neither, and is no widening", () => { + expect(sqlTypeEquals({ kind: "text" }, { kind: "text", variant: "varchar" })).toBe(true); + expect(sqlTypeEquals({ kind: "text", maxLength: 3 }, { kind: "text", maxLength: 3, variant: "char" })).toBe(false); + expect(isWidening({ kind: "text", maxLength: 3, variant: "char" }, { kind: "text" })).toBe(false); +}); diff --git a/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts b/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts index 7f31fe22f5..52611d9994 100644 --- a/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts +++ b/server/typescript/packages/migrate-ts/test/integration/postgres-introspect.test.ts @@ -333,8 +333,9 @@ describe("pgTypeToSqlType normalization", () => { expect(pgTypeToSqlType("varchar(120)")).toEqual({ kind: "text", maxLength: 120 }); }); - test("character varying (unbounded) → text", () => { - expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text" }); + // rc.21 part B (U2): unbounded varchar keeps its spelling, and compares equal to text. + test("character varying (unbounded) → text, spelled varchar", () => { + expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text", variant: "varchar" }); }); test("text → text", () => { diff --git a/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts b/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts index 324be0a7f7..e72ddf8446 100644 --- a/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts +++ b/server/typescript/packages/migrate-ts/test/unit/introspect-postgres-helpers.test.ts @@ -24,8 +24,8 @@ describe("pgTypeToSqlType", () => { expect(pgTypeToSqlType("varchar(64)")).toEqual({ kind: "text", maxLength: 64 }); // bare varchar + separate maxLength column expect(pgTypeToSqlType("character varying", 100)).toEqual({ kind: "text", maxLength: 100 }); - // bare varchar with no length info → plain text - expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text" }); + // bare varchar with no length info → text, spelled varchar (rc.21 U2; it equals text in the diff) + expect(pgTypeToSqlType("character varying")).toEqual({ kind: "text", variant: "varchar" }); expect(pgTypeToSqlType("text")).toEqual({ kind: "text" }); }); diff --git a/site-reference/index.html b/site-reference/index.html index 699a85a986..f3cec925e9 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -82,7 +82,7 @@ - + @@ -311,6 +311,11 @@ + + + + + diff --git a/site-reference/providers.html b/site-reference/providers.html index 40c8e0ec96..673e8f1f11 100644 --- a/site-reference/providers.html +++ b/site-reference/providers.html @@ -51,7 +51,7 @@ INDEX.md lists by type.

    metaobjects-core-types

    Core metaobjects metamodel types and subtypes.

    -

    Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.report, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.checkbox, view.currency, view.date, view.dropdown, view.hidden, view.hotlink, view.image, view.month, view.number, view.password, view.radio, view.text, view.textarea, view.web

    +

    Owns (registers): attr.base, attr.boolean, attr.class, attr.double, attr.expression, attr.filter, attr.int, attr.intMap, attr.long, attr.properties, attr.string, field.base, field.boolean, field.currency, field.date, field.decimal, field.double, field.duration, field.enum, field.float, field.inet, field.int, field.long, field.map, field.object, field.string, field.time, field.timestamp, field.uri, field.uuid, identity.primary, identity.reference, identity.secondary, layout.base, layout.dataGrid, object.base, object.entity, object.projection, object.report, object.value, origin.aggregate, origin.base, origin.computed, origin.first, origin.function, origin.passthrough, relationship.aggregation, relationship.association, relationship.base, relationship.composition, source.base, source.rdb, template.base, template.output, template.prompt, template.toolcall, validator.array, validator.atLeastOne, validator.base, validator.comparison, validator.length, validator.numeric, validator.presentIff, validator.regex, validator.required, validator.requiredWhen, view.base, view.checkbox, view.currency, view.date, view.dropdown, view.hidden, view.hotlink, view.image, view.month, view.number, view.password, view.radio, view.text, view.textarea, view.web

    Contributes attributes:

    • field.base: @default, @mutability, @required, @unique
    • @@ -68,11 +68,12 @@

      metaobjects-core-types

    • identity.secondary: @fields
    • object.base: @object, @objectAdapter
    • object.entity: @collectionName, @dbSetName, @discriminator, @discriminatorValue
    • -
    • object.projection: @collectionName, @dbSetName, @filter
    • +
    • object.projection: @collectionName, @dbSetName, @filter, @grain, @grainOrdinal, @union, @unionAll
    • object.report: @collectionName, @dbSetName, @dimensions, @filter, @from, @measures, @segment, @spine
    • origin.aggregate: @agg, @distinct, @filter, @of, @orderBy, @segment, @via
    • origin.computed: @expr
    • origin.first: @filter, @of, @orderBy, @segment, @via
    • +
    • origin.function: @args, @function, @schema
    • origin.passthrough: @convert, @from, @via
    • relationship.aggregation: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
    • relationship.association: @cardinality, @objectRef, @onDelete, @onUpdate, @sourceRefField, @symmetric, @through
    • diff --git a/site-reference/types/attr.html b/site-reference/types/attr.html index 3d426b2da0..2495d90ecf 100644 --- a/site-reference/types/attr.html +++ b/site-reference/types/attr.html @@ -79,7 +79,7 @@

      attr.double

      Allowed children

      No structural children.

      attr.expression

      -

      A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159.

      +

      A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.

      Owning provider: metaobjects-core-types

      Attributes

      No subtype-specific attributes.

      diff --git a/site-reference/types/field.html b/site-reference/types/field.html index be2a31c07d..a71e246d27 100644 --- a/site-reference/types/field.html +++ b/site-reference/types/field.html @@ -89,9 +89,9 @@

      field.base

    - + - + @@ -239,9 +239,9 @@

    field.boolean

    - + - + @@ -399,9 +399,9 @@

    field.currency

    - + - + @@ -558,9 +558,9 @@

    field.date

    - + - + @@ -709,9 +709,9 @@

    field.decimal

    - + - + @@ -877,9 +877,9 @@

    field.double

    - + - + @@ -1027,9 +1027,9 @@

    field.duration

    - + - + @@ -1205,9 +1205,9 @@

    field.enum

    - + - + @@ -1426,9 +1426,9 @@

    field.float

    - + - + @@ -1576,9 +1576,9 @@

    field.inet

    - + - + @@ -1735,9 +1735,9 @@

    field.int

    - + - + @@ -1885,9 +1885,9 @@

    field.long

    - + - + @@ -2036,9 +2036,9 @@

    field.map

    - + - + @@ -2205,9 +2205,9 @@

    field.object

    - + - + @@ -2382,9 +2382,9 @@

    field.string

    - + - + @@ -2558,9 +2558,9 @@

    field.time

    - + - + @@ -2717,9 +2717,9 @@

    field.timestamp

    - + - + @@ -2876,9 +2876,9 @@

    field.uri

    - + - + @@ -3035,9 +3035,9 @@

    field.uuid

    - + - + diff --git a/site-reference/types/object.html b/site-reference/types/object.html index 72724966ad..f430768794 100644 --- a/site-reference/types/object.html +++ b/site-reference/types/object.html @@ -227,6 +227,24 @@

    object.projection

    + + + + + + + + + + + + + + + + + + @@ -244,6 +262,24 @@

    object.projection

    + + + + + + + + + + + + + + + + + +
    attr.expressionA structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. Arithmetic is #159.A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. types/attr.md#attrexpression
    types/origin.md#originfirst
    origin.functionA value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.types/origin.md#originfunction
    origin.passthrough A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via). types/origin.md#originpassthroughstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultstring no uuid, jsonb metaobjects-dbPhysical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, both on field.string (uuid = native Postgres uuid column over a string-typed field; jsonb = genuinely-open JSON column). The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2.
    @defaultOptional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19).
    @grainstringnometaobjects-core-typesrc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection.
    @grainOrdinalstringnometaobjects-core-typesrc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array.
    @object string nometaobjects-core-types JVM-only (ADR-0005): the fully-qualified name of an ObjectAdapter that takes over value access for this object's instances. Every port loads and type-checks it; only Java and Kotlin act on it.
    @unionstring[]nometaobjects-core-typesrc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless.
    @unionAllbooleannometaobjects-core-typesrc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default.

    Allowed children

      diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index f6f9ce06c3..cbc8087926 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -236,6 +236,53 @@

      origin.first

    Allowed children

    No structural children.

    +

    origin.function

    +

    A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.

    +

    Owning provider: metaobjects-core-types

    +

    When to use: A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.

    +

    Attributes

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    AttributeTypeRequiredDefaultAllowed valuesProviderDescription
    @argsstring[]nometaobjects-core-typesThe fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments.
    @functionstringyesmetaobjects-core-typesThe function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase.
    @schemastringnometaobjects-core-typesThe schema the function lives in, a plain identifier. Absent: public.
    +

    Allowed children

    +

    No structural children.

    origin.passthrough

    A cross-entity field reference: this projection field passes a source entity's value straight through (@from), optionally reached via a relationship path (@via).

    Owning provider: metaobjects-core-types

    From f90e0d51b1f9b714d7cf7680803faba5402d5c49 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 18:20:54 -0500 Subject: [PATCH 191/267] feat(csharp): the rc.21 view vocabulary at load, and the text @dbColumnType column types The C# loader takes the TypeScript rules, message for message: the cast node and the closed function set (with the int-stored-enum cast rule), a scalar aggregate read by a computed (not filterable), a path in an expression or a correlated operand on a projection, origin.function, @union shapes and @grain projections, the text @dbColumnType spellings (with the @maxLength-over-n refusal), and the CHECK subset of a @condition. The registry gains origin.function and the four projection attrs, and the manifest drops @dbColumnType's allowedValues. The EF context maps a text spelling to its column type. Co-Authored-By: Claude Opus 5.5 --- .../GeneratorHooksTests.cs | 22 ++ .../Generators/DbContextGenerator.cs | 11 + .../ViewVocabularyRc21LoaderTests.cs | 165 +++++++++++ .../Core/Attr/ExpressionGrammar.cs | 172 +++++++++-- .../Core/Object/ObjectConstants.cs | 5 + .../MetaObjects/Core/Object/ObjectSchema.cs | 16 ++ server/csharp/MetaObjects/CoreTypes.cs | 2 +- .../MetaObjects/Loader/MetaDataLoader.cs | 2 + .../MetaObjects/Loader/ValidationPasses.cs | 269 +++++++++++++++--- .../MetaObjects/Persistence/Db/DbConstants.cs | 42 ++- .../MetaObjects/Persistence/Db/DbSchema.cs | 16 +- .../Persistence/Origin/OriginConstants.cs | 11 + .../Persistence/Origin/OriginSchema.cs | 12 + 13 files changed, 677 insertions(+), 68 deletions(-) create mode 100644 server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs index c1a6961aa8..1d5e4e19c5 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorHooksTests.cs @@ -435,6 +435,28 @@ public void Override_of_DbColumnTypeConfig_changes_only_its_lines() Assert.Contains(".Property(x => x.Uid).HasColumnType(\"uuid\")", line); } + // rc.21 part B (U2): a text @dbColumnType spelling is the EF column type, as meta migrate creates it. + [Fact] + public void A_text_db_column_type_spelling_is_the_column_type() + { + var root = Load(""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Region", "children": [ + { "source.rdb": { "@table": "regions" } }, + { "field.long": { "name": "id" } }, + { "field.string": { "name": "code", "@dbColumnType": "character(3)" } }, + { "field.string": { "name": "label", "@dbColumnType": "varchar" } }, + { "field.string": { "name": "note", "@dbColumnType": "varchar(20)" } }, + { "field.string": { "name": "body", "@dbColumnType": "text" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } } ] } } + """); + var db = Db(new DbContextGenerator(), root); + Assert.Contains(".Property(x => x.Code).HasColumnType(\"character(3)\");", db); + Assert.Contains(".Property(x => x.Label).HasColumnType(\"character varying\");", db); + Assert.Contains(".Property(x => x.Note).HasColumnType(\"character varying(20)\");", db); + Assert.Contains(".Property(x => x.Body).HasColumnType(\"text\");", db); + } + private sealed class NoReferenceDb : DbContextGenerator { protected override IEnumerable ReferenceConfig(MetaObject entity, MetaReferenceIdentity reference, GenContext ctx) => []; diff --git a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs index bd114b8d6b..4049b04883 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/DbContextGenerator.cs @@ -676,10 +676,21 @@ protected virtual string DbSetLine(MetaObject entity, GenContext ctx) lhs + ".HasColumnType(\"uuid\").HasConversion(v => global::System.Guid.Parse(v!), g => g.ToString(\"D\"));", DbConstants.DB_COLUMN_TYPE_JSONB => lhs + ".HasColumnType(\"jsonb\");", + // rc.21 part B (U2): a text spelling is the column type, as `meta migrate` creates it. + { } spelling when DbConstants.ParseDbColumnType(spelling) is { Kind: "text" or "varchar" or "char" } p => + lhs + $".HasColumnType(\"{TextColumnType(p)}\");", _ => null, }; } + /// rc.21 part B (U2): the Postgres column type a text @dbColumnType spelling names. + private static string TextColumnType(DbConstants.ParsedDbColumnType p) => p.Kind switch + { + "char" => $"character({p.Length})", + "varchar" => p.Length is { } n ? $"character varying({n})" : "character varying", + _ => "text", + }; + // FR-017 — EF TPH single-table inheritance config for a discriminator base. The // discriminator property is the base's @discriminator field (PascalCased); the // HasValue clauses bind each concrete subtype to its @discriminatorValue. When the diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs new file mode 100644 index 0000000000..db409453ba --- /dev/null +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -0,0 +1,165 @@ +// rc.21 part B — the view vocabulary at load, the C# twin of the TypeScript +// rc21b-view-vocabulary.test.ts: each construct accepted where it means something and refused, +// with its code and message, where it does not. The shared conformance fixtures +// (projection-view-vocabulary-rc21 and its error-* siblings) pin the cross-port envelopes. + +using System.Text.Json; +using MetaObjects.Loader; +using MetaObjects.Source; +using Xunit; + +namespace MetaObjects.Conformance.Tests; + +public class ViewVocabularyRc21LoaderTests +{ + private const string Entities = """ + { "object.value": { "name": "Contact", "children": [ { "field.string": { "name": "kind" } } ] } }, + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, + { "field.long": { "name": "id" } }, { "field.string": { "name": "zip" } }, + { "field.object": { "name": "contacts", "@objectRef": "Contact", "isArray": true, "@storage": "jsonb" } }, + { "identity.primary": { "name": "id", "@fields": "id" } } ] } }, + { "object.entity": { "name": "Order", "children": [ + { "source.rdb": { "@table": "orders" } }, + { "field.long": { "name": "id" } }, { "field.long": { "name": "customerId" } }, + { "field.enum": { "name": "status", "@values": ["Open", "Shipped"], "@intValueMap": { "Open": 0, "Shipped": 1 } } }, + { "field.enum": { "name": "kind", "@values": ["A", "B"] } }, + { "field.int": { "name": "n" } }, { "field.string": { "name": "ref" } }, { "field.timestamp": { "name": "at" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "customerId", "@fields": "customerId", "@references": "Customer" } } ] } }, + { "object.entity": { "name": "OrderEvent", "children": [ + { "source.rdb": { "@table": "order_events" } }, + { "field.long": { "name": "id" } }, { "field.long": { "name": "orderId" } }, { "field.long": { "name": "customerId" } }, + { "field.timestamp": { "name": "createdAt" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } ] } } + """; + + private static string View(params string[] fields) => $$""" + { "object.projection": { "name": "V", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + {{string.Join(",\n", fields)}} ] } } + """; + + private static string Computed(string name, string subType, object expr) => + $$"""{ "field.{{subType}}": { "name": "{{name}}", "children": [ { "origin.computed": { "@expr": {{JsonSerializer.Serialize(expr)}} } } ] } }"""; + + private static IReadOnlyList Load(params string[] extra) + { + var json = $$"""{ "metadata.root": { "package": "acme", "children": [ {{Entities}}{{string.Concat(extra.Select(e => ",\n" + e))}} ] } }"""; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + return new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "v.json")]).Errors; + } + + private static void Refused(string code, string fragment, params string[] extra) + { + var errors = Load(extra); + Assert.True(errors.Any(e => e.Code.ToString() == code && e.Message.Contains(fragment, StringComparison.Ordinal)), + $"expected {code} containing '{fragment}', got: {string.Join(" | ", errors.Select(e => $"{e.Code}: {e.Message}"))}"); + } + + private static object F(string name) => new Dictionary { ["field"] = name }; + private static object V(object? value) => new Dictionary { ["value"] = value }; + private static object Fn(string fn, params object[] args) => new Dictionary { ["fn"] = fn, ["args"] = args }; + private static object Cast(object arg, string to) => new Dictionary { ["cast"] = arg, ["as"] = to }; + + [Fact] + public void Typed_functions_casts_paths_and_aggregate_reads_load() + { + var errors = Load(View( + Computed("a", "string", Fn("splitPart", F("customerId.zip"), V("-"), V(1))), + Computed("b", "string", Fn("concatWs", V(" "), F("ref"), F("n"))), + Computed("c", "int", Fn("length", Fn("btrim", F("ref")))), + Computed("d", "string", Cast(F("id"), "string")), + Computed("e", "int", Cast(F("status"), "int")), + """{ "field.timestamp": { "name": "last", "children": [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }""", + Computed("touched", "timestamp", Fn("greatest", F("at"), F("last"))), + """{ "field.long": { "name": "ev", "children": [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { "customerId": { "eq": { "field": "customerId.id" } } } } } ] } }""")); + Assert.Empty(errors); + } + + [Fact] + public void An_unknown_function_a_bad_arity_and_a_wrong_argument_are_refused() + { + Refused("ERR_UNKNOWN_EXPR_NODE", "unknown expression fn 'initcap'", View(Computed("a", "string", Fn("initcap", F("ref"))))); + Refused("ERR_UNKNOWN_EXPR_NODE", "'splitPart' requires at least 3 args", View(Computed("a", "string", Fn("splitPart", F("ref"))))); + Refused("ERR_INVALID_ORIGIN", "'lower' argument 1 must be a string, got int", View(Computed("a", "string", Fn("lower", F("n"))))); + Refused("ERR_INVALID_ORIGIN", "'greatest' arguments have differing types", View(Computed("a", "int", Fn("greatest", F("n"), F("id"))))); + } + + [Fact] + public void A_cast_the_source_cannot_hold_is_refused() + { + Refused("ERR_INVALID_ORIGIN", "only an enum stored as an integer", View(Computed("a", "int", Cast(F("kind"), "int")))); + Refused("ERR_INVALID_ORIGIN", "a timestamp cannot be cast to int", View(Computed("a", "int", Cast(F("at"), "int")))); + Refused("ERR_UNKNOWN_EXPR_NODE", "requires 'as': one of", View(Computed("a", "string", Cast(F("id"), "enum")))); + } + + [Fact] + public void An_expression_over_an_aggregate_is_not_filterable() + { + Refused("ERR_BAD_ATTR_FILTER", "touched", $$""" + { "object.projection": { "name": "V", "@filter": { "touched": { "isNull": false } }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.timestamp": { "name": "last", "children": [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, + {{Computed("touched", "timestamp", Fn("greatest", F("at"), F("last")))}} ] } } + """); + } + + [Fact] + public void A_path_operand_that_does_not_resolve_is_refused() + { + Refused("ERR_BAD_ATTR_FILTER", "base-row path \"customerId.nope\"", View( + """{ "field.long": { "name": "ev", "children": [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { "customerId": { "eq": { "field": "customerId.nope" } } } } } ] } }""")); + } + + [Fact] + public void A_check_condition_refuses_the_view_only_nodes() + { + Refused("ERR_BAD_ATTR_VALUE", "uses lower, which a CHECK condition cannot hold", """ + { "object.entity": { "name": "W", "children": [ + { "source.rdb": { "@table": "w" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "a" } }, { "field.string": { "name": "b" } }, + { "identity.primary": { "name": "id", "@fields": "id" } }, + { "validator.requiredWhen": { "name": "r", "@field": "b", "@condition": { "op": "eq", "left": { "fn": "lower", "args": [ { "field": "a" } ] }, "right": { "value": "x" } } } } ] } } + """); + } + + [Fact] + public void A_grain_needs_an_object_array_and_a_union_needs_one_shape() + { + Refused("ERR_BAD_ATTR_VALUE", "@grain \"zip\" must name a field.object array", """ + { "object.projection": { "name": "G", "@grain": "zip", "children": [ + { "source.rdb": { "@kind": "view", "@view": "g" } }, { "field.long": { "name": "customerId", "extends": "Customer.id" } } ] } } + """); + Assert.Empty(Load(""" + { "object.projection": { "name": "G", "@grain": "contacts", "@grainOrdinal": "pos", "children": [ + { "source.rdb": { "@kind": "view", "@view": "g" } }, { "field.long": { "name": "customerId", "extends": "Customer.id" } }, + { "field.int": { "name": "pos" } }, + { "field.string": { "name": "kind", "children": [ { "origin.passthrough": { "@from": "Contact.kind" } } ] } } ] } } + """)); + Refused("ERR_BAD_ATTR_VALUE", "@unionAll needs @union", """ + { "object.projection": { "name": "A", "abstract": true, "children": [ { "field.long": { "name": "personId", "extends": "Customer.id" } } ] } }, + { "object.projection": { "name": "U", "extends": "A", "@unionAll": true, "children": [ { "source.rdb": { "@kind": "view", "@view": "u" } } ] } } + """); + } + + [Fact] + public void The_db_column_type_text_spellings_load_and_an_oversize_max_length_is_refused() + { + foreach (var t in new[] { "text", "varchar", "character varying", "varchar(12)", "character varying(12)", "character(3)" }) + Assert.Empty(Load($$""" + { "object.entity": { "name": "R", "children": [ { "source.rdb": { "@table": "r" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "c", "@dbColumnType": "{{t}}" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } + """)); + Refused("ERR_BAD_ATTR_VALUE", "@maxLength: 10 over '@dbColumnType: character(3)'", """ + { "object.entity": { "name": "R", "children": [ { "source.rdb": { "@table": "r" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "c", "@dbColumnType": "character(3)", "@maxLength": 10 } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } + """); + Refused("ERR_BAD_ATTR_VALUE", "'VARCHAR' is not a valid value", """ + { "object.entity": { "name": "R", "children": [ { "source.rdb": { "@table": "r" } }, { "field.long": { "name": "id" } }, + { "field.string": { "name": "c", "@dbColumnType": "VARCHAR" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } + """); + } +} diff --git a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs index ae5e9d7f9b..dd01e70ee8 100644 --- a/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs +++ b/server/csharp/MetaObjects/Core/Attr/ExpressionGrammar.cs @@ -39,6 +39,92 @@ public static class ExpressionGrammar public const string EXPR_CASE_OPERAND = "operand"; public const string EXPR_NOW = "now"; public const string EXPR_NOW_START_OF = "startOf"; + // rc.21 part B (U12): { cast: , as: "", dbColumnType?: "" }. + public const string EXPR_CAST = "cast"; + public const string EXPR_CAST_AS = "as"; + public const string EXPR_CAST_DB_COLUMN_TYPE = "dbColumnType"; + + /// A function parameter's kind: a string, an integer, any scalar, or the type the "same" ones share. + private enum ParamKind { String, Int, Scalar, Same } + /// One function's signature: arity, each parameter's kind (the last repeats) and the result. + private sealed record FnSignature(int Min, int Max, ParamKind[] Params, string Result, bool Ordered = false); + + /// + /// rc.21 part B (U11, U13): the closed, typed function set beside coalesce, by name — the TS + /// EXPR_FUNCTIONS table, entry for entry. Never free SQL. + /// + private static readonly Dictionary Functions = new(StringComparer.Ordinal) + { + [EXPR_FN_COALESCE] = new(1, int.MaxValue, [ParamKind.Same], "same"), + ["greatest"] = new(1, int.MaxValue, [ParamKind.Same], "same", Ordered: true), + ["least"] = new(1, int.MaxValue, [ParamKind.Same], "same", Ordered: true), + ["nullif"] = new(2, 2, [ParamKind.Same, ParamKind.Same], "same"), + ["lower"] = new(1, 1, [ParamKind.String], "string"), + ["upper"] = new(1, 1, [ParamKind.String], "string"), + ["btrim"] = new(1, 2, [ParamKind.String, ParamKind.String], "string"), + ["splitPart"] = new(3, 3, [ParamKind.String, ParamKind.String, ParamKind.Int], "string"), + ["concat"] = new(1, int.MaxValue, [ParamKind.Scalar], "string"), + ["concatWs"] = new(2, int.MaxValue, [ParamKind.String, ParamKind.Scalar], "string"), + ["substring"] = new(2, 3, [ParamKind.String, ParamKind.Int, ParamKind.Int], "string"), + ["replace"] = new(3, 3, [ParamKind.String, ParamKind.String, ParamKind.String], "string"), + ["left"] = new(2, 2, [ParamKind.String, ParamKind.Int], "string"), + ["right"] = new(2, 2, [ParamKind.String, ParamKind.Int], "string"), + ["length"] = new(1, 1, [ParamKind.String], "int"), + }; + + /// The field subtypes a cast may name in as. + public static readonly IReadOnlyList CastTargets = + [ + FIELD_SUBTYPE_STRING, FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, + FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_BOOLEAN, FIELD_SUBTYPE_DATE, FIELD_SUBTYPE_TIMESTAMP, FIELD_SUBTYPE_UUID, + ]; + private static readonly HashSet NumericSubtypes = new(StringComparer.Ordinal) + { + FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG, FIELD_SUBTYPE_DOUBLE, FIELD_SUBTYPE_FLOAT, FIELD_SUBTYPE_DECIMAL, FIELD_SUBTYPE_CURRENCY, + }; + private static readonly HashSet IntegerSubtypes = new(StringComparer.Ordinal) { FIELD_SUBTYPE_INT, FIELD_SUBTYPE_LONG }; + private static readonly HashSet NonScalarSubtypes = new(StringComparer.Ordinal) { FIELD_SUBTYPE_OBJECT, FIELD_SUBTYPE_MAP }; + + /// Why a value of cannot be cast to , or null — TS castProblem. + public static string? CastProblem(string? from, string to, bool intStoredEnum) + { + if (from is null) return null; + if (NonScalarSubtypes.Contains(from)) return $"a field.{from} value cannot be cast"; + if (from == to) return null; + if (from == FIELD_SUBTYPE_ENUM) + { + if (to == FIELD_SUBTYPE_STRING) return intStoredEnum ? "an int-stored enum (@intValueMap) cast to string gives its integer, not its member; cast it to int" : null; + if (IntegerSubtypes.Contains(to)) return intStoredEnum ? null : "only an enum stored as an integer (@intValueMap) can be cast to a number"; + return $"an enum cannot be cast to {to}"; + } + if (to == FIELD_SUBTYPE_STRING) return null; + if (from == FIELD_SUBTYPE_STRING) return null; + if (NumericSubtypes.Contains(to)) return NumericSubtypes.Contains(from) || from == FIELD_SUBTYPE_BOOLEAN ? null : $"a {from} cannot be cast to {to}"; + if (to == FIELD_SUBTYPE_BOOLEAN) return IntegerSubtypes.Contains(from) ? null : $"a {from} cannot be cast to boolean"; + if (to is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIMESTAMP) + return from is FIELD_SUBTYPE_DATE or FIELD_SUBTYPE_TIMESTAMP ? null : $"a {from} cannot be cast to {to}"; + return $"a {from} cannot be cast to {to}"; + } + + /// + /// The first node a CHECK condition cannot hold (case, now, cast, a function other than coalesce, + /// a path), or null — TS exprViewOnlyNode. + /// + public static string? ExprViewOnlyNode(object? node) + { + if (node is not IReadOnlyDictionary n) return null; + if (n.ContainsKey(EXPR_CAST)) return EXPR_CAST; + if (n.ContainsKey(EXPR_CASE)) return EXPR_CASE; + if (n.ContainsKey(EXPR_NOW)) return EXPR_NOW; + if (n.ContainsKey(KEY_FN) && !Equals(Get(n, KEY_FN), EXPR_FN_COALESCE)) return Str(Get(n, KEY_FN)); + if (Get(n, KEY_FIELD) is string f && f.Contains('.')) return $"the path \"{f}\""; + foreach (var key in new[] { KEY_LEFT, KEY_RIGHT, KEY_ARG }) + if (ExprViewOnlyNode(Get(n, key)) is { } hit) return hit; + if (Get(n, KEY_ARGS) is IEnumerable args) + foreach (var a in args) + if (ExprViewOnlyNode(a) is { } hit) return hit; + return null; + } // Node-kind keys (verbatim from the @expr tree — not metamodel attrs). private const string KEY_FIELD = "field"; @@ -77,6 +163,7 @@ void Walk(object? x) Walk(Get(n, KEY_RIGHT)); Walk(Get(n, KEY_ARG)); if (Get(n, KEY_ARGS) is IEnumerable args) foreach (var a in args) Walk(a); + Walk(Get(n, EXPR_CAST)); Walk(Get(n, EXPR_CASE_OPERAND)); Walk(Get(n, EXPR_CASE_ELSE)); if (Get(n, EXPR_CASE) is IEnumerable arms) @@ -147,13 +234,30 @@ public static List ValidateExprNode(object? node) return errs; } + if (n.ContainsKey(EXPR_CAST)) + { + var extra = n.Keys.Where(k => k != EXPR_CAST && k != EXPR_CAST_AS && k != EXPR_CAST_DB_COLUMN_TYPE).ToList(); + if (extra.Count > 0) + return [$"expression '{EXPR_CAST}' takes only '{EXPR_CAST_AS}' and '{EXPR_CAST_DB_COLUMN_TYPE}' beside it, not {string.Join(", ", extra)}"]; + if (Get(n, EXPR_CAST_AS) is not string to || !CastTargets.Contains(to)) + return [$"'{EXPR_CAST}' requires '{EXPR_CAST_AS}': one of {string.Join(", ", CastTargets)}"]; + if (n.ContainsKey(EXPR_CAST_DB_COLUMN_TYPE)) + { + var parsed = Get(n, EXPR_CAST_DB_COLUMN_TYPE) is string spelling ? MetaObjects.Persistence.Db.DbConstants.ParseDbColumnType(spelling) : null; + if (parsed is null || parsed.Kind is "uuid" or "jsonb" || to != FIELD_SUBTYPE_STRING) + return [$"'{EXPR_CAST}' '{EXPR_CAST_DB_COLUMN_TYPE}' is a text spelling of @dbColumnType (text, varchar, character varying, varchar(n), character varying(n), character(n)) with '{EXPR_CAST_AS}: {FIELD_SUBTYPE_STRING}'"]; + } + return ValidateExprNode(Get(n, EXPR_CAST)); + } + if (n.ContainsKey(KEY_FN)) { - if (Get(n, KEY_FN) is not string fn || fn != EXPR_FN_COALESCE) + if (Get(n, KEY_FN) is not string fn || !Functions.TryGetValue(fn, out var sig)) return [$"unknown expression fn '{Str(Get(n, KEY_FN))}'"]; - return Get(n, KEY_ARGS) is IReadOnlyList args && args.Count >= 1 - ? args.SelectMany(ValidateExprNode).ToList() - : [$"'{EXPR_FN_COALESCE}' requires a non-empty args array"]; + if (Get(n, KEY_ARGS) is not IReadOnlyList args || args.Count < Math.Max(sig.Min, 1)) + return [sig.Min <= 1 ? $"'{fn}' requires a non-empty args array" : $"'{fn}' requires at least {sig.Min} args"]; + if (args.Count > sig.Max) return [$"'{fn}' takes at most {sig.Max} args, got {args.Count}"]; + return args.SelectMany(ValidateExprNode).ToList(); } if (n.ContainsKey(KEY_OP)) @@ -181,7 +285,7 @@ public static List ValidateExprNode(object? node) return [$"unknown expression op '{op}'"]; } - return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}"]; + return ["expression node must be one of {field}, {value}, {op,…}, {fn,…}, {case,…}, {now}, {cast,…}"]; } // ------------------------------------------------------------------------- @@ -198,8 +302,9 @@ public static List ValidateExprNode(object? node) /// coalesce → the unified arg subType. Also enforces per-operand op legality /// against the shared filter bands. Mirrors TS inferExprType. /// - public static InferResult InferExprType(object? node, Func resolveField) + public static InferResult InferExprType(object? node, Func resolveField, Func? isIntStoredEnum = null) { + isIntStoredEnum ??= _ => false; var structural = ValidateExprNode(node); if (structural.Count > 0) return new InferResult(null, structural); var n = (IReadOnlyDictionary)node!; @@ -224,25 +329,25 @@ public static InferResult InferExprType(object? node, Func reso { var errors = new List(); var arms = (IReadOnlyList)Get(n, EXPR_CASE)!; - InferResult? operand = n.ContainsKey(EXPR_CASE_OPERAND) ? InferExprType(Get(n, EXPR_CASE_OPERAND), resolveField) : null; + InferResult? operand = n.ContainsKey(EXPR_CASE_OPERAND) ? InferExprType(Get(n, EXPR_CASE_OPERAND), resolveField, isIntStoredEnum) : null; if (operand is { } o) errors.AddRange(o.Errors); var results = new List(); foreach (var armObj in arms) { var arm = (IReadOnlyDictionary)armObj!; - var w = InferExprType(Get(arm, EXPR_CASE_WHEN), resolveField); + var w = InferExprType(Get(arm, EXPR_CASE_WHEN), resolveField, isIntStoredEnum); errors.AddRange(w.Errors); if (operand is null && w.Type is not null && w.Type != FIELD_SUBTYPE_BOOLEAN) errors.Add($"a searched '{EXPR_CASE}' needs a boolean '{EXPR_CASE_WHEN}', got {w.Type}"); if (operand is { Type: { } ot } && w.Type is not null && w.Type != ot) errors.Add($"a simple '{EXPR_CASE}' compares its {ot} '{EXPR_CASE_OPERAND}' with a {w.Type} '{EXPR_CASE_WHEN}'"); - var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField); + var t = InferExprType(Get(arm, EXPR_CASE_THEN), resolveField, isIntStoredEnum); errors.AddRange(t.Errors); results.Add(t.Type); } if (n.ContainsKey(EXPR_CASE_ELSE)) { - var e = InferExprType(Get(n, EXPR_CASE_ELSE), resolveField); + var e = InferExprType(Get(n, EXPR_CASE_ELSE), resolveField, isIntStoredEnum); errors.AddRange(e.Errors); results.Add(e.Type); } @@ -253,30 +358,55 @@ public static InferResult InferExprType(object? node, Func reso return new InferResult(unified, errors); } - if (n.ContainsKey(KEY_FN)) // coalesce + if (n.ContainsKey(EXPR_CAST)) { + var inner = Get(n, EXPR_CAST); + var operand = InferExprType(inner, resolveField, isIntStoredEnum); + var to = (string)Get(n, EXPR_CAST_AS)!; + var fieldRef = inner is IReadOnlyDictionary innerNode ? Get(innerNode, KEY_FIELD) as string : null; + var problem = CastProblem(operand.Type, to, fieldRef is not null && isIntStoredEnum(fieldRef)); + return new InferResult(to, problem is null ? operand.Errors : [.. operand.Errors, $"'{EXPR_CAST}': {problem}"]); + } + + if (n.ContainsKey(KEY_FN)) + { + var name = (string)Get(n, KEY_FN)!; + var sig = Functions[name]; var args = (IReadOnlyList)Get(n, KEY_ARGS)!; - var argResults = args.Select(a => InferExprType(a, resolveField)).ToList(); + var argResults = args.Select(a => InferExprType(a, resolveField, isIntStoredEnum)).ToList(); var errors = argResults.SelectMany(a => a.Errors).ToList(); - var argTypes = argResults.Select(a => a.Type).Where(t => t is not null).Select(t => t!).ToList(); - string? unified = argTypes.Count > 0 ? argTypes[0] : null; - if (unified is not null && argTypes.Any(t => t != unified)) - errors.Add($"'{EXPR_FN_COALESCE}' arguments have differing types ({string.Join(", ", argTypes.Distinct())})"); - return new InferResult(unified, errors); + var same = new List(); + for (var i = 0; i < argResults.Count; i++) + { + var t = argResults[i].Type; + if (t is null) continue; // a null literal fits any parameter + var kind = sig.Params[Math.Min(i, sig.Params.Length - 1)]; + if (kind == ParamKind.Same) same.Add(t); + else if (kind == ParamKind.String && t != FIELD_SUBTYPE_STRING) errors.Add($"'{name}' argument {i + 1} must be a string, got {t}"); + else if (kind == ParamKind.Int && !IntegerSubtypes.Contains(t)) errors.Add($"'{name}' argument {i + 1} must be an integer, got {t}"); + else if (kind == ParamKind.Scalar && NonScalarSubtypes.Contains(t)) errors.Add($"'{name}' argument {i + 1} must be a scalar, got {t}"); + } + string? unified = same.Count > 0 ? same[0] : null; + if (unified is not null && same.Any(t => t != unified)) + errors.Add($"'{name}' arguments have differing types ({string.Join(", ", same.Distinct())})"); + if (sig.Ordered && unified is not null && (unified == FIELD_SUBTYPE_BOOLEAN || NonScalarSubtypes.Contains(unified))) + errors.Add($"'{name}' needs ordered arguments, got {unified}"); + var type = sig.Result == "same" ? unified : sig.Result == "int" ? FIELD_SUBTYPE_INT : FIELD_SUBTYPE_STRING; + return new InferResult(type, errors); } var op = (string)Get(n, KEY_OP)!; if (ComparisonOps.Contains(op)) { - var l = InferExprType(Get(n, KEY_LEFT), resolveField); - var r = InferExprType(Get(n, KEY_RIGHT), resolveField); + var l = InferExprType(Get(n, KEY_LEFT), resolveField, isIntStoredEnum); + var r = InferExprType(Get(n, KEY_RIGHT), resolveField, isIntStoredEnum); var errors = l.Errors.Concat(r.Errors).ToList(); if (l.Type is not null && !OpsForSubType(l.Type).Contains(op)) errors.Add($"op '{op}' is not legal for a {l.Type} operand"); return new InferResult(FIELD_SUBTYPE_BOOLEAN, errors); } if (NullOps.Contains(op)) - return new InferResult(FIELD_SUBTYPE_BOOLEAN, InferExprType(Get(n, KEY_ARG), resolveField).Errors.ToList()); + return new InferResult(FIELD_SUBTYPE_BOOLEAN, InferExprType(Get(n, KEY_ARG), resolveField, isIntStoredEnum).Errors.ToList()); if (op == EXPR_OP_NOT || VariadicLogicOps.Contains(op)) { var kids = op == EXPR_OP_NOT @@ -285,7 +415,7 @@ public static InferResult InferExprType(object? node, Func reso var errors = new List(); foreach (var k in kids) { - var kt = InferExprType(k, resolveField); + var kt = InferExprType(k, resolveField, isIntStoredEnum); errors.AddRange(kt.Errors); if (kt.Type is not null && kt.Type != FIELD_SUBTYPE_BOOLEAN) errors.Add($"op '{op}' requires boolean operands, got {kt.Type}"); diff --git a/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs b/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs index 909d304974..98305852b6 100644 --- a/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs +++ b/server/csharp/MetaObjects/Core/Object/ObjectConstants.cs @@ -81,6 +81,11 @@ public static class ObjectConstants /// max 1). Mirrors TS OBJECT_PROJECTION_ATTR_FILTER. /// public const string OBJECT_PROJECTION_ATTR_FILTER = "filter"; + /// rc.21 part B: a projection UNIONed with others (U15), and one with a row per array element (U14). + public const string OBJECT_PROJECTION_ATTR_UNION = "union"; + public const string OBJECT_PROJECTION_ATTR_UNION_ALL = "unionAll"; + public const string OBJECT_PROJECTION_ATTR_GRAIN = "grain"; + public const string OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL = "grainOrdinal"; // ----------------------------------------------------------------------- // FR-044 — object.report attrs. Mirrors TS OBJECT_REPORT_ATTR_*. diff --git a/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs b/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs index a95b8a5ab7..ff65becb1e 100644 --- a/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs +++ b/server/csharp/MetaObjects/Core/Object/ObjectSchema.cs @@ -102,4 +102,20 @@ public static class ObjectSchema "returns — lowered to an outer SQL WHERE. Resolves against the " + "projection's own declared fields; an aggregate-derived field is not " + "addressable (fail-closed)."); + + /// + /// rc.21 part B — @union / @unionAll (U15) and @grain / @grainOrdinal (U14) on an + /// object.projection. Descriptions are single-sourced from spec/metamodel/object.json. + /// + public static readonly IReadOnlyList ProjectionShapeAttrs = + [ + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_UNION, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, + Description: "rc.21: the view is this projection's rows UNIONed with each named projection's rows."), + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_UNION_ALL, ValueType: AttrConstants.ATTR_SUBTYPE_BOOLEAN, Required: false, + Description: "rc.21: with @union, keep duplicate rows (UNION ALL)."), + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_GRAIN, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + Description: "rc.21: the view has one row per element of this base-entity field.object array."), + new AttrSchema(Name: ObjectConstants.OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + Description: "rc.21: with @grain, the projection field that holds the element's 1-based position."), + ]; } diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs index 719cc683ed..88d773c134 100644 --- a/server/csharp/MetaObjects/CoreTypes.cs +++ b/server/csharp/MetaObjects/CoreTypes.cs @@ -319,7 +319,7 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry) // declare; its structural child graph also comes from the spec. List objectAttrs = subType switch { - OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, ObjectSchema.CollectionNameAttr, ObjectSchema.DbSetNameAttr], + OBJECT_SUBTYPE_PROJECTION => [.. ObjectSchema.ObjectAttrs, ObjectSchema.ProjectionFilterAttr, .. ObjectSchema.ProjectionShapeAttrs, ObjectSchema.CollectionNameAttr, ObjectSchema.DbSetNameAttr], OBJECT_SUBTYPE_REPORT => [.. ObjectSchema.ObjectAttrs, .. ReportingSchema.ReportAttrs, ObjectSchema.CollectionNameAttr, ObjectSchema.DbSetNameAttr], OBJECT_SUBTYPE_ENTITY => [.. ObjectSchema.ObjectAttrs, ObjectSchema.CollectionNameAttr, ObjectSchema.DbSetNameAttr], _ => ObjectSchema.ObjectAttrs.ToList(), diff --git a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs index eb825624c1..72faee9228 100644 --- a/server/csharp/MetaObjects/Loader/MetaDataLoader.cs +++ b/server/csharp/MetaObjects/Loader/MetaDataLoader.cs @@ -526,6 +526,8 @@ public LoadResult Load(IReadOnlyList sources) // aggregate-derived field-ref fails closed with ERR_BAD_ATTR_FILTER. errors.AddRange(ValidationPasses.ValidateProjectionFilter(root)); errors.AddRange(ValidationPasses.ValidateOriginSegmentsAndCorrelation(root)); + // rc.21 part B — @union shapes and @grain projections. + errors.AddRange(ValidationPasses.ValidateProjectionUnionAndGrain(root)); // Pass 7c (FR-044): reporting vocabulary cross-node rules (dimensions, measures, // segments, reports, relative-date filter values). diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 2184610529..51f9be9c2a 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -513,6 +513,23 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) } var fromTarget = ValidateFromPath(from, root, obj, field.Name, errors, "origin.passthrough.@from", origin.Source); + // rc.21 part B (U14): on a @grain projection, a @from on the grain field's value + // object reads a member of the array element; there is no path to walk. + if (fromTarget is ResolvedFromTarget gt && GrainValueObject(obj, root) is { } grainVo + && ReferenceEquals(gt.Entity, grainVo)) + { + bool gconvert = origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_CONVERT) is true; + CheckPassthroughType(field, gt.Field, from, gconvert, obj, origin.Source, errors); + if ((gt.Field is MetaField gmf && gmf.ResolvedIsArray()) || gt.Field.SubType is FIELD_SUBTYPE_OBJECT or FIELD_SUBTYPE_MAP) + errors.Add(new MetaError( + $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" is not a scalar member of the @grain element.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); + if (origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_VIA) is not null) + errors.Add(new MetaError( + $"origin.passthrough on {obj.Name}.{field.Name}: @from \"{from}\" reads the @grain element, which takes no @via.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: origin.Source)); + continue; + } // FR-024 B6 — extends/origin agreement (host-agnostic; runs // whether @via is explicit, inferred, or a base-relation column). if (fromTarget is ResolvedFromTarget ft1) @@ -770,18 +787,28 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) // rc.19 computed-over-joined: a ref names one of the projection's own fields // first (a passthrough, an origin.first, another computed — never itself, never // an aggregate), else a base field. - Func resolveField = name => + // rc.21 part B: also a scalar origin.aggregate (U13, read on the grouped row) and, + // on a projection, a PATH of to-one hops from the base (U3). Never a collect. + Func fieldNode = name => { if (!ReferenceEquals(obj, computedBase) && name != field.Name && obj.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name) is { } own) - { - var ownOrigin = own.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); - return ownOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE ? null : own.SubType; - } - return computedBase!.Children() - .FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name)?.SubType; + return own; + var baseField = computedBase!.Children().FirstOrDefault(f => f.Type == TYPE_FIELD && f.Name == name); + if (baseField is not null || ReferenceEquals(obj, computedBase) || !name.Contains('.')) return baseField; + return computedBase is MetaObject bo ? FilterPaths.Resolve(bo, name, out _)?.Field : null; + }; + Func resolveField = name => + { + if (fieldNode(name) is not { } node) return null; + var nodeOrigin = node.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + if (!ReferenceEquals(node, field) && nodeOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE + && nodeOrigin.OwnAttr(ORIGIN_AGGREGATE_ATTR_AGG) as string == AGG_COLLECT) return null; + return node.SubType; }; - var inferred = ExpressionGrammar.InferExprType(expr, resolveField); + Func isIntStoredEnum = name => + fieldNode(name) is { } node && node.SubType == FIELD_SUBTYPE_ENUM && node.Attr(FIELD_ATTR_INT_VALUE_MAP) is not null; + var inferred = ExpressionGrammar.InferExprType(expr, resolveField, isIntStoredEnum); if (inferred.Errors.Count > 0) { foreach (var m in inferred.Errors) @@ -795,6 +822,10 @@ public static IReadOnlyList ValidateOriginPaths(MetaData root) $"origin.computed on {obj.Name}.{field.Name}: @expr infers field.{inferred.Type} but the field is declared field.{field.SubType} — a computed column's type is derived from its expression and must match (no @convert escape).", ErrorCode.ERR_COMPUTED_TYPE_MISMATCH, Envelope: src)); } + else if (origin.SubType == ORIGIN_SUBTYPE_FUNCTION) + { + ValidateFunctionOrigin(origin, obj, field, root, errors); + } else if (origin.SubType == ORIGIN_SUBTYPE_FIRST) { // #195 — pick one related row by @orderBy along @via, project @of. @@ -1607,10 +1638,17 @@ private static HashSet ProjectionReachedEntityFields(MetaData root) } } foreach (var field in obj.Children().Where(c => c.Type == TYPE_FIELD)) + { foreach (var origin in field.OwnChildren().Where(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_PASSTHROUGH)) if (origin.OwnAttr(ORIGIN_PASSTHROUGH_ATTR_FROM) is string from && ValidateFromPath(from, root, obj, field.Name, silent, "origin.passthrough.@from", origin.Source) is { } target) reached.Add(target.Field); + // rc.21 part B (U3): a computed expression's path ref reaches the field at its end. + if (baseEntity is MetaObject bo2 && !ReferenceEquals(baseEntity, obj)) + foreach (var origin in field.OwnChildren().Where(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_COMPUTED)) + foreach (var name in ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR)).Where(n => n.Contains('.'))) + if (FilterPaths.Resolve(bo2, name, out _) is { } p) reached.Add(p.Field); + } } return reached; } @@ -1649,7 +1687,132 @@ public static IReadOnlyList ValidateOriginSegmentsAndCorrelation(Meta if (origin.OwnAttr(ORIGIN_FIRST_ATTR_FILTER) is not IReadOnlyDictionary filter) continue; var silent = new List(); if (DeriveBaseEntity(obj, root, field.Name, origin.Source, silent) is not { } baseEntity) continue; - CheckCorrelatedOperands(filter, baseEntity, where, origin.Source, errors); + CheckCorrelatedOperands(filter, baseEntity, where, origin.Source, errors, obj.SubType == OBJECT_SUBTYPE_PROJECTION); + } + } + } + return errors.AsReadOnly(); + } + + /// + /// rc.21 part B (U10) — origin.function: its name and schema are plain identifiers (never free + /// SQL); each argument names a scalar field of the host entity, or of the projection (not an + /// aggregate, not the field itself) or its base. Mirrors TS _validateFunctionOrigin. + /// + private static void ValidateFunctionOrigin(MetaData origin, MetaData obj, MetaData field, MetaData root, List errors) + { + var src = origin.Source; + var where = $"origin.function on {obj.Name}.{field.Name}"; + foreach (var attr in new[] { ORIGIN_FUNCTION_ATTR_FUNCTION, ORIGIN_FUNCTION_ATTR_SCHEMA }) + { + var v = origin.OwnAttr(attr); + if (v is not null && (v is not string sv || !ORIGIN_FUNCTION_IDENTIFIER.IsMatch(sv))) + errors.Add(new MetaError( + $"{where}: @{attr} {System.Text.Json.JsonSerializer.Serialize(v?.ToString())} is not a plain identifier ([A-Za-z_][A-Za-z0-9_]*); a function is named, never written as SQL.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + } + var raw = origin.OwnAttr(ORIGIN_FUNCTION_ATTR_ARGS); + var args = raw switch { null => new List(), IReadOnlyList l => l.ToList(), _ => new List { raw } }; + var isProjection = obj.SubType == OBJECT_SUBTYPE_PROJECTION; + var baseEntity = isProjection ? DeriveBaseEntity(obj, root, field.Name, src, new List()) : obj; + foreach (var a in args) + { + var name = a as string; + var own = name is not null && name != field.Name + ? obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) : null; + var ownOrigin = own?.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + var arg = own ?? (name is not null && baseEntity is not null + ? baseEntity.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name) : null); + if (arg is null || name == field.Name) + errors.Add(new MetaError( + $"{where}: @args names \"{a}\", which is not a field of {(isProjection ? "the projection or its base entity" : $"\"{obj.Name}\"")}.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + else if (ownOrigin?.SubType == ORIGIN_SUBTYPE_AGGREGATE) + errors.Add(new MetaError( + $"{where}: @args names \"{a}\", an origin.aggregate; a function takes values of the row, not of the group.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + else if (arg.SubType is FIELD_SUBTYPE_OBJECT or FIELD_SUBTYPE_MAP || (arg is MetaField af && af.ResolvedIsArray())) + errors.Add(new MetaError( + $"{where}: @args names \"{a}\", a field.{arg.SubType}{(arg is MetaField af2 && af2.ResolvedIsArray() ? " array" : "")}; a function argument is a scalar.", + ErrorCode.ERR_INVALID_ORIGIN, Envelope: src)); + } + } + + /// rc.21 part B (U14): the value object a @grain projection's rows are elements of. + private static MetaData? GrainValueObject(MetaData obj, MetaData root) + { + if (obj.SubType != OBJECT_SUBTYPE_PROJECTION || obj.Attr(OBJECT_PROJECTION_ATTR_GRAIN) is not string grain) return null; + var baseEntity = DeriveBaseEntity(obj, root, "@grain", obj.Source, new List()); + var field = baseEntity?.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == grain); + return field is null ? null : NamingRefs.RefTarget(field, FIELD_ATTR_OBJECT_REF); + } + + /// + /// rc.21 part B — @union shapes (U15) and @grain projections (U14). Mirrors TS + /// validateProjectionUnionAndGrain, message for message. + /// + public static IReadOnlyList ValidateProjectionUnionAndGrain(MetaData root) + { + var errors = new List(); + foreach (var obj in root.OwnChildren().Where(c => c.Type == TYPE_OBJECT && c.SubType == OBJECT_SUBTYPE_PROJECTION)) + { + void Bad(string message) => errors.Add(new MetaError($"object.projection {obj.Name}: {message}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: obj.Source)); + // ADR-0039: own — a projection's @union / @grain names ITS view's shape. + var union = obj.OwnAttr(OBJECT_PROJECTION_ATTR_UNION); + if (obj.OwnAttr(OBJECT_PROJECTION_ATTR_UNION_ALL) is not null && union is null) + Bad($"@{OBJECT_PROJECTION_ATTR_UNION_ALL} needs @{OBJECT_PROJECTION_ATTR_UNION}."); + if (union is not null) + { + var pkg = NamingRefs.EffectivePackage(obj); + var mine = obj.Children().Where(c => c.Type == TYPE_FIELD).ToList(); + var names = union is IReadOnlyList l ? l.ToList() : new List { union }; + static string Describe(MetaData f) + { + var arr = f is MetaField mf && mf.ResolvedIsArray() ? "[]" : ""; + var col = f.Attr(FIELD_ATTR_COLUMN) is string c ? $" @column {c}" : ""; + return $"{f.Name}: field.{f.SubType}{arr}{col}"; + } + foreach (var nameObj in names) + { + var member = nameObj is string name ? NamingRefs.ResolveObjectRef(root, name, pkg) : null; + if (member is null || member.Type != TYPE_OBJECT || member.SubType != OBJECT_SUBTYPE_PROJECTION) + { + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} names \"{nameObj}\", which is not an object.projection."); + continue; + } + if (ReferenceEquals(member, obj)) + { + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} names the projection itself."); + continue; + } + var a = mine.Select(Describe).ToList(); + var b = member.Children().Where(c => c.Type == TYPE_FIELD).Select(Describe).ToList(); + if (!a.SequenceEqual(b)) + Bad($"@{OBJECT_PROJECTION_ATTR_UNION} member \"{member.Name}\" has a different shape: " + + $"({string.Join(", ", b)}) where this view is ({string.Join(", ", a)}). A union's members have the same fields, in order."); + } + } + var grain = obj.OwnAttr(OBJECT_PROJECTION_ATTR_GRAIN); + var ordinal = obj.OwnAttr(OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL); + if (ordinal is not null && grain is null) Bad($"@{OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} needs @{OBJECT_PROJECTION_ATTR_GRAIN}."); + if (grain is string g) + { + var baseEntity = DeriveBaseEntity(obj, root, "@grain", obj.Source, new List()); + var field = baseEntity?.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == g); + var isArray = field is MetaField gf && gf.ResolvedIsArray(); + var storage = field?.Attr(FIELD_ATTR_STORAGE) as string; + if (field is null || field.SubType != FIELD_SUBTYPE_OBJECT || !isArray || (storage is not null && storage != STORAGE_JSONB) + || NamingRefs.RefTarget(field, FIELD_ATTR_OBJECT_REF) is null) + Bad($"@{OBJECT_PROJECTION_ATTR_GRAIN} \"{g}\" must name a field.object array (isArray, jsonb storage, with @objectRef) of the base entity{(baseEntity is null ? "" : $" \"{baseEntity.Name}\"")}."); + foreach (var f in obj.Children().Where(c => c.Type == TYPE_FIELD)) + if (f.OwnChildren().Any(c => c.Type == TYPE_ORIGIN && c.SubType == ORIGIN_SUBTYPE_AGGREGATE)) + Bad($"\"{f.Name}\" is an origin.aggregate; a @grain view has one row per element and groups nothing."); + if (ordinal is not null) + { + var f = obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == ordinal as string); + if (f is null || (f.SubType != FIELD_SUBTYPE_INT && f.SubType != FIELD_SUBTYPE_LONG) + || f.OwnChildren().Any(c => c.Type == TYPE_ORIGIN) || f.SuperRef is not null) + Bad($"@{OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL} \"{ordinal}\" must name a field.int or field.long of the projection, with no origin and no extends."); } } } @@ -1678,7 +1841,8 @@ public static IReadOnlyList ValidateOriginSegmentsAndCorrelation(Meta } private static void CheckCorrelatedOperands( - IReadOnlyDictionary filter, MetaData baseEntity, string where, ErrorSource source, List errors) + IReadOnlyDictionary filter, MetaData baseEntity, string where, ErrorSource source, List errors, + bool onProjection) { foreach (var (key, clause) in filter) { @@ -1687,7 +1851,7 @@ private static void CheckCorrelatedOperands( if (clause is IReadOnlyList subs) foreach (var sub in subs) if (sub is IReadOnlyDictionary subFilter) - CheckCorrelatedOperands(subFilter, baseEntity, where, source, errors); + CheckCorrelatedOperands(subFilter, baseEntity, where, source, errors, onProjection); continue; } if (clause is not IReadOnlyDictionary ops) continue; @@ -1708,9 +1872,20 @@ private static void CheckCorrelatedOperands( $"{where}: @filter on \"{key}\" compares with a base-row field using \"{op}\"; a correlated operand takes {string.Join(", ", CorrelatedFilterOps)}.", ErrorCode.ERR_BAD_ATTR_FILTER, Envelope: source)); else if (name is null || !baseEntity.Children().Any(c => c.Type == TYPE_FIELD && c.Name == name)) + { + // rc.21 part B (U4): on a projection, a PATH of to-one hops from the base row. + string? why = null; + var path = name is not null && name.Contains('.') && onProjection && baseEntity is MetaObject bo + ? FilterPaths.Resolve(bo, name, out why) : null; + if (path is not null) continue; errors.Add(new MetaError( - $"{where}: @filter on \"{key}\" names base-row field \"{name}\", which \"{baseEntity.Name}\" does not declare.", + why is not null + ? $"{where}: @filter on \"{key}\" compares with the base-row path \"{name}\": {why}." + : name is not null && name.Contains('.') && !onProjection + ? $"{where}: @filter on \"{key}\" compares with the path \"{name}\"; a path operand is legal only on a projection, whose view joins it." + : $"{where}: @filter on \"{key}\" names base-row field \"{name}\", which \"{baseEntity.Name}\" does not declare.", ErrorCode.ERR_BAD_ATTR_FILTER, Envelope: source)); + } } } } @@ -1741,7 +1916,8 @@ public static IReadOnlyList ValidateDerivedFieldProvidability(MetaDat if (origin is null) continue; // rc.19 entity-derived: a derived field a projection reaches (its @filter or a passthrough // @from) is lowered inline there, so it needs no read source. Only the inlinable origins. - if ((origin.SubType == ORIGIN_SUBTYPE_FIRST || origin.SubType == ORIGIN_SUBTYPE_COMPUTED) && reached.Contains(field)) + if ((origin.SubType == ORIGIN_SUBTYPE_FIRST || origin.SubType == ORIGIN_SUBTYPE_COMPUTED + || origin.SubType == ORIGIN_SUBTYPE_FUNCTION) && reached.Contains(field)) continue; errors.Add(new MetaError( $"derived field \"{obj.Name}.{field.Name}\" carries an origin.* but entity \"{obj.Name}\" declares no " + @@ -1982,7 +2158,7 @@ public static IReadOnlyList ValidateProjectionFilter(MetaData root) var origin = f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); if (origin is not null && origin.SubType != ORIGIN_SUBTYPE_PASSTHROUGH && - origin.SubType != ORIGIN_SUBTYPE_COMPUTED) + (origin.SubType != ORIGIN_SUBTYPE_COMPUTED || ComputedReadsAggregate(f, obj, new HashSet(StringComparer.Ordinal)))) { aggregateDerived.Add(f.Name); } @@ -2030,6 +2206,26 @@ public static IReadOnlyList ValidateProjectionFilter(MetaData root) /// when it is an aggregate (a WHERE runs before grouping); its column, an origin.computed or an /// origin.first (a correlated scalar subquery) can (entity-derived). origin.* never inherits. /// + /// + /// rc.21 part B (U13): whether an origin.computed reads an origin.aggregate of its projection, + /// directly or through another computed — a value of the grouped row a WHERE cannot hold. + /// + private static bool ComputedReadsAggregate(MetaData f, MetaData obj, HashSet seen) + { + if (!seen.Add(f.Name)) return false; + // ADR-0039: own — origin.* never inherits (ADR-0029). + var origin = f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN); + if (origin?.SubType != ORIGIN_SUBTYPE_COMPUTED) return false; + foreach (var name in ExpressionGrammar.FieldRefs(origin.OwnAttr(ORIGIN_COMPUTED_ATTR_EXPR))) + { + if (name == f.Name) continue; + var other = obj.Children().FirstOrDefault(c => c.Type == TYPE_FIELD && c.Name == name); + if (other is null) continue; + if (EntityFieldAggregates(other) || ComputedReadsAggregate(other, obj, seen)) return true; + } + return false; + } + private static bool EntityFieldAggregates(MetaData f) => f.OwnChildren().FirstOrDefault(c => c.Type == TYPE_ORIGIN) is { SubType: ORIGIN_SUBTYPE_AGGREGATE }; @@ -2418,6 +2614,9 @@ public static IReadOnlyList ValidateCrossFieldValidators(MetaData roo /// private static string? ConditionProblem(object condition, MetaObject obj) { + // rc.21 part B: a CHECK holds only the subset every port's CHECK emitter renders. + if (MetaObjects.Core.Attr.ExpressionGrammar.ExprViewOnlyNode(condition) is { } viewOnly) + return $"uses {viewOnly}, which a CHECK condition cannot hold: it takes fields, literals, comparisons, null tests, and / or / not, and coalesce."; var fields = new Dictionary(StringComparer.Ordinal); foreach (var f in obj.Fields()) fields.TryAdd(f.Name, f); var inferred = MetaObjects.Core.Attr.ExpressionGrammar.InferExprType( @@ -3446,33 +3645,35 @@ private static void WalkDbColumnType(MetaData node, List errors) { if (node is MetaField field && field.DbColumnType is { } value) { - // Rule 1: recognized value. - if (!VALID_DB_COLUMN_TYPES.Contains(value)) + // Rule 1: recognized value (rc.21: the text spellings, sized ones included). + var parsed = ParseDbColumnType(value); + if (parsed is null) { errors.Add(new MetaError( $"field '{field.Name}' @{FIELD_ATTR_DB_COLUMN_TYPE} '{value}' is not a valid value; " + - $"allowed: {string.Join(", ", VALID_DB_COLUMN_TYPES)}", + $"allowed: {string.Join(", ", VALID_DB_COLUMN_TYPES.Concat(DB_COLUMN_TYPE_SIZED_SPELLINGS))}", ErrorCode.ERR_BAD_ATTR_VALUE, Envelope: field.Source)); } - else + else if (field.SubType != FIELD_SUBTYPE_STRING) { - // Rule 2: legal (subtype × value) pairing. - var requiredSubType = value switch - { - DB_COLUMN_TYPE_UUID or DB_COLUMN_TYPE_JSONB => FIELD_SUBTYPE_STRING, - _ => null, // unreachable (Rule 1) - }; - if (requiredSubType is not null && field.SubType != requiredSubType) - { - errors.Add(new MetaError( - $"field '{field.Name}' @{FIELD_ATTR_DB_COLUMN_TYPE} '{value}' is not valid on " + - $"field.{field.SubType} (requires field.{requiredSubType}); allowed pairings: " + - $"{DB_COLUMN_TYPE_UUID}→field.{FIELD_SUBTYPE_STRING}, " + - $"{DB_COLUMN_TYPE_JSONB}→field.{FIELD_SUBTYPE_STRING}", - ErrorCode.ERR_BAD_ATTR_VALUE, - Envelope: field.Source)); - } + // Rule 2: legal (subtype × value) pairing — every value is field.string's. + errors.Add(new MetaError( + $"field '{field.Name}' @{FIELD_ATTR_DB_COLUMN_TYPE} '{value}' is not valid on " + + $"field.{field.SubType} (requires field.{FIELD_SUBTYPE_STRING}); every @{FIELD_ATTR_DB_COLUMN_TYPE} value is a field.{FIELD_SUBTYPE_STRING}'s", + ErrorCode.ERR_BAD_ATTR_VALUE, + Envelope: field.Source)); + } + else if (parsed.Length is { } n && field.Attr(FIELD_ATTR_MAX_LENGTH) is { } maxObj + && Convert.ToInt64(maxObj, System.Globalization.CultureInfo.InvariantCulture) > n) + { + // Rule 3 (rc.21): a sized spelling holds n characters; a longer @maxLength (resolving) + // would let the app accept a value the column refuses. + errors.Add(new MetaError( + $"field.string '{field.Name}' declares @{FIELD_ATTR_MAX_LENGTH}: {maxObj} over '@{FIELD_ATTR_DB_COLUMN_TYPE}: {value}', " + + $"which holds {n}; a value the field accepts would not fit the column.", + ErrorCode.ERR_BAD_ATTR_VALUE, + Envelope: field.Source)); } } diff --git a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs index dc0f4ed6d7..d202e03457 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs @@ -83,10 +83,50 @@ public static class DbConstants /// @dbColumnType: jsonb — genuinely-open JSON column (legal on field.string). public const string DB_COLUMN_TYPE_JSONB = "jsonb"; - /// The closed set of legal @dbColumnType values. + /// rc.21 part B (U2): the text column spellings @dbColumnType takes on a field.string. + public const string DB_COLUMN_TYPE_TEXT = "text"; + public const string DB_COLUMN_TYPE_VARCHAR = "varchar"; + public const string DB_COLUMN_TYPE_CHARACTER_VARYING = "character varying"; + + /// The closed set of legal bare @dbColumnType values; the sized spellings + /// varchar(n), character varying(n) and character(n) are parsed by . public static readonly IReadOnlyList VALID_DB_COLUMN_TYPES = new[] { DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + DB_COLUMN_TYPE_TEXT, + DB_COLUMN_TYPE_VARCHAR, + DB_COLUMN_TYPE_CHARACTER_VARYING, }; + + /// The sized spellings, as written in a message. + public static readonly IReadOnlyList DB_COLUMN_TYPE_SIZED_SPELLINGS = new[] + { + "varchar(n)", "character varying(n)", "character(n)", + }; + + /// A parsed @dbColumnType: uuid, jsonb, text, varchar or char, and a sized spelling's length. + public sealed record ParsedDbColumnType(string Kind, int? Length); + + private static readonly System.Text.RegularExpressions.Regex SizedDbColumnType = + new(@"^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$", System.Text.RegularExpressions.RegexOptions.CultureInvariant); + + /// + /// rc.21 part B (U2): parse a @dbColumnType value, or null for one that is not legal. + /// Postgres's own spellings, matched exactly, as every port parses them (TS parseDbColumnType). + /// + public static ParsedDbColumnType? ParseDbColumnType(string value) + { + switch (value) + { + case DB_COLUMN_TYPE_UUID: return new("uuid", null); + case DB_COLUMN_TYPE_JSONB: return new("jsonb", null); + case DB_COLUMN_TYPE_TEXT: return new("text", null); + case DB_COLUMN_TYPE_VARCHAR or DB_COLUMN_TYPE_CHARACTER_VARYING: return new("varchar", null); + } + var m = SizedDbColumnType.Match(value); + if (!m.Success) return null; + var n = int.Parse(m.Groups[2].Value, System.Globalization.CultureInfo.InvariantCulture); + return m.Groups[1].Value == "character" ? new("char", n) : new("varchar", n); + } } diff --git a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs index d35c94d38e..871d65dc0f 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbSchema.cs @@ -29,23 +29,17 @@ public static class DbSchema /// /// R6 Plan 2b: @dbColumnType — physical DB column-type override on every field - /// subtype. The closed value set (ADR-0036 Wave 1) is - /// — surfaced as the manifest's allowedValues; the subtype × value pairing is + /// subtype. The bare values are plus the sized text + /// spellings (rc.21), so the manifest carries no allowedValues; the subtype × value pairing is /// validated own-only by the loader (ValidateDbColumnType → ERR_BAD_ATTR_VALUE). /// public static readonly AttrSchema DbColumnTypeSchema = new AttrSchema( Name: DbConstants.FIELD_ATTR_DB_COLUMN_TYPE, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, - AllowedValues: [.. DbConstants.VALID_DB_COLUMN_TYPES], - Description: - "Physical DB column-type override (ADR-0013 escape hatch). Legal values are uuid | jsonb, " + - "both on field.string (uuid = native Postgres uuid column over a string-typed field; " + - "jsonb = genuinely-open JSON column). The logical field type and its native binding are " + - "unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from " + - "a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — " + - "timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive " + - "opt-out), per ADR-0036 Wave 2."); + // rc.21 part B (U2): no allowedValues — the sized spellings (varchar(n), character(n)) are no + // closed set; ValidateDbColumnType parses the value (DbConstants.ParseDbColumnType). + Description: "Physical DB column-type override (ADR-0013 escape hatch). Legal values, all on field.string: uuid (a native Postgres uuid column over a string-typed field), jsonb (a genuinely-open JSON column), and the text spellings text, varchar / character varying (unbounded), varchar(n) / character varying(n) and character(n) (rc.21: Postgres's own names, lowercase; a @maxLength over n is refused). The view cast and the column use the spelling; meta migrate treats an unbounded varchar and text as one type. The logical field type and its native binding are unchanged. Native SQL arrays (uuid[]/text[]) are NOT declared here — they are derived from a field subtype + isArray (ADR-0036 Wave 1). The retired timestamp_with_tz value is gone — timezone-awareness lives in field.timestamp (instant by default) + @localTime (the naive opt-out), per ADR-0036 Wave 2."); /// /// ADR-0036 Wave 2: @localTime — the naive-timestamp opt-out on field.timestamp diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs index 4706a1abc6..560c08d2a8 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginConstants.cs @@ -30,6 +30,8 @@ public static class OriginConstants // along @via, projecting @of (argmax-then-project). public const string ORIGIN_SUBTYPE_COMPUTED = "computed"; public const string ORIGIN_SUBTYPE_FIRST = "first"; + // rc.21 part B (U10): a value computed by a database function the project owns. + public const string ORIGIN_SUBTYPE_FUNCTION = "function"; public static readonly string[] ORIGIN_SUBTYPES = [ @@ -38,6 +40,7 @@ public static class OriginConstants ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ]; // #210 — the ASSEMBLY origins: they derive a value by rolling up, computing, @@ -51,6 +54,7 @@ public static class OriginConstants ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, }; // passthrough attrs @@ -85,6 +89,13 @@ public static class OriginConstants public const string ORIGIN_FIRST_ATTR_VIA = "via"; public const string ORIGIN_FIRST_ATTR_FILTER = "filter"; + // rc.21 part B (U10) origin.function attrs. + public const string ORIGIN_FUNCTION_ATTR_FUNCTION = "function"; + public const string ORIGIN_FUNCTION_ATTR_SCHEMA = "schema"; + public const string ORIGIN_FUNCTION_ATTR_ARGS = "args"; + /// A plain SQL identifier: what @function and @schema may hold (never free SQL). + public static readonly System.Text.RegularExpressions.Regex ORIGIN_FUNCTION_IDENTIFIER = new("^[A-Za-z_][A-Za-z0-9_]*$"); + // aggregate function vocabulary. // // AGGREGATE_FUNCTIONS is the NUMERIC/ORDINAL reduce set — each maps directly to diff --git a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs index 5bb0d8dfc6..2269e13a20 100644 --- a/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs +++ b/server/csharp/MetaObjects/Persistence/Origin/OriginSchema.cs @@ -129,6 +129,17 @@ public static class OriginSchema Description: "Optional name of a segment.filter declared on the related entity; its predicate scopes the related rows, ANDed with @filter."), ]; + // rc.21 part B (U10) — function: a call of a database function the project owns. + private static readonly IReadOnlyList FunctionOriginAttrs = + [ + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_FUNCTION, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: true, + Description: "The function's name as the database names it: a plain identifier."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_SCHEMA, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, + Description: "The schema the function lives in, a plain identifier. Absent: public."), + new AttrSchema(Name: OriginConstants.ORIGIN_FUNCTION_ATTR_ARGS, ValueType: AttrConstants.ATTR_SUBTYPE_STRING, Required: false, IsArray: true, + Description: "The fields passed to the function, in parameter order."), + ]; + /// /// Attrs per origin subtype. base has none; passthrough, aggregate, /// computed (#195), and first (#195) carry their respective attrs. @@ -141,5 +152,6 @@ public static class OriginSchema [OriginConstants.ORIGIN_SUBTYPE_AGGREGATE] = [.. AggregateOriginAttrs], [OriginConstants.ORIGIN_SUBTYPE_COMPUTED] = [.. ComputedOriginAttrs], [OriginConstants.ORIGIN_SUBTYPE_FIRST] = [.. FirstOriginAttrs], + [OriginConstants.ORIGIN_SUBTYPE_FUNCTION] = [.. FunctionOriginAttrs], }; } From 099bdaacc081c4e30a05b44d8471624693602f64 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 18:27:54 -0500 Subject: [PATCH 192/267] feat(java,python): register the rc.21 view vocabulary so a strict load accepts it Java and Python register origin.function and the four projection attrs (@union, @unionAll, @grain, @grainOrdinal), and accept the text @dbColumnType spellings with the @maxLength-over-n refusal. They do not validate the view rules (the expression grammar, paths, union shapes, grain): both ports already lag the rc.19 view vocabulary there, and only TypeScript emits view SQL. The new conformance fixtures that need those rules join that known lag. Co-Authored-By: Claude Opus 5.5 --- .../database/CoreDBMetaDataProvider.java | 21 +++++++- .../metaobjects/loader/ValidationPhase.java | 29 ++++++---- .../com/metaobjects/object/MetaObject.java | 10 ++++ .../metaobjects/origin/FunctionOrigin.java | 53 +++++++++++++++++++ .../origin/OriginTypesMetaDataProvider.java | 1 + server/python/src/metaobjects/core_types.py | 24 +++++++++ .../metaobjects/loader/validation_passes.py | 26 +++++++-- .../meta/core/object/object_constants.py | 5 ++ .../meta/persistence/db/db_constants.py | 29 ++++++++++ .../meta/persistence/db/db_provider.py | 2 +- .../persistence/origin/origin_constants.py | 7 +++ 11 files changed, 191 insertions(+), 16 deletions(-) create mode 100644 server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java diff --git a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java index 1fc244795c..805f0135c4 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/database/CoreDBMetaDataProvider.java @@ -107,7 +107,26 @@ public class CoreDBMetaDataProvider implements MetaDataTypeProvider { * with the Kotlin port via this JVM provider.

    */ public static final java.util.List VALID_DB_COLUMN_TYPES = java.util.List.of( - DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB); + DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, "text", "varchar", "character varying"); + + /** rc.21 part B (U2): the sized text spellings, as written in a message. */ + public static final java.util.List DB_COLUMN_TYPE_SIZED_SPELLINGS = + java.util.List.of("varchar(n)", "character varying(n)", "character(n)"); + + private static final java.util.regex.Pattern SIZED_DB_COLUMN_TYPE = + java.util.regex.Pattern.compile("^(varchar|character varying|character)\\(([1-9][0-9]{0,8})\\)$"); + + /** + * rc.21 part B (U2): the declared length of a sized {@code @dbColumnType} spelling + * ({@code varchar(n)}, {@code character varying(n)}, {@code character(n)}), 0 for a legal bare + * value, or -1 when the value is not legal. Postgres's own spellings, as every port parses them. + */ + public static int dbColumnTypeLength(String value) { + if (value == null) return -1; + if (VALID_DB_COLUMN_TYPES.contains(value)) return 0; + java.util.regex.Matcher m = SIZED_DB_COLUMN_TYPE.matcher(value); + return m.matches() ? Integer.parseInt(m.group(2)) : -1; + } @Override public String getProviderId() { diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java index 2ac2ef2b0a..0ec31953c9 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java +++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ValidationPhase.java @@ -1243,24 +1243,35 @@ private static void validateDbColumnTypeNode(MetaData node) { String value = node.getMetaAttr(CoreDBMetaDataProvider.DB_COLUMN_TYPE, false) .getValueAsString(); - // Rule 1: recognized value. - if (value == null || !CoreDBMetaDataProvider.VALID_DB_COLUMN_TYPES.contains(value)) { + // Rule 1: recognized value (rc.21: the text spellings, sized ones included). + int length = CoreDBMetaDataProvider.dbColumnTypeLength(value); + if (length < 0) { throw new MetaDataException( ErrorMessageConstants.ERR_BAD_ATTR_VALUE + ": field '" + node.getName() + "' @" + CoreDBMetaDataProvider.DB_COLUMN_TYPE + " '" + value + "' is not a valid value; allowed: " - + CoreDBMetaDataProvider.VALID_DB_COLUMN_TYPES, + + CoreDBMetaDataProvider.VALID_DB_COLUMN_TYPES + " and " + + CoreDBMetaDataProvider.DB_COLUMN_TYPE_SIZED_SPELLINGS, ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); } + // Rule 3 (rc.21): a sized spelling holds n characters; a longer @maxLength would let the + // app accept a value the column refuses. ADR-0039: resolving. + if (length > 0 && node.hasMetaAttr("maxLength")) { + Object max = node.getMetaAttr("maxLength").getValue(); + if (max instanceof Number n && n.longValue() > length) { + throw new MetaDataException( + ErrorMessageConstants.ERR_BAD_ATTR_VALUE + + ": field.string '" + node.getName() + "' declares @maxLength: " + n + + " over '@" + CoreDBMetaDataProvider.DB_COLUMN_TYPE + ": " + value + "', which holds " + + length + "; a value the field accepts would not fit the column.", + ErrorCode.ERR_BAD_ATTR_VALUE, node.getSource()); + } + } - // Rule 2: legal (subtype × value) pairing. + // Rule 2: legal (subtype × value) pairing — every value is field.string's. String subType = node.getSubType(); - String requiredSubType = switch (value) { - case CoreDBMetaDataProvider.DB_COLUMN_TYPE_UUID, - CoreDBMetaDataProvider.DB_COLUMN_TYPE_JSONB -> StringField.SUBTYPE_STRING; - default -> null; // unreachable — Rule 1 already rejected unknown values - }; + String requiredSubType = StringField.SUBTYPE_STRING; if (requiredSubType != null && !requiredSubType.equals(subType)) { throw new MetaDataException( ErrorMessageConstants.ERR_BAD_ATTR_VALUE diff --git a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java index 8cf97b9d1f..e45948a0d1 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java +++ b/server/java/metadata/src/main/java/com/metaobjects/object/MetaObject.java @@ -256,6 +256,16 @@ public static void registerEntityValueTypes(MetaDataRegistry registry) { // object.projection, so it survives pruning here while staying off entity/value. def.optionalAttributeWithConstraints(ATTR_FILTER) .ofType(FilterAttribute.SUBTYPE_FILTER).asSingle(); + // rc.21 part B: @union / @unionAll (U15) and @grain / @grainOrdinal (U14), registered + // so a strict load accepts them; the shape rules run in TypeScript and C#. + def.optionalAttributeWithConstraints("union") + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + def.optionalAttributeWithConstraints("unionAll") + .ofType(com.metaobjects.attr.BooleanAttribute.SUBTYPE_BOOLEAN).asSingle(); + def.optionalAttributeWithConstraints("grain") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints("grainOrdinal") + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); }); // FR-044 — object.report: a fixed combination of dimensions and measures of ONE diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java new file mode 100644 index 0000000000..ddc5d7f396 --- /dev/null +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/FunctionOrigin.java @@ -0,0 +1,53 @@ +/* + * Copyright 2026 Doug Mealing LLC dba Meta Objects + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.metaobjects.origin; + +import com.metaobjects.attr.StringAttribute; +import com.metaobjects.registry.MetaDataRegistry; + +/** + * rc.21 part B (U10) — {@code origin.function}: a value computed by a database function the + * project owns, named ({@code @function}, {@code @schema}) and typed by its argument fields + * ({@code @args}). Registered so a strict load accepts it; the call rules run in TypeScript + * and C#, and only the TypeScript view emitter lowers it. + */ +public class FunctionOrigin extends MetaOrigin { + + /** Function origin subtype constant. */ + public static final String SUBTYPE_FUNCTION = "function"; + public static final String ATTR_FUNCTION = "function"; + public static final String ATTR_SCHEMA = "schema"; + public static final String ATTR_ARGS = "args"; + + public FunctionOrigin(String name) { + super(SUBTYPE_FUNCTION, name); + } + + /** Register the concrete {@code origin.function} subtype with the registry. */ + public static void registerTypes(MetaDataRegistry registry) { + registry.registerType(FunctionOrigin.class, def -> { + def.type(TYPE_ORIGIN).subType(SUBTYPE_FUNCTION) + .description("Function origin — a value computed by a database function the project owns") + .inheritsFrom(TYPE_ORIGIN, SUBTYPE_BASE); + def.requiredAttributeWithConstraints(ATTR_FUNCTION) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_SCHEMA) + .ofType(StringAttribute.SUBTYPE_STRING).asSingle(); + def.optionalAttributeWithConstraints(ATTR_ARGS) + .ofType(StringAttribute.SUBTYPE_STRING).asArray(); + }); + } +} diff --git a/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java index 2187d9fb5c..790f65e3b0 100644 --- a/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java +++ b/server/java/metadata/src/main/java/com/metaobjects/origin/OriginTypesMetaDataProvider.java @@ -31,6 +31,7 @@ public void registerTypes(MetaDataRegistry registry) { AggregateOrigin.registerTypes(registry); ComputedOrigin.registerTypes(registry); FirstOrigin.registerTypes(registry); + FunctionOrigin.registerTypes(registry); } @Override diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py index d44f12ed56..020a116211 100644 --- a/server/python/src/metaobjects/core_types.py +++ b/server/python/src/metaobjects/core_types.py @@ -340,6 +340,14 @@ def _register_subtypes( required=False, ) ) + # rc.21 part B: @union / @unionAll (U15), @grain / @grainOrdinal (U14). Registered so a + # strict load accepts them; the shape rules run in TypeScript and C# (see CHANGELOG). + _def.attrs.extend([ + AttrSchema(name="union", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + AttrSchema(name="unionAll", value_type="boolean", required=False), + AttrSchema(name="grain", value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name="grainOrdinal", value_type=ATTR_SUBTYPE_STRING, required=False), + ]) break # FR-044 — object.report: declared dimensions x measures of ONE entity (@from), @@ -1055,6 +1063,22 @@ def _register_subtypes( ) ) +# origin.function (rc.21 part B, U10) — a call of a database function the project owns: +# @function required, @schema and @args optional. Registered so a strict load accepts it. +core_provider.add( + TypeDefinition( + type=TYPE_ORIGIN, + sub_type="function", + factory=MetaOrigin, + attrs=[ + AttrSchema(name="function", value_type=ATTR_SUBTYPE_STRING, required=True), + AttrSchema(name="schema", value_type=ATTR_SUBTYPE_STRING, required=False), + AttrSchema(name="args", value_type=ATTR_SUBTYPE_STRING, required=False, is_array=True), + ], + child_rules=[ChildRule(TYPE_ATTR, "*")], + ) +) + # view.* (base + 13 control kinds). FR-033 — view.currency's @locale is re-homed to # the UI domain provider (`ui_provider`, metaobjects-ui) via TypeRegistry.extend # (ui.json declares @locale on view.currency), matching the TS uiProvider split. Core diff --git a/server/python/src/metaobjects/loader/validation_passes.py b/server/python/src/metaobjects/loader/validation_passes.py index 1e091d26d5..a0fbcf71e0 100644 --- a/server/python/src/metaobjects/loader/validation_passes.py +++ b/server/python/src/metaobjects/loader/validation_passes.py @@ -64,6 +64,8 @@ DB_COLUMN_TYPE_UUID, FIELD_ATTR_DB_COLUMN_TYPE, VALID_DB_COLUMN_TYPES, + DB_COLUMN_TYPE_SIZED_SPELLINGS, + parse_db_column_type, ) from ..meta.core.object.meta_object import MetaObject from ..meta.core.relationship.meta_relationship import MetaRelationship @@ -1016,21 +1018,35 @@ def _validate_db_column_type(root: MetaData, errors: list[MetaError]) -> None: if not isinstance(value, str): continue - # Rule 1: recognized value. - if value not in VALID_DB_COLUMN_TYPES: + # Rule 1: recognized value (rc.21: the text spellings, sized ones included). + parsed = parse_db_column_type(value) + if parsed is None: errors.append( MetaError( f"field '{node.name}' attribute '@{FIELD_ATTR_DB_COLUMN_TYPE}' " f"value {value!r} is not a valid value; allowed: " - f"{', '.join(VALID_DB_COLUMN_TYPES)}", + f"{', '.join((*VALID_DB_COLUMN_TYPES, *DB_COLUMN_TYPE_SIZED_SPELLINGS))}", ErrorCode.ERR_BAD_ATTR_VALUE, envelope=node.source, ) ) continue + # Rule 3 (rc.21): a sized spelling holds n characters; a longer @maxLength (resolving) + # would let the app accept a value the column refuses. + max_length = node.get_meta_attr(FIELD_ATTR_MAX_LENGTH) + if parsed[1] is not None and isinstance(max_length, int) and max_length > parsed[1]: + errors.append( + MetaError( + f"field.string '{node.name}' declares @{FIELD_ATTR_MAX_LENGTH}: {max_length} over " + f"'@{FIELD_ATTR_DB_COLUMN_TYPE}: {value}', which holds {parsed[1]}; a value the field " + f"accepts would not fit the column.", + ErrorCode.ERR_BAD_ATTR_VALUE, + envelope=node.source, + ) + ) - # Rule 2: legal (subtype × value) pairing. - required_subtype = _DB_COLUMN_TYPE_REQUIRED_SUBTYPE[value] + # Rule 2: legal (subtype × value) pairing — every value is field.string's. + required_subtype = FIELD_SUBTYPE_STRING if node.sub_type != required_subtype: # Derive the allowed-pairings list from the map so it stays the single # source of truth for pairing legality. diff --git a/server/python/src/metaobjects/meta/core/object/object_constants.py b/server/python/src/metaobjects/meta/core/object/object_constants.py index b913d1964e..a091eeb5d9 100644 --- a/server/python/src/metaobjects/meta/core/object/object_constants.py +++ b/server/python/src/metaobjects/meta/core/object/object_constants.py @@ -30,6 +30,11 @@ # the SAME attr subtype as origin.aggregate's @filter) that lowers to an outer # SQL WHERE. Mirrors TS object-constants.ts OBJECT_PROJECTION_ATTR_FILTER. OBJECT_PROJECTION_ATTR_FILTER = "filter" +# rc.21 part B: a projection UNIONed with others (U15), one with a row per array element (U14). +OBJECT_PROJECTION_ATTR_UNION = "union" +OBJECT_PROJECTION_ATTR_UNION_ALL = "unionAll" +OBJECT_PROJECTION_ATTR_GRAIN = "grain" +OBJECT_PROJECTION_ATTR_GRAIN_ORDINAL = "grainOrdinal" # --------------------------------------------------------------------------- # FR-044 — object.report attrs. Mirrors TS object-constants.ts. diff --git a/server/python/src/metaobjects/meta/persistence/db/db_constants.py b/server/python/src/metaobjects/meta/persistence/db/db_constants.py index 6fc5ee76f2..bfbb99532a 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_constants.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_constants.py @@ -54,10 +54,39 @@ # The closed set of legal @dbColumnType values. ADR-0036 Wave 2 retires # timestamp_with_tz — the legal set is now just { uuid, jsonb }, both on field.string. +# rc.21 part B (U2): the text spellings, all on field.string; the sized ones are parsed. +DB_COLUMN_TYPE_TEXT = "text" +DB_COLUMN_TYPE_VARCHAR = "varchar" +DB_COLUMN_TYPE_CHARACTER_VARYING = "character varying" VALID_DB_COLUMN_TYPES = ( DB_COLUMN_TYPE_UUID, DB_COLUMN_TYPE_JSONB, + DB_COLUMN_TYPE_TEXT, + DB_COLUMN_TYPE_VARCHAR, + DB_COLUMN_TYPE_CHARACTER_VARYING, ) +DB_COLUMN_TYPE_SIZED_SPELLINGS = ("varchar(n)", "character varying(n)", "character(n)") + +import re as _re + +_SIZED_DB_COLUMN_TYPE = _re.compile(r"^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$") + + +def parse_db_column_type(value: str) -> tuple[str, int | None] | None: + """rc.21 part B (U2): parse a @dbColumnType value to (kind, length), or None when it is + not legal. Postgres's own spellings, matched exactly, as every port parses them.""" + if value == DB_COLUMN_TYPE_UUID: + return ("uuid", None) + if value == DB_COLUMN_TYPE_JSONB: + return ("jsonb", None) + if value == DB_COLUMN_TYPE_TEXT: + return ("text", None) + if value in (DB_COLUMN_TYPE_VARCHAR, DB_COLUMN_TYPE_CHARACTER_VARYING): + return ("varchar", None) + m = _SIZED_DB_COLUMN_TYPE.match(value) + if m is None: + return None + return ("char" if m.group(1) == "character" else "varchar", int(m.group(2))) # --------------------------------------------------------------------------- # DB-domain physical attrs on identity subtypes (RDB index / FK-constraint diff --git a/server/python/src/metaobjects/meta/persistence/db/db_provider.py b/server/python/src/metaobjects/meta/persistence/db/db_provider.py index cba60c9076..0c554df486 100644 --- a/server/python/src/metaobjects/meta/persistence/db/db_provider.py +++ b/server/python/src/metaobjects/meta/persistence/db/db_provider.py @@ -65,7 +65,7 @@ name=FIELD_ATTR_DB_COLUMN_TYPE, value_type=ATTR_SUBTYPE_STRING, required=False, - allowed_values=VALID_DB_COLUMN_TYPES, + # rc.21 part B (U2): no allowed_values — the sized spellings are no closed set. ) # @localTime — boolean opt-out into a naive / wall-clock timestamp (ADR-0036 Wave diff --git a/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py b/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py index 6097df59c5..4453c8f18b 100644 --- a/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py +++ b/server/python/src/metaobjects/meta/persistence/origin/origin_constants.py @@ -15,13 +15,19 @@ # @via, projecting @of. ORIGIN_SUBTYPE_COMPUTED = "computed" ORIGIN_SUBTYPE_FIRST = "first" +# rc.21 part B (U10): a value computed by a database function the project owns. +ORIGIN_SUBTYPE_FUNCTION = "function" ORIGIN_SUBTYPES = ( SUBTYPE_BASE, ORIGIN_SUBTYPE_PASSTHROUGH, ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ) +ORIGIN_ATTR_FUNCTION = "function" +ORIGIN_ATTR_SCHEMA = "schema" +ORIGIN_ATTR_ARGS = "args" # #210 — the ASSEMBLY origins: they derive a value by rolling up, computing, or # collecting from a backing store, which is what an object.projection is for. @@ -33,6 +39,7 @@ ORIGIN_SUBTYPE_AGGREGATE, ORIGIN_SUBTYPE_COMPUTED, ORIGIN_SUBTYPE_FIRST, + ORIGIN_SUBTYPE_FUNCTION, ) # passthrough attrs From e9ecb82d49f8c61c995a4616918d1ff2583ed60f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 18:56:11 -0500 Subject: [PATCH 193/267] fix(views): extenders keep their super's identity anchor; a unique reverse hop is to-one for a passthrough A projection that extends another and declares no identity of its own now keeps the identity its super anchors with, so a projection over a TPH root can add a subtype's column without moving its base to the subtype; a field bound to a TPH relative of the base reads the shared table's column. A reference walked backwards is to-one for a passthrough when its holder declares an identity.primary or identity.secondary over exactly its fields; an aggregate over it stays legal. TypeScript (loader and view emitter) and C# (loader). Co-Authored-By: Claude Opus 5.5 --- .../ViewVocabularyRc21LoaderTests.cs | 25 +++++++ .../MetaObjects/Loader/ValidationPasses.cs | 52 +++++++++++++- .../src/projection/extract-view-spec.ts | 22 +++++- .../projection/rc21b-view-vocabulary.test.ts | 72 +++++++++++++++++++ .../metadata/src/loader/validation-passes.ts | 52 ++++++++++++-- 5 files changed, 214 insertions(+), 9 deletions(-) diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index db409453ba..569679a467 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -162,4 +162,29 @@ public void The_db_column_type_text_spellings_load_and_an_oversize_max_length_is { "field.string": { "name": "c", "@dbColumnType": "VARCHAR" } }, { "identity.primary": { "name": "id", "@fields": "id" } } ] } } """); } + + // rc.21 part B: a passthrough walks a reference backwards when its holder declares a unique identity over its fields. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_passthrough_over_a_reverse_hop_needs_a_unique_identity(bool unique) + { + var secondary = unique ? """{ "identity.secondary": { "name": "events_order_uq", "@fields": "orderId" } },""" : ""; + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Order", "children": [ { "source.rdb": { "@table": "orders" } }, { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Receipt", "children": [ { "source.rdb": { "@table": "receipts" } }, { "field.long": { "name": "id" } }, + { "field.long": { "name": "orderId" } }, { "field.string": { "name": "note" } }, { "identity.primary": { "@fields": "id" } }, {{secondary}} + { "identity.reference": { "name": "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, + { "object.projection": { "name": "V", "children": [ { "source.rdb": { "@kind": "view", "@view": "v" } }, + { "field.long": { "name": "id", "extends": "Order.id" } }, + { "field.string": { "name": "note", "children": [ { "origin.passthrough": { "@from": "Receipt.note", "@via": "Order.receipts" } } ] } }, + { "identity.primary": { "name": "id", "extends": "Order.primary" } } ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var errors = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "r.json")]).Errors; + if (unique) Assert.Empty(errors); + else Assert.Contains(errors, e => e.Code.ToString() == "ERR_ORIGIN_CARDINALITY"); + } } diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 51f9be9c2a..b7c4bbd89e 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1272,13 +1272,44 @@ private static bool IsReferenceHop(MetaData hop) /// A hop's effective @cardinality, or null when not declared. A reference hop /// (a forward FK) is inherently to-one — a child names the parent it points at. - private static string? HopCardinality(MetaData rel, IReadOnlySet? reverse = null) + private static string? HopCardinality(MetaData rel, IReadOnlySet? reverse = null, bool uniqueReverseIsOne = false) => reverse is not null && reverse.Contains(rel) - ? CARDINALITY_MANY // R-walk: a reference walked backwards reaches every row that references the walked-from one + // R-walk: a reference walked backwards reaches every row that references the walked-from one — + // unless (rc.21 part B) its holder declares a unique identity over exactly its fields. + // (only a passthrough asks: an aggregate over such a hop stays legal, as it was). + ? (uniqueReverseIsOne && ReverseHopIsUnique(rel) ? CARDINALITY_ONE : CARDINALITY_MANY) : IsReferenceHop(rel) ? CARDINALITY_ONE : rel.Attr(RELATIONSHIP_ATTR_CARDINALITY) as string; + /// The field names an identity or reference declares (@fields), sorted. + private static string IdentityFieldSet(MetaData node) + { + var raw = node.Attr(IDENTITY_ATTR_FIELDS); + IEnumerable list = raw switch + { + IReadOnlyList l => l.Select(x => x?.ToString() ?? ""), + string s => s.Split(','), + _ => [], + }; + return string.Join(",", list.Select(f => f.Trim()).Where(f => f.Length > 0).OrderBy(f => f, StringComparer.Ordinal)); + } + + /// + /// rc.21 part B: whether a reference walked backwards reaches at most one row — its holder declares + /// (resolving) an identity.primary or identity.secondary over exactly the reference's fields. TS + /// _reverseHopIsUnique. + /// + private static bool ReverseHopIsUnique(MetaData rel) + { + if (rel.Parent is not { } holder) return false; + var fields = IdentityFieldSet(rel); + if (fields.Length == 0) return false; + return holder.Children().Any(c => c.Type == TYPE_IDENTITY + && (c.SubType == IDENTITY_SUBTYPE_PRIMARY || c.SubType == IDENTITY_SUBTYPE_SECONDARY) + && IdentityFieldSet(c) == fields); + } + /// FR-024: the entity NAMED by a node's dotted extends ref — the OWNER part /// of `....` resolved as an object. Differs from /// SuperData.Parent when the resolved child is INHERITED. @@ -1299,6 +1330,14 @@ private static bool IsReferenceHop(MetaData hop) /// Derive the BASE entity a no-`@via` origin path anchors at (spec §5). /// Returns null when no base is derivable (an error has been pushed). + /// rc.21 part B: whether a projection (or one it extends) anchors its base with an extended identity. + private static bool AnchorsByIdentity(MetaData obj) + { + // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. + if (obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY && c.SuperData is { Type: TYPE_IDENTITY })) return true; + return obj.SuperData is { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } sup && AnchorsByIdentity(sup); + } + private static MetaData? DeriveBaseEntity( MetaData obj, MetaData root, string fieldName, ErrorSource originSource, List errors) { @@ -1320,6 +1359,13 @@ private static bool IsReferenceHop(MetaData hop) } } + // 1b) rc.21 part B (G13): an extender with no identity of its own keeps the identity its super + // anchors with, so its own fields (a TPH subtype's columns, say) do not move the base. + if (!obj.OwnChildren().Any(c => c.Type == TYPE_IDENTITY) + && obj.SuperData is { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } anchoredSuper + && AnchorsByIdentity(anchoredSuper)) + return DeriveBaseEntity(anchoredSuper, root, fieldName, originSource, errors); + // 2) Fallback: the single distinct entity targeted by plain field-extends — // preferring the ref-named owner over the physical declaring ancestor. var targets = new HashSet(); @@ -1412,7 +1458,7 @@ private static void CheckPassthroughCardinality( { foreach (var rel in hops) { - if (HopCardinality(rel, reverse) == CARDINALITY_MANY) + if (HopCardinality(rel, reverse, uniqueReverseIsOne: true) == CARDINALITY_MANY) { errors.Add(new MetaError( $"origin.passthrough on {obj.Name}.{fieldName}: @via hop \"{rel.Name}\" is to-many " + diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts index eeb17f85ac..1aba835078 100644 --- a/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts +++ b/server/typescript/packages/codegen-ts/src/projection/extract-view-spec.ts @@ -98,7 +98,7 @@ import { // #213 — a write-through ENTITY (FR-024 §7 read-view) hosts its own view; the base // is the entity itself, not an extends-anchored projection. import { isWriteThrough } from "./projection-detector.js"; -import { tphDiscriminatorBase, tphDiscriminatorPin } from "../tph.js"; +import { tphDiscriminatorBase, tphDiscriminatorPin, tphStorageObject } from "../tph.js"; // #209 — the SAME NOT-NULL predicate that drives a column's `.notNull()` decides // whether a belongs-to join is INNER (required FK) vs LEFT OUTER (nullable FK). import type { ColumnNamingStrategy } from "../metaobjects-config.js"; @@ -749,6 +749,13 @@ function baseEntityFor( const named = refNamedOwner(identity, root); if (named !== undefined) return named; } + // rc.21 part B (G13): an extender with no identity of its own keeps its super's identity anchor, so its + // own fields (a TPH subtype's columns, say) do not move the base (mirrors the loader's _deriveBaseEntity). + const supAnchor = projection.superResolved; + if (!projection.ownChildren().some((c) => c.type === TYPE_IDENTITY) && supAnchor !== undefined && isMetaObject(supAnchor) + && supAnchor.subType === OBJECT_SUBTYPE_PROJECTION && anchorsByIdentity(supAnchor, root)) { + return baseEntityFor(supAnchor, root); + } const targets = new Set(); // ADR-0039: own — see above; base-entity derivation reads own extends-bound fields. for (const f of projection.ownChildren().filter((c) => c.type === TYPE_FIELD)) { @@ -769,6 +776,14 @@ function baseEntityFor( ); } +/** rc.21 part B: whether a projection (or a projection it extends) anchors its base with an extended identity. */ +function anchorsByIdentity(projection: MetaObject, root: MetaRoot): boolean { + // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. + if (projection.ownChildren().some((c) => c.type === TYPE_IDENTITY && refNamedOwner(c, root) !== undefined)) return true; + const sup = projection.superResolved; + return sup !== undefined && isMetaObject(sup) && sup.subType === OBJECT_SUBTYPE_PROJECTION && anchorsByIdentity(sup, root); +} + export function sourceColumnNameFor( entityField: MetaData, ctx: ExtractContext, @@ -818,7 +833,10 @@ function baseColumnNameFor( ): string { const target = field.superData; if (target === undefined) return sourceColumnNameFor(field, ctx); - if (refNamedOwner(field, root) !== base) return sourceColumnNameFor(field, ctx); + const owner = refNamedOwner(field, root); + // rc.21 part B: a field bound to a TPH relative of the base (a subtype's column of a projection over the + // TPH root) is a column of the same shared table, so it reads that column too. + if (owner !== base && (owner === undefined || tphStorageObject(owner) !== tphStorageObject(base))) return sourceColumnNameFor(field, ctx); return sourceColumnNameFor(target, ctx); } diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts index 49a85022c4..0f745c739a 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -206,3 +206,75 @@ describe("U15 @union", () => { } }); }); + +// rc.21 part B: two fixes the vocabulary needed to build its motivating views. +describe("a projection over a TPH root reads its subtypes' columns; a unique reverse hop is to-one", () => { + const tph = [ + { "object.entity": { name: "Grant", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "grants" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "kind", "@maxLength": 10 } }, + { "field.long": { name: "cardId" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "PriorGrant", extends: "Grant", "@discriminatorValue": "PRIOR", children: [ + { "field.string": { name: "integrationKey" } } ] } }, + { "object.entity": { name: "Card", children: [ + { "source.rdb": { "@table": "cards" } }, + { "field.long": { name: "id" } }, + { "field.string": { name: "number" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "CardGrant", children: [ + { "source.rdb": { "@table": "card_grants" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "cardId" } }, + { "field.string": { name: "note" } }, + { "identity.primary": { "@fields": "id" } }, + { "identity.reference": { name: "cardId", "@fields": "cardId", "@references": "Card" } } ] } }, + ]; + async function load(extra: unknown[]) { + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [...tph, ...extra] } }))]); + return { root, errors: errors.map((e) => e.message) }; + } + test("an extender with no identity keeps the super's anchor, and a subtype column reads the shared table", async () => { + const { root, errors } = await load([ + { "object.projection": { name: "GrantBase", abstract: true, children: [ + { "field.long": { name: "grantId", extends: "Grant.id" } }, + { "identity.primary": { name: "id", extends: "Grant.primary" } } ] } }, + { "object.projection": { name: "GrantRow", extends: "GrantBase", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_grants" } }, + { "field.string": { name: "externalKey", extends: "PriorGrant.integrationKey" } } ] } }, + ]); + expect(errors).toEqual([]); + const sql = buildProjectionViews(root, { dialect: "postgres" })[0]!.sql; + expect(sql).toContain("g.id AS grant_id"); + expect(sql).toContain("g.integration_key AS external_key"); + expect(sql).toContain("FROM public.grants g"); + expect(sql).not.toContain("'PRIOR'"); + }); + const viaCard = (unique: boolean) => [ + { "object.entity": { name: "CardGrant", children: [ + { "source.rdb": { "@table": "card_grants" } }, + { "field.long": { name: "id" } }, + { "field.long": { name: "cardId" } }, + { "field.string": { name: "note" } }, + { "identity.primary": { "@fields": "id" } }, + ...(unique ? [{ "identity.secondary": { name: "card_grants_card_uq", "@fields": "cardId" } }] : []), + { "identity.reference": { name: "cardId", "@fields": "cardId", "@references": "Card" } } ] } }, + ]; + test("a passthrough over a reverse hop loads when the holder's reference fields are a unique identity, and only then", async () => { + const projection = { "object.projection": { name: "CardRow", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_cards" } }, + { "field.long": { name: "id", extends: "Card.id" } }, + { "field.string": { name: "note", children: [ { "origin.passthrough": { "@from": "CardGrant.note", "@via": "Card.cardGrants" } } ] } }, + { "identity.primary": { name: "id", extends: "Card.primary" } } ] } }; + const withUnique = async (unique: boolean) => { + const doc = { "metadata.root": { package: "acme", children: [...tph.slice(0, 3), ...viaCard(unique), projection] } }; + const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); + return { root, errors: errors.map((e) => e.message) }; + }; + const ok = await withUnique(true); + expect(ok.errors).toEqual([]); + expect(buildProjectionViews(ok.root, { dialect: "postgres" })[0]!.sql).toContain("LEFT OUTER JOIN public.card_grants c0 ON c0.card_id = c.id"); + expect((await withUnique(false)).errors.some((m) => /is to-many/.test(m))).toBe(true); + }); +}); diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 632892e112..bb8be747f5 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -877,14 +877,40 @@ function _validateViaPath( /** A hop's effective @cardinality, or undefined when not declared. A reference * hop (a forward FK) is inherently to-one — a child names the parent it points at. */ -function _hopCardinality(rel: MetaData, reverse?: ReadonlySet): string | undefined { - // R-walk: a reference walked backwards reaches every row that references the walked-from one. - if (reverse?.has(rel) === true) return CARDINALITY_MANY; +function _hopCardinality(rel: MetaData, reverse?: ReadonlySet, uniqueReverseIsOne = false): string | undefined { + // R-walk: a reference walked backwards reaches every row that references the walked-from one — + // unless (rc.21 part B) its holder declares a unique identity over exactly the reference's fields, + // so at most one row references it: then a passthrough may walk it (the aggregate rule keeps calling + // it to-many: an aggregate over it stays legal, as it was). + if (reverse?.has(rel) === true) return uniqueReverseIsOne && _reverseHopIsUnique(rel) ? CARDINALITY_ONE : CARDINALITY_MANY; if (_isReferenceHop(rel)) return CARDINALITY_ONE; const v = rel.attr(RELATIONSHIP_ATTR_CARDINALITY); return typeof v === "string" ? v : undefined; } +/** The field names an identity or reference declares (`@fields`, a string or a list). */ +function _identityFieldSet(node: MetaData): string[] { + const raw = node.attr(IDENTITY_ATTR_FIELDS); + const list = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : []; + return list.map((f) => String(f).trim()).filter((f) => f.length > 0).sort(); +} + +/** + * rc.21 part B: whether a reference walked backwards reaches at most one row — its holder (or an + * ancestor it inherits identities from) declares an identity.primary or identity.secondary whose + * fields are exactly the reference's fields. Derived from the model; no new vocabulary. + */ +function _reverseHopIsUnique(rel: MetaData): boolean { + const holder = rel.parent; + if (holder === undefined) return false; + const fields = _identityFieldSet(rel).join(","); + if (fields === "") return false; + // ADR-0039: resolving — a unique identity may be inherited. + return holder.children().some((c) => c.type === TYPE_IDENTITY + && (c.subType === IDENTITY_SUBTYPE_PRIMARY || c.subType === IDENTITY_SUBTYPE_SECONDARY) + && _identityFieldSet(c).join(",") === fields); +} + /** * Derive the BASE entity a no-`@via` origin path anchors at (spec §5): * - an entity (or any non-projection host) is its own base — derived fields @@ -945,6 +971,16 @@ function _deriveBaseEntity( } } + // 1b) rc.21 part B (G13): a projection that extends another projection and declares no identity of + // its own keeps the identity its super anchors with: the inherited identity still names the base, + // so an extender's own fields (a TPH subtype's columns, say) do not move it. + const ownIdentity = obj.ownChildren().some((c) => c.type === TYPE_IDENTITY); + const superProjection = obj.superResolved; + if (!ownIdentity && superProjection !== undefined && superProjection.type === TYPE_OBJECT + && superProjection.subType === OBJECT_SUBTYPE_PROJECTION && _anchorsByIdentity(superProjection)) { + return _deriveBaseEntity(superProjection, root, fieldName, originSource, errors); + } + // 2) Fallback: the single distinct entity targeted by plain field-extends — // again preferring the ref-named owner over the physical declaring ancestor. const targets = new Set(); @@ -993,6 +1029,14 @@ function _deriveBaseEntity( return undefined; } +/** rc.21 part B: whether a projection (or a projection it extends) anchors its base with an extended identity. */ +function _anchorsByIdentity(obj: MetaData): boolean { + // ADR-0039: own — an anchor is a locally declared extends-bound identity, at some level of the chain. + if (obj.ownChildren().some((c) => c.type === TYPE_IDENTITY && c.superResolved?.type === TYPE_IDENTITY)) return true; + const sup = obj.superResolved; + return sup !== undefined && sup.type === TYPE_OBJECT && sup.subType === OBJECT_SUBTYPE_PROJECTION && _anchorsByIdentity(sup); +} + /** * True when the `@from`/`@of` target entity IS the host's base relation: the * derived base entity itself, or an ancestor on the base's (or the host's) @@ -1087,7 +1131,7 @@ function _checkPassthroughCardinality( reverse?: ReadonlySet, ): void { for (const rel of hops) { - if (_hopCardinality(rel, reverse) === CARDINALITY_MANY) { + if (_hopCardinality(rel, reverse, true) === CARDINALITY_MANY) { errors.push( new ParseError( `origin.passthrough on ${obj.name}.${fieldName}: @via hop "${rel.name}" is to-many ` + From 8fb61841bd0385597b66a889bf709b068142193f Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 18:56:14 -0500 Subject: [PATCH 194/267] docs(views): the rc.21 view vocabulary, and its CHANGELOG entries Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 56 ++++++++++++++++++++++++++++- docs/features/relationships.md | 65 ++++++++++++++++++++++++++++++++++ 2 files changed, 120 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ceba25175..b1a5add696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,9 @@ here.** ## [Unreleased] **`metamodelVersion` moves to `1.3`.** This release adds vocabulary (`field.duration`, -`@constraintName`, `@dbCheck`, `@stringValueMap`, `@condition`, `atLeastOne @max`, `@sequenceStart`, `@sequenceName`, +`@constraintName`, `@dbCheck`, `@stringValueMap`, the rc.21 view vocabulary (`origin.function`, `@union`, +`@unionAll`, `@grain`, `@grainOrdinal`, the text `@dbColumnType` spellings, and the `cast` node and function +set of `attr.expression`), `@condition`, `atLeastOne @max`, `@sequenceStart`, `@sequenceName`, `@flattenedColumnPrefix`, the `pascal` column rule, and `@dbSetName`, a C#-only attr) and nothing that loaded before stops loading. The registry gains two fields on a type or attr entry, carried into the registry manifest: `implementedIn` (kind 1: cross-port vocabulary only the named ports @@ -23,6 +25,40 @@ vocabulary; upgrade every port together. ### Added +- **The rc.21 view vocabulary: what a projection needs to replace a hand-written `@sql` view.** + Every construct is closed and typed, never free SQL; the TypeScript view emitter lowers them on + Postgres and SQLite (SQLite spells each with its own functions, or refuses what it cannot mean), + C# validates them at load with the TypeScript rules, and Java and Python register them so a + strict load accepts them. In `attr.expression`: `{ cast: , as: , + dbColumnType? }` (an enum casts to an integer only when stored as one, `@intValueMap`, which is + how an int-stored enum and an int share a `case`); the functions `greatest`, `least`, `nullif`, + `lower`, `upper`, `btrim`, `splitPart`, `concat`, `concatWs`, `substring`, `replace`, `left`, + `right` and `length` beside `coalesce`, each argument typed; a `{ field }` ref to a scalar + `origin.aggregate` (read on the grouped row, not filterable); and, on a projection, a path of + to-one hops (`"patientId.currentMailingAddressId"`) in an expression or as a correlated + `@filter` operand, joined but not output. `origin.function` (`@function`, `@schema`, `@args`) + is a value computed by a database function the project owns, typed by its argument fields and + its carrying field; declared on an entity it is entity-derived (Postgres only). On + `object.projection`: `@grain` / `@grainOrdinal`, one row per element of a jsonb `field.object` + array, its members read through `origin.passthrough @from: .`; and + `@union` / `@unionAll`, a view that is the UNION (or UNION ALL) of projections of one shape, + checked at load. `@dbColumnType` takes the text spellings `text`, `varchar`, `character + varying`, `varchar(n)`, `character varying(n)` and `character(n)` on a `field.string` (`meta + migrate`, Drizzle, the C# EF context and the view cast honour them; a `@maxLength` over n is + refused), and the registry drops its `allowedValues`. A cross-field `@condition` takes only + the CHECK subset of the grammar (fields, literals, comparisons, null tests, and/or/not, + coalesce), refused at load otherwise. Rulings: the cast names a field subtype, the type + `@convert` casts to, with an optional text spelling; two-word functions are camelCase + (`splitPart`, `concatWs`) and `btrim` keeps Postgres's name; `concat` ignores NULLs, as SQL's + `concat()` does, and there is no separate NULL-propagating `||`; a union defaults to UNION, + SQL's own default. Fixtures `fixtures/conformance/projection-view-vocabulary-rc21` and + `error-origin-function-free-sql`, `error-projection-union-shape`, + `error-projection-grain-not-object-array`, `error-computed-cast-enum-not-int-stored`, + `error-db-column-type-sized-max-length`; the live run is + `integration-tests/test/view-vocabulary-rc21-pg.test.ts`. **Upgrade note:** `meta migrate` now + reads a Postgres `character(n)` column as itself, so a model that declared a plain + `field.string` over one sees a type change until it declares `@dbColumnType: character(n)`. + - **`@stringValueMap`: a field.enum member's stored string (rc.21).** A string-stored enum may declare the string each member is stored as, `{ member: string }`, for a legacy column whose spelling differs from the member symbols (lowercase `draft`, `LEGACY_A`). The generated native @@ -584,6 +620,24 @@ vocabulary; upgrade every port together. ### Fixed +- **Fix, TypeScript and C#: a projection that extends another keeps its super's identity anchor + (rc.21).** An extender that declared no identity of its own took its base from its own fields' + `extends`, so a projection over a TPH root that added a subtype's column moved its base to the + subtype (and its view to that subtype's rows). It now keeps the identity its super anchors with. + And a field bound to a TPH relative of the base reads the shared table's column, where it read a + column named after the projection field. + +- **Fix, TypeScript and C#: a passthrough may walk a reference backwards when at most one row + references it (rc.21).** A reverse hop was always to-many, so a passthrough over it was refused + (`ERR_ORIGIN_CARDINALITY`). When the holder declares an `identity.primary` or + `identity.secondary` over exactly the reference's fields, the hop is to-one for a passthrough; + an aggregate over it stays legal. + +- **Fix, TypeScript: a grouped view groups the joined columns its expressions read (rc.21).** A + computed column or an `origin.first` correlation that read a joined column outside an + aggregate was not in the GROUP BY; Postgres refused the view. The base row's columns stay out + (its primary key is grouped). + - **Fix, C#: a reference over a flattened member configures the owned type's own navigation (rc.21, U6).** `identity.reference { @fields: address.countryId, @references: Country }` emitted `OwnsOne(x => x.Address).HasOne().WithMany().HasForeignKey(e => e.CountryId)`. When the diff --git a/docs/features/relationships.md b/docs/features/relationships.md index bbaf7b7cbe..3e6a3880e4 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -244,6 +244,71 @@ boolean on `Patient` declared as `origin.first { @via: Patient.consents, @segmen `fixtures/conformance/entity-derived-hipaa-gate` pins the metadata; `codegen-ts/test/projection/hipaa-gate-entity-derived.test.ts` pins the view and runs it. +### rc.21: the rest of what a view needs + +These constructs let a projection build the views that needed a hand-written `@sql` body. Every +one is a closed, typed construct: nothing is free SQL. Only the TypeScript view emitter lowers +them (C# validates them at load; Java and Python accept them under strict load). + +**A cast** (`{ cast: , as: , dbColumnType? }`). `as` is one of `string`, +`int`, `long`, `double`, `float`, `decimal`, `boolean`, `date`, `timestamp`, `uuid`, and the +column type is that subtype's. A string cast may name a text `@dbColumnType` spelling (`text`, +`varchar`, `character varying`, `varchar(n)`, `character varying(n)`, `character(n)`): a typed +NULL of an unbounded varchar is `{ cast: { value: null }, as: string, dbColumnType: varchar }`. +An enum casts to an integer only when it is stored as one (`@intValueMap`), which is also how an +int-stored enum and an int meet in one `case`: `then: { cast: { field: status }, as: int }`. + +**Functions** (`{ fn, args }`). Beside `coalesce`: `greatest` and `least` (ordered arguments of +one type), `nullif` (two of one type), `lower`, `upper`, `btrim` (a string, optionally the +characters), `splitPart` (string, delimiter, integer), `concat` (scalars; NULL reads as empty), +`concatWs` (a separator, then scalars), `substring` (string, start, optional length), `replace`, +`left` and `right` (string, integer), and `length` (string to int). Each argument is typed; a +NULL literal fits any. On SQLite each is spelled with SQLite's own functions where the meaning +is the same (`greatest` keeps Postgres's NULL-skipping), and refused where it is not: +`splitPart` beyond the first part. + +**A path in an expression or an operand.** On a projection, `{ field: "patientId.currentMailingAddressId" }` +in an `origin.computed` expression, or `{ field: "taskId.caseId" }` as a correlated operand in an +origin's `@filter`, is a path of to-one hops from the base and a field of the entity reached: +the view joins it without outputting it. + +**An expression over an aggregate.** `{ field }` may name a scalar `origin.aggregate` of the +projection (`count`/`sum`/`avg`/`min`/`max`, `any`/`all`), read on the grouped row: +`{ fn: greatest, args: [ { field: updatedAt }, { field: lastEvent } ] }`. Such a value is not +filterable (it exists only after grouping). A grouped view also groups every joined column its +expressions read. + +**A database function the project owns** (`origin.function`). `@function` and `@schema` name it +(plain identifiers), `@args` the fields passed to it in order; each argument is typed by its +field and the result by the carrying field's subtype. Declared on an entity, it is +entity-derived: a projection reaching the entity reads it like any derived field. MetaObjects +never creates the function (it is owned SQL, created before the view). Postgres only. + +```yaml +- field.int: + name: consentState + children: [ { origin.function: { "@function": compute_consent_state, "@schema": app, "@args": [id] } } ] +``` + +**One row per array element** (`@grain`, `@grainOrdinal`). A projection whose `@grain` names a +base-entity `field.object` array stored as jsonb has one row per element (`jsonb_array_elements +… WITH ORDINALITY` on Postgres, `json_each` on SQLite); a base row with no element has no row. A +field whose `origin.passthrough @from` names the array's value object (`Contact.kind`) reads that +member of the element, cast to the field's type; the base's own fields read the parent row. +`@grainOrdinal` names a `field.int`/`field.long` of the projection that holds the 1-based +position. No `origin.aggregate` on such a projection. + +**A union** (`@union`, `@unionAll`). A projection that extends one branch and names the others in +`@union` is the UNION of their rows; each branch has its own base, joins and `@filter`, and every +branch has the same fields in order (name, subtype, array-ness, `@column`), checked at load +(`ERR_BAD_ATTR_VALUE`). Duplicates are removed (UNION, SQL's default) unless `@unionAll: true`. + +**Two related rules.** A reference walked backwards is to-one for a passthrough when its holder +declares a unique identity (`identity.primary` or `identity.secondary`) over exactly its fields. +And a projection that extends another and declares no identity of its own keeps the identity its +super anchors with, so a TPH root's projection can add a subtype's column and still read the +root's shared table. + ## When one entity has two references to the same target An entity may legitimately declare more than one `identity.reference` onto the same From 0da6151bb2020e749f789f57ce1a7f667c45bc2d Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:10:54 -0500 Subject: [PATCH 195/267] chore(templates): the Drizzle template reaches fitPgIdentifier through the engine; resync the owned copies Owned template copies import only @metaobjectsdev/codegen-ts/engine, so the Postgres identifier fit is re-exported there (an engine module) and the CheckEntry type sits below the imports, where the eject rewrite expects them. The owned copies are resynced. Co-Authored-By: Claude Opus 5.5 --- .../codegen/templates/drizzle-schema.ts | 40 ++++++++++++++++--- .../codegen/templates/drizzle-schema.ts | 40 ++++++++++++++++--- .../packages/codegen-ts/src/engine-surface.ts | 1 + .../packages/codegen-ts/src/engine.ts | 1 + .../packages/codegen-ts/src/pg-identifier.ts | 3 ++ .../src/templates/drizzle-schema.ts | 8 ++-- .../src/templates/drizzle-schema.ts | 40 ++++++++++++++++--- 7 files changed, 111 insertions(+), 22 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/src/pg-identifier.ts diff --git a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts index 64434dc4c9..b0378ef6e3 100644 --- a/examples/advanced-modeling/codegen/templates/drizzle-schema.ts +++ b/examples/advanced-modeling/codegen/templates/drizzle-schema.ts @@ -27,6 +27,7 @@ import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/codegen-ts/engine"; import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; @@ -36,6 +37,9 @@ import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-dis import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -177,7 +181,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -191,7 +195,7 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); @@ -204,6 +208,8 @@ export function renderDrizzleSchema( expr: names === undefined || values === undefined ? code`${spec.checkConstraint ?? ""}` : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", }; } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which @@ -212,6 +218,8 @@ export function renderDrizzleSchema( return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -220,6 +228,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -392,6 +402,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -766,7 +792,7 @@ function renderColumn( */ function guardedSiblingEnumChecks( obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, -): Array<{ name: Code; expr: Code }> | undefined { +): CheckEntry[] | undefined { const plan = tphPlan(obj, ctx.loadedRoot); if (plan === null) return undefined; const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); @@ -792,7 +818,7 @@ function guardedSiblingEnumChecks( const stored = disc === undefined ? value : storedEnumValue(disc, value); return `'${stored.replace(/'/g, "''")}'`; }; - const out: Array<{ name: Code; expr: Code }> = []; + const out: CheckEntry[] = []; owners.forEach((o, i) => { const check = specs[i]!.checkConstraint; if (check === undefined) return; @@ -800,10 +826,12 @@ function guardedSiblingEnumChecks( ? `"${discCol}" <> ${literal(o.values[0]!)}` : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; const name = typeof declared === "string" && declared.length > 0 ? declared - : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; - out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); }); return out; } diff --git a/examples/showcase/codegen/templates/drizzle-schema.ts b/examples/showcase/codegen/templates/drizzle-schema.ts index 64434dc4c9..b0378ef6e3 100644 --- a/examples/showcase/codegen/templates/drizzle-schema.ts +++ b/examples/showcase/codegen/templates/drizzle-schema.ts @@ -27,6 +27,7 @@ import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/codegen-ts/engine"; import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; @@ -36,6 +37,9 @@ import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-dis import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -177,7 +181,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -191,7 +195,7 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); @@ -204,6 +208,8 @@ export function renderDrizzleSchema( expr: names === undefined || values === undefined ? code`${spec.checkConstraint ?? ""}` : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", }; } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which @@ -212,6 +218,8 @@ export function renderDrizzleSchema( return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -220,6 +228,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -392,6 +402,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -766,7 +792,7 @@ function renderColumn( */ function guardedSiblingEnumChecks( obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, -): Array<{ name: Code; expr: Code }> | undefined { +): CheckEntry[] | undefined { const plan = tphPlan(obj, ctx.loadedRoot); if (plan === null) return undefined; const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); @@ -792,7 +818,7 @@ function guardedSiblingEnumChecks( const stored = disc === undefined ? value : storedEnumValue(disc, value); return `'${stored.replace(/'/g, "''")}'`; }; - const out: Array<{ name: Code; expr: Code }> = []; + const out: CheckEntry[] = []; owners.forEach((o, i) => { const check = specs[i]!.checkConstraint; if (check === undefined) return; @@ -800,10 +826,12 @@ function guardedSiblingEnumChecks( ? `"${discCol}" <> ${literal(o.values[0]!)}` : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; const name = typeof declared === "string" && declared.length > 0 ? declared - : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; - out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); }); return out; } diff --git a/server/typescript/packages/codegen-ts/src/engine-surface.ts b/server/typescript/packages/codegen-ts/src/engine-surface.ts index 71492ca21f..71f959c650 100644 --- a/server/typescript/packages/codegen-ts/src/engine-surface.ts +++ b/server/typescript/packages/codegen-ts/src/engine-surface.ts @@ -65,5 +65,6 @@ export const ENGINE_MODULES: readonly string[] = [ "codegen-ts/src/templates/find-inbound.ts", "codegen-ts/src/templates/find-templates.ts", "codegen-ts/src/tph.ts", + "codegen-ts/src/pg-identifier.ts", "codegen-ts/src/view-context.ts", ]; diff --git a/server/typescript/packages/codegen-ts/src/engine.ts b/server/typescript/packages/codegen-ts/src/engine.ts index 331d83cc08..4660bf4bae 100644 --- a/server/typescript/packages/codegen-ts/src/engine.ts +++ b/server/typescript/packages/codegen-ts/src/engine.ts @@ -52,6 +52,7 @@ export * from "./templates/entity-ui-descriptor.js"; export * from "./templates/find-inbound.js"; export * from "./templates/find-templates.js"; export * from "./tph.js"; +export * from "./pg-identifier.js"; export * from "./view-context.js"; export { ENGINE_MODULES } from "./engine-surface.js"; export { code, imp, joinCode, Import } from "ts-poet"; diff --git a/server/typescript/packages/codegen-ts/src/pg-identifier.ts b/server/typescript/packages/codegen-ts/src/pg-identifier.ts new file mode 100644 index 0000000000..8e796e2d87 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/pg-identifier.ts @@ -0,0 +1,3 @@ +// rc.21 part B (N2): Postgres's 63-byte identifier fit, re-exported where the generators (and the +// owned template copies, which import only from `@metaobjectsdev/codegen-ts/engine`) can reach it. +export { fitPgIdentifier } from "@metaobjectsdev/migrate-ts/expected"; diff --git a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts index 3ba6e3fc25..84ea1bd030 100644 --- a/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/codegen-ts/src/templates/drizzle-schema.ts @@ -27,10 +27,7 @@ import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "../names.js"; import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; -import { fitPgIdentifier } from "@metaobjectsdev/migrate-ts/expected"; - -/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ -interface CheckEntry { name: Code; expr: Code; key: string; text: string } +import { fitPgIdentifier } from "../pg-identifier.js"; import { intValueMapOf } from "../enum-meta.js"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; @@ -40,6 +37,9 @@ import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-dis import { tphStorageObject } from "../tph.js"; import { effectivePackage } from "../docs-paths.js"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children diff --git a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts index 64434dc4c9..b0378ef6e3 100644 --- a/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts +++ b/server/typescript/packages/test-generators/src/templates/drizzle-schema.ts @@ -27,6 +27,7 @@ import { namesRef, physicalNameExpr, sourceSchemaExpr, indexNameExpr, columnExpr, } from "@metaobjectsdev/codegen-ts/engine"; import { resolveTableSchema, storedEnumValue, VALIDATOR_ATTR_CONSTRAINT_NAME } from "@metaobjectsdev/metadata"; +import { fitPgIdentifier } from "@metaobjectsdev/codegen-ts/engine"; import { intValueMapOf } from "@metaobjectsdev/codegen-ts/engine"; import { renderEnumIntCustomType } from "./enum-int-codec.js"; import { renderDurationCustomType } from "./duration-wire-helper.js"; @@ -36,6 +37,9 @@ import { collectTphSubtypeFields, tphConcreteSubtypes, tphPlan } from "./tph-dis import { tphStorageObject } from "@metaobjectsdev/codegen-ts/engine"; import { effectivePackage } from "@metaobjectsdev/codegen-ts/engine"; +/** One table-level CHECK: its name and expression as emitted, and their plain text (rc.21, N1). */ +interface CheckEntry { name: Code; expr: Code; key: string; text: string } + /** * Render the Drizzle table definition for one entity, including: * - FK .references() on FK columns derived from relationship children @@ -177,7 +181,7 @@ export function renderDrizzleSchema( const columnLines: Code[] = []; // Collect CHECK constraints for enum columns; emitted as table-level check() callbacks. - const checkConstraints: Array<{ name: Code; expr: Code }> = []; + const checkConstraints: CheckEntry[] = []; /** * One CHECK entry, composed against `Names` when the artifact is in the run. * @@ -191,7 +195,7 @@ export function renderDrizzleSchema( * The expression's column goes through `sql.raw`, not `sql.identifier`: the latter QUOTES * the name, which changes the constraint text migrate compares against. */ - const checkEntry = (field: MetaField, spec: ColumnSpec): { name: Code; expr: Code } => { + const checkEntry = (field: MetaField, spec: ColumnSpec): CheckEntry => { const colExpr = columnNameExpr(field, spec.dbName); const values = spec.checkConstraintValues; const sqlSym = imp("sql@drizzle-orm"); @@ -204,6 +208,8 @@ export function renderDrizzleSchema( expr: names === undefined || values === undefined ? code`${spec.checkConstraint ?? ""}` : code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: declared, + text: spec.checkConstraint ?? "", }; } // No artifact in this run (the documented ADR-0034 opt-out) — spell both halves, which @@ -212,6 +218,8 @@ export function renderDrizzleSchema( return { name: code`${JSON.stringify(`${tableName}_${spec.dbName}_chk`)}`, expr: code`${spec.checkConstraint ?? ""}`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; } // `\${` emits a literal `${` into the generated source: the name becomes a template @@ -220,6 +228,8 @@ export function renderDrizzleSchema( return { name: code`\`\${${tableNameExpr}}_\${${colExpr}}_chk\``, expr: code`\${${sqlSym}.raw(${colExpr})} IN (${values})`, + key: `${tableName}_${spec.dbName}_chk`, + text: spec.checkConstraint ?? "", }; }; // Int-backed field.enum customType helpers, emitted ahead of the table. Keyed by @@ -392,6 +402,22 @@ export function renderDrizzleSchema( // Emit table-level CHECK constraints for enum fields. Both halves are composed by // `checkEntry` above, which owns the constant-vs-literal decision for the pair. + // rc.21 (N1): Postgres requires each constraint on a table to have its own name, so two + // different CHECKs under one name are refused there, as `meta migrate` refuses them. SQLite + // and D1 accept and enforce both, so both are kept there. + if (dialect === "postgres") { + const byName = new Map(); + for (const c of checkConstraints) { + const seen = byName.get(c.key); + if (seen !== undefined && seen !== c.text) { + throw new Error( + `object.entity '${obj.name}': two CHECK constraints are both named '${c.key}' (${seen} | ${c.text}); ` + + "Postgres requires each constraint on a table to have its own name. Give one a @constraintName.", + ); + } + byName.set(c.key, c.text); + } + } for (const { name, expr } of checkConstraints) { const checkSym = imp(`check@${importModule}`); const sqlSym = imp("sql@drizzle-orm"); @@ -766,7 +792,7 @@ function renderColumn( */ function guardedSiblingEnumChecks( obj: MetaObject, fieldName: string, tableName: string, ctx: RenderContext, -): Array<{ name: Code; expr: Code }> | undefined { +): CheckEntry[] | undefined { const plan = tphPlan(obj, ctx.loadedRoot); if (plan === null) return undefined; const subs = [...plan.subtypes].sort((a, b) => (a.entity.name < b.entity.name ? -1 : a.entity.name > b.entity.name ? 1 : 0)); @@ -792,7 +818,7 @@ function guardedSiblingEnumChecks( const stored = disc === undefined ? value : storedEnumValue(disc, value); return `'${stored.replace(/'/g, "''")}'`; }; - const out: Array<{ name: Code; expr: Code }> = []; + const out: CheckEntry[] = []; owners.forEach((o, i) => { const check = specs[i]!.checkConstraint; if (check === undefined) return; @@ -800,10 +826,12 @@ function guardedSiblingEnumChecks( ? `"${discCol}" <> ${literal(o.values[0]!)}` : o.values.map((v) => `("${discCol}" <> ${literal(v)})`).join(" AND "); const declared = o.node.attr(VALIDATOR_ATTR_CONSTRAINT_NAME); + // rc.21 (N2): a qualified default name is fitted to Postgres's 63-byte limit, as migrate fits it. + const qualified = `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; const name = typeof declared === "string" && declared.length > 0 ? declared - : `${tableName}_${(o.node.parent?.name ?? "subtype").toLowerCase()}_${specs[i]!.dbName}_chk`; - out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})` }); + : ctx.dialect === "postgres" ? fitPgIdentifier(qualified) : qualified; + out.push({ name: code`${JSON.stringify(name)}`, expr: code`(${unless}) OR (${check})`, key: name, text: `(${unless}) OR (${check})` }); }); return out; } From 94d7fc1496ddb4b0913624ff1e1197541a9bdd1e Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:12:20 -0500 Subject: [PATCH 196/267] feat(requirements): an authored requirement for origin.function The project's requirement ledger promises what origin.function is for, as every registered subtype must; the requirement harness is regenerated from it. Co-Authored-By: Claude Opus 5.5 --- .../csharp/RequirementHarnessTests.cs | 6 +++++- .../java/RequirementHarnessTest.java | 7 ++++++- .../kotlin/RequirementHarnessTest.kt | 7 ++++++- .../python/test_requirement_harness.py | 7 ++++++- .../typescript/requirement-harness.test.ts | 7 ++++++- metaobjects/meta.requirements.yaml | 14 ++++++++++++++ 6 files changed, 43 insertions(+), 5 deletions(-) diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs index 56a08ae700..94a17762e5 100644 --- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs +++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (115 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (116 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into C#'s own suite and write the assertion the @@ -144,6 +144,10 @@ public void declare_derivation_originComputed() { /* metaobjects.declare.derivat [Fact(Skip = "unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return.")] public void declare_derivation_originFirst() { /* metaobjects.declare.derivation.originFirst */ } + // Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. + [Fact(Skip = "unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.")] + public void declare_derivation_originFunction() { /* metaobjects.declare.derivation.originFunction */ } + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. [Fact(Skip = "unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.")] public void declare_derivation_originPassthrough() { /* metaobjects.declare.derivation.originPassthrough */ } diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java index f02b52d9d3..ed3357e2bd 100644 --- a/fixtures/requirement-harness/java/RequirementHarnessTest.java +++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (115 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (116 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into Java's own suite and write the assertion the @@ -177,6 +177,11 @@ void declare_derivation_originComputed() { /* metaobjects.declare.derivation.ori @Disabled("unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return.") void declare_derivation_originFirst() { /* metaobjects.declare.derivation.originFirst */ } + // Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.") + void declare_derivation_originFunction() { /* metaobjects.declare.derivation.originFunction */ } + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. @Test @Disabled("unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.") diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt index 38830b4bfc..6076670fb1 100644 --- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt +++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (115 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (116 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into Kotlin's own suite and write the assertion the @@ -177,6 +177,11 @@ class RequirementHarnessTest { @Disabled("unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return.") fun declare_derivation_originFirst() { /* metaobjects.declare.derivation.originFirst */ } + // Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. + @Test + @Disabled("unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.") + fun declare_derivation_originFunction() { /* metaobjects.declare.derivation.originFunction */ } + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. @Test @Disabled("unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.") diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py index 0e5fdfd90e..cd7c7e2b7a 100644 --- a/fixtures/requirement-harness/python/test_requirement_harness.py +++ b/fixtures/requirement-harness/python/test_requirement_harness.py @@ -1,6 +1,6 @@ # @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. # -# One slot per authored promise in metaobjects/meta.requirements.yaml (115 of them). +# One slot per authored promise in metaobjects/meta.requirements.yaml (116 of them). # Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a # claim that nothing is verified — the conformance corpora already check many of # these. To FILL one, move it into Python's own suite and write the assertion the @@ -172,6 +172,11 @@ def test_declare_derivation_originComputed(): def test_declare_derivation_originFirst(): """metaobjects.declare.derivation.originFirst""" +# Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. +@pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated.") +def test_declare_derivation_originFunction(): + """metaobjects.declare.derivation.originFunction""" + # Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. @pytest.mark.skip(reason="unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so.") def test_declare_derivation_originPassthrough(): diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts index 487abe99db..29db0a8890 100644 --- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts +++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts @@ -1,6 +1,6 @@ // @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE. // -// One slot per authored promise in metaobjects/meta.requirements.yaml (115 of them). +// One slot per authored promise in metaobjects/meta.requirements.yaml (116 of them). // Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a // claim that nothing is verified — the conformance corpora already check many of // these. To FILL one, move it into TypeScript's own suite and write the assertion the @@ -172,6 +172,11 @@ test.skip("metaobjects.declare.derivation.originFirst", () => { // unfilled slot — write an assertion that fails when: A latest value that is whichever row the database happened to return. }); +// Owned database function — A value computed by a database function the project owns is declared by the function's name, schema and argument fields, so every call is checked against the model, never written as SQL. +test.skip("metaobjects.declare.derivation.originFunction", () => { + // unfilled slot — write an assertion that fails when: A view body that calls the function by hand and keeps working after the argument column is renamed only until the view is next recreated. +}); + // Passthrough — A passthrough declares that a value IS a value on another object, and must keep its type across the hop. test.skip("metaobjects.declare.derivation.originPassthrough", () => { // unfilled slot — write an assertion that fails when: A number carried through as text because the two ends disagreed about its type, with nothing saying so. diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml index dcd229a300..40142fb990 100644 --- a/metaobjects/meta.requirements.yaml +++ b/metaobjects/meta.requirements.yaml @@ -1148,6 +1148,20 @@ metadata.root: counterexample: >- A latest value that is whichever row the database happened to return. + - requirement.functional: + name: originFunction + title: Owned database function + level: 4 + status: live + statement: >- + A value computed by a database function the + project owns is declared by the function's name, + schema and argument fields, so every call is + checked against the model, never written as SQL. + counterexample: >- + A view body that calls the function by hand and + keeps working after the argument column is renamed + only until the view is next recreated. - requirement.functional: name: reporting From 03f8d8560a8693e1ab969b397ecf30892cb11a66 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:23:14 -0500 Subject: [PATCH 197/267] chore(requirements): the ledger's expected warning count follows the new live requirement Co-Authored-By: Claude Opus 5.5 --- scripts/check-requirements-ledger.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/check-requirements-ledger.ts b/scripts/check-requirements-ledger.ts index 7c0506bebd..3082f11e2a 100644 --- a/scripts/check-requirements-ledger.ts +++ b/scripts/check-requirements-ledger.ts @@ -48,7 +48,7 @@ const EXPECTED_WARNING = "WARN_REQUIREMENT_NOTHING_IMPLEMENTS"; * the neighbour — became `Number("metaobjects")`, i.e. NaN. Every comparison against * NaN is unequal, so the gate failed reporting "expected NaN" and a remedy paragraph * about updating the pin. */ -const DEFAULT_EXPECTED_WARNING_COUNT = 148; +const DEFAULT_EXPECTED_WARNING_COUNT = 149; function expectedWarnings(argv: readonly string[]): number { const flag = argv.find((a) => a.startsWith("--expect-warnings=")); From d2fd99b63401b3a29565718559f45a84765aa029 Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:29:07 -0500 Subject: [PATCH 198/267] test(python): the #210 assembly-origin table covers origin.function Co-Authored-By: Claude Opus 5.5 --- server/python/tests/loader/test_template_payload_target_210.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/python/tests/loader/test_template_payload_target_210.py b/server/python/tests/loader/test_template_payload_target_210.py index ce9fc43c34..e63bf9902d 100644 --- a/server/python/tests/loader/test_template_payload_target_210.py +++ b/server/python/tests/loader/test_template_payload_target_210.py @@ -82,6 +82,8 @@ def test_assembly_origins_rejected_on_value_host() -> None: "first": {"origin.first": {"@of": "t::ai::Author.name", "@via": "t::ai::Author.posts", "@orderBy": ["name:desc"]}}, + # rc.21 part B (U10). + "function": {"origin.function": {"@function": "f"}}, } assert set(origin_by_subtype) == set(ASSEMBLY_ORIGIN_SUBTYPES) for sub, origin in origin_by_subtype.items(): From 4d3f252a74c925d500933299f831981a29ce4a0e Mon Sep 17 00:00:00 2001 From: Douglas Mealing Date: Fri, 13 Nov 2026 19:43:23 -0500 Subject: [PATCH 199/267] chore(views): neutral examples for the rc.21 view vocabulary The expression description in the spec (and its copies, the registry, docs and site), the CHANGELOG, the docs and the tests now use neutral domain names for paths, functions and TPH examples. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/features/relationships.md | 8 +- .../expected.json | 6 +- .../input/meta.views.json | 6 +- fixtures/metamodel-docs/expected/INDEX.md | 2 +- .../metamodel-docs/expected/types/attr.md | 2 +- .../expected-registry.json | 2 +- .../MetaObjects/SpecMetamodel/attr.json | 2 +- .../src/metaobjects/spec_metamodel/attr.json | 2 +- .../rc21b-view-vocabulary.fixture.ts | 6 +- .../projection/rc21b-view-vocabulary.test.ts | 84 +++++++++---------- .../test/view-vocabulary-rc21-pg.test.ts | 12 +-- .../src/core/attr/attr-definition.embedded.ts | 2 +- .../metadata/src/loader/validation-passes.ts | 2 +- site-reference/index.html | 2 +- site-reference/types/attr.html | 2 +- spec/metamodel/attr.json | 2 +- 17 files changed, 72 insertions(+), 72 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1a5add696..92f48264c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,7 +35,7 @@ vocabulary; upgrade every port together. `lower`, `upper`, `btrim`, `splitPart`, `concat`, `concatWs`, `substring`, `replace`, `left`, `right` and `length` beside `coalesce`, each argument typed; a `{ field }` ref to a scalar `origin.aggregate` (read on the grouped row, not filterable); and, on a projection, a path of - to-one hops (`"patientId.currentMailingAddressId"`) in an expression or as a correlated + to-one hops (`"customerId.regionId"`) in an expression or as a correlated `@filter` operand, joined but not output. `origin.function` (`@function`, `@schema`, `@args`) is a value computed by a database function the project owns, typed by its argument fields and its carrying field; declared on an entity it is entity-derived (Postgres only). On diff --git a/docs/features/relationships.md b/docs/features/relationships.md index 3e6a3880e4..3877221a3b 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -267,8 +267,8 @@ NULL literal fits any. On SQLite each is spelled with SQLite's own functions whe is the same (`greatest` keeps Postgres's NULL-skipping), and refused where it is not: `splitPart` beyond the first part. -**A path in an expression or an operand.** On a projection, `{ field: "patientId.currentMailingAddressId" }` -in an `origin.computed` expression, or `{ field: "taskId.caseId" }` as a correlated operand in an +**A path in an expression or an operand.** On a projection, `{ field: "customerId.regionId" }` +in an `origin.computed` expression, or `{ field: "orderId.customerId" }` as a correlated operand in an origin's `@filter`, is a path of to-one hops from the base and a field of the entity reached: the view joins it without outputting it. @@ -286,8 +286,8 @@ never creates the function (it is owned SQL, created before the view). Postgres ```yaml - field.int: - name: consentState - children: [ { origin.function: { "@function": compute_consent_state, "@schema": app, "@args": [id] } } ] + name: riskScore + children: [ { origin.function: { "@function": compute_risk_score, "@schema": app, "@args": [id] } } ] ``` **One row per array element** (`@grain`, `@grainOrdinal`). A projection whose `@grain` names a diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/expected.json b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json index 335403cc0e..74e6c19e96 100644 --- a/fixtures/conformance/projection-view-vocabulary-rc21/expected.json +++ b/fixtures/conformance/projection-view-vocabulary-rc21/expected.json @@ -121,7 +121,7 @@ }, { "field.int": { - "name": "cumulativeStatus" + "name": "stage" } }, { @@ -226,7 +226,7 @@ "when": { "op": "eq", "left": { - "field": "cumulativeStatus" + "field": "stage" }, "right": { "value": 0 @@ -241,7 +241,7 @@ } ], "else": { - "field": "cumulativeStatus" + "field": "stage" } } } diff --git a/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json index 68401ce7fd..4864b5e411 100644 --- a/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json +++ b/fixtures/conformance/projection-view-vocabulary-rc21/input/meta.views.json @@ -23,7 +23,7 @@ { "field.long": { "name": "id" } }, { "field.long": { "name": "customerId" } }, { "field.enum": { "name": "status", "@values": ["Open", "Shipped"], "@intValueMap": { "Open": 0, "Shipped": 1 } } }, - { "field.int": { "name": "cumulativeStatus" } }, + { "field.int": { "name": "stage" } }, { "field.timestamp": { "name": "updatedAt" } }, { "identity.primary": { "name": "id", "@fields": "id" } }, { "identity.reference": { "name": "customerId", "@fields": "customerId", "@references": "Customer" } } @@ -41,9 +41,9 @@ { "source.rdb": { "@kind": "view", "@view": "v_order_row" } }, { "field.long": { "name": "id", "extends": "Order.id" } }, { "field.int": { "name": "outcome", "children": [ { "origin.computed": { "@expr": { - "case": [ { "when": { "op": "eq", "left": { "field": "cumulativeStatus" }, "right": { "value": 0 } }, + "case": [ { "when": { "op": "eq", "left": { "field": "stage" }, "right": { "value": 0 } }, "then": { "cast": { "field": "status" }, "as": "int" } } ], - "else": { "field": "cumulativeStatus" } } } } ] } }, + "else": { "field": "stage" } } } } ] } }, { "field.string": { "name": "zip5", "children": [ { "origin.computed": { "@expr": { "fn": "splitPart", "args": [ { "field": "customerId.zip" }, { "value": "-" }, { "value": 1 } ] } } } ] } }, { "field.string": { "name": "nothing", "children": [ { "origin.computed": { "@expr": { diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md index 02e5586e0f..03801c2a58 100644 --- a/fixtures/metamodel-docs/expected/INDEX.md +++ b/fixtures/metamodel-docs/expected/INDEX.md @@ -19,7 +19,7 @@ children and the cardinality of that subtype. Documentation attributes | `attr.boolean` | A boolean-valued metadata attribute. Coerces to and validates as true/false. | [types/attr.md#attrboolean](types/attr.md#attrboolean) | | `attr.class` | A class-/type-reference-valued metadata attribute. String-backed (a fully-qualified class or type name) used by binding facets. | [types/attr.md#attrclass](types/attr.md#attrclass) | | `attr.double` | A double-precision floating-point-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrdouble](types/attr.md#attrdouble) | -| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | +| `attr.expression` | A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. | [types/attr.md#attrexpression](types/attr.md#attrexpression) | | `attr.filter` | A filter-expression-valued metadata attribute. Object-shaped value that desugars a preset filter to the canonical { field: { op: value } } form (scalar→eq, array→in, null→isNull; or/and recurse). | [types/attr.md#attrfilter](types/attr.md#attrfilter) | | `attr.int` | A 32-bit-integer-valued metadata attribute. Coerces to and validates as a number. | [types/attr.md#attrint](types/attr.md#attrint) | | `attr.intMap` | An object-shaped attribute whose values are all integers (e.g. field.enum's @intValueMap: {memberSymbol: int}). Generic shape check only; a consumer field type layers its own semantic rules (key-set membership, uniqueness) in its own content-rule validation. | [types/attr.md#attrintmap](types/attr.md#attrintmap) | diff --git a/fixtures/metamodel-docs/expected/types/attr.md b/fixtures/metamodel-docs/expected/types/attr.md index 285bf6c6df..b07e2267ee 100644 --- a/fixtures/metamodel-docs/expected/types/attr.md +++ b/fixtures/metamodel-docs/expected/types/attr.md @@ -68,7 +68,7 @@ _No structural children._ ### attr.expression -A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. +A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. **Owning provider:** metaobjects-core-types diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 48ed0890fa..8163d03c83 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -32,7 +32,7 @@ { "type": "attr", "subType": "expression", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.", + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.", "attrs": [], "children": [] }, diff --git a/server/csharp/MetaObjects/SpecMetamodel/attr.json b/server/csharp/MetaObjects/SpecMetamodel/attr.json index c05dab28b7..ec55a95947 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/attr.json +++ b/server/csharp/MetaObjects/SpecMetamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/server/python/src/metaobjects/spec_metamodel/attr.json b/server/python/src/metaobjects/spec_metamodel/attr.json index c05dab28b7..ec55a95947 100644 --- a/server/python/src/metaobjects/spec_metamodel/attr.json +++ b/server/python/src/metaobjects/spec_metamodel/attr.json @@ -65,7 +65,7 @@ "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] } diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts index 6c598a9148..6a474f2992 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.fixture.ts @@ -19,7 +19,7 @@ export const RC21B_ENTITIES: unknown[] = [ { "field.string": { name: "lastName" } }, { "field.string": { name: "zip" } }, { "field.long": { name: "regionId" } }, - { "field.long": { name: "mailingAddressId" } }, + { "field.long": { name: "defaultWarehouseId" } }, { "field.object": { name: "contacts", "@objectRef": "Contact", isArray: true, "@storage": "jsonb" } }, { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "regionId", "@fields": "regionId", "@references": "Region" } }, @@ -39,7 +39,7 @@ export const RC21B_ENTITIES: unknown[] = [ { "field.long": { name: "id" } }, { "field.long": { name: "customerId" } }, { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, - { "field.int": { name: "cumulativeStatus" } }, + { "field.int": { name: "stage" } }, { "field.string": { name: "externalRef" } }, { "field.timestamp": { name: "updatedAt" } }, { "identity.primary": { name: "id", "@fields": "id" } }, @@ -50,7 +50,7 @@ export const RC21B_ENTITIES: unknown[] = [ { "field.long": { name: "id" } }, { "field.long": { name: "orderId", "@required": true } }, { "field.long": { name: "customerId" } }, - { "field.int": { name: "cumulativeStatus" } }, + { "field.int": { name: "stage" } }, { "field.timestamp": { name: "createdAt" } }, { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } }, diff --git a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts index 0f745c739a..37c1406607 100644 --- a/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/codegen-ts/test/projection/rc21b-view-vocabulary.test.ts @@ -50,9 +50,9 @@ describe("U12 cast and U2 a typed NULL of an unbounded varchar", () => { describe("U8 an int-stored enum and an int in one case, through the cast", () => { test("postgres", async () => { const sql = await one("postgres", orderRow([computed("outcome", "int", { - case: [{ when: { op: "eq", left: { field: "cumulativeStatus" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } }], - else: { field: "cumulativeStatus" } })])); - expect(sql).toContain("(CASE WHEN o.cumulative_status = 0 THEN CAST(o.status AS INTEGER) ELSE o.cumulative_status END) AS outcome"); + case: [{ when: { op: "eq", left: { field: "stage" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } }], + else: { field: "stage" } })])); + expect(sql).toContain("(CASE WHEN o.stage = 0 THEN CAST(o.status AS INTEGER) ELSE o.stage END) AS outcome"); }); }); @@ -81,8 +81,8 @@ describe("U11 string functions, and U3 a path the view does not output", () => { test("sqlite: the same values from SQLite's own functions", async () => { const sql = await one("sqlite", p); const db = new Database(":memory:"); - db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); - db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, cumulative_status INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, stage INTEGER, external_ref TEXT, updated_at TEXT)"); db.run("INSERT INTO customers (id, first_name, last_name, zip) VALUES (10, 'Ada', 'Lovelace', '02139-4307'), (11, NULL, 'Hopper', '12345')"); db.run("INSERT INTO orders (id, customer_id, external_ref) VALUES (1, 10, 'AXXBCD'), (2, 11, 'NONE'), (3, NULL, NULL)"); db.run(`CREATE VIEW v AS ${sql}`); @@ -117,9 +117,9 @@ describe("U13 greatest / least over an aggregate, and U4 a correlated path opera const sql = await one("sqlite", p); expect(sql).toContain("MAX(COALESCE(o.updated_at, MAX(o0.created_at)), COALESCE(MAX(o0.created_at), o.updated_at)) AS touched"); const db = new Database(":memory:"); - db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); - db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, cumulative_status INTEGER, external_ref TEXT, updated_at TEXT)"); - db.run("CREATE TABLE order_events (id INTEGER PRIMARY KEY, order_id INTEGER, customer_id INTEGER, cumulative_status INTEGER, created_at TEXT)"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, status INTEGER, stage INTEGER, external_ref TEXT, updated_at TEXT)"); + db.run("CREATE TABLE order_events (id INTEGER PRIMARY KEY, order_id INTEGER, customer_id INTEGER, stage INTEGER, created_at TEXT)"); db.run("INSERT INTO customers (id) VALUES (10)"); db.run("INSERT INTO orders (id, customer_id, updated_at) VALUES (1, 10, '2026-01-05'), (2, 10, NULL), (3, 10, '2026-01-01')"); db.run("INSERT INTO order_events (id, order_id, customer_id, created_at) VALUES (100, 1, 10, '2026-02-01'), (101, 2, 9, '2026-03-01'), (102, 2, 10, '2026-03-02')"); @@ -163,7 +163,7 @@ describe("U14 @grain — one row per array element", () => { test("sqlite", async () => { const sql = await one("sqlite", p); const db = new Database(":memory:"); - db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); db.run(`INSERT INTO customers (id, contacts) VALUES (1, '[{"kind":"email","rank":1},{"kind":"phone","rank":2}]'), (2, '[]'), (3, NULL)`); db.run(`CREATE VIEW v AS ${sql}`); expect(db.query("SELECT customer_id, position, kind, rank FROM v ORDER BY customer_id, position").all()).toEqual([ @@ -197,7 +197,7 @@ describe("U15 @union", () => { for (const all of [false, true]) { const sql = (await views("sqlite", ...branches, union(all))).get("v_people")!; const db = new Database(":memory:"); - db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, mailing_address_id INTEGER, contacts TEXT)"); + db.run("CREATE TABLE customers (id INTEGER PRIMARY KEY, first_name TEXT, last_name TEXT, zip TEXT, region_id INTEGER, default_warehouse_id INTEGER, contacts TEXT)"); db.run("CREATE TABLE addresses (id INTEGER PRIMARY KEY, customer_id INTEGER, street TEXT)"); db.run("INSERT INTO customers (id, last_name) VALUES (1, 'Main')"); db.run("INSERT INTO addresses (id, customer_id, street) VALUES (9, 1, 'main'), (10, 2, 'Elm')"); @@ -210,26 +210,26 @@ describe("U15 @union", () => { // rc.21 part B: two fixes the vocabulary needed to build its motivating views. describe("a projection over a TPH root reads its subtypes' columns; a unique reverse hop is to-one", () => { const tph = [ - { "object.entity": { name: "Grant", "@discriminator": "kind", children: [ - { "source.rdb": { "@table": "grants" } }, + { "object.entity": { name: "Vehicle", "@discriminator": "kind", children: [ + { "source.rdb": { "@table": "vehicles" } }, { "field.long": { name: "id" } }, { "field.string": { name: "kind", "@maxLength": 10 } }, - { "field.long": { name: "cardId" } }, + { "field.long": { name: "lockerId" } }, { "identity.primary": { "@fields": "id" } } ] } }, - { "object.entity": { name: "PriorGrant", extends: "Grant", "@discriminatorValue": "PRIOR", children: [ - { "field.string": { name: "integrationKey" } } ] } }, - { "object.entity": { name: "Card", children: [ - { "source.rdb": { "@table": "cards" } }, + { "object.entity": { name: "Truck", extends: "Vehicle", "@discriminatorValue": "TRUCK", children: [ + { "field.string": { name: "payloadClass" } } ] } }, + { "object.entity": { name: "Locker", children: [ + { "source.rdb": { "@table": "lockers" } }, { "field.long": { name: "id" } }, { "field.string": { name: "number" } }, { "identity.primary": { "@fields": "id" } } ] } }, - { "object.entity": { name: "CardGrant", children: [ - { "source.rdb": { "@table": "card_grants" } }, + { "object.entity": { name: "LockerKey", children: [ + { "source.rdb": { "@table": "locker_keys" } }, { "field.long": { name: "id" } }, - { "field.long": { name: "cardId" } }, + { "field.long": { name: "lockerId" } }, { "field.string": { name: "note" } }, { "identity.primary": { "@fields": "id" } }, - { "identity.reference": { name: "cardId", "@fields": "cardId", "@references": "Card" } } ] } }, + { "identity.reference": { name: "lockerId", "@fields": "lockerId", "@references": "Locker" } } ] } }, ]; async function load(extra: unknown[]) { const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [...tph, ...extra] } }))]); @@ -237,36 +237,36 @@ describe("a projection over a TPH root reads its subtypes' columns; a unique rev } test("an extender with no identity keeps the super's anchor, and a subtype column reads the shared table", async () => { const { root, errors } = await load([ - { "object.projection": { name: "GrantBase", abstract: true, children: [ - { "field.long": { name: "grantId", extends: "Grant.id" } }, - { "identity.primary": { name: "id", extends: "Grant.primary" } } ] } }, - { "object.projection": { name: "GrantRow", extends: "GrantBase", children: [ - { "source.rdb": { "@kind": "view", "@view": "v_grants" } }, - { "field.string": { name: "externalKey", extends: "PriorGrant.integrationKey" } } ] } }, + { "object.projection": { name: "VehicleBase", abstract: true, children: [ + { "field.long": { name: "vehicleId", extends: "Vehicle.id" } }, + { "identity.primary": { name: "id", extends: "Vehicle.primary" } } ] } }, + { "object.projection": { name: "VehicleRow", extends: "VehicleBase", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_vehicles" } }, + { "field.string": { name: "externalKey", extends: "Truck.payloadClass" } } ] } }, ]); expect(errors).toEqual([]); const sql = buildProjectionViews(root, { dialect: "postgres" })[0]!.sql; - expect(sql).toContain("g.id AS grant_id"); - expect(sql).toContain("g.integration_key AS external_key"); - expect(sql).toContain("FROM public.grants g"); - expect(sql).not.toContain("'PRIOR'"); + expect(sql).toContain("v.id AS vehicle_id"); + expect(sql).toContain("v.payload_class AS external_key"); + expect(sql).toContain("FROM public.vehicles v"); + expect(sql).not.toContain("'TRUCK'"); }); const viaCard = (unique: boolean) => [ - { "object.entity": { name: "CardGrant", children: [ - { "source.rdb": { "@table": "card_grants" } }, + { "object.entity": { name: "LockerKey", children: [ + { "source.rdb": { "@table": "locker_keys" } }, { "field.long": { name: "id" } }, - { "field.long": { name: "cardId" } }, + { "field.long": { name: "lockerId" } }, { "field.string": { name: "note" } }, { "identity.primary": { "@fields": "id" } }, - ...(unique ? [{ "identity.secondary": { name: "card_grants_card_uq", "@fields": "cardId" } }] : []), - { "identity.reference": { name: "cardId", "@fields": "cardId", "@references": "Card" } } ] } }, + ...(unique ? [{ "identity.secondary": { name: "locker_keys_locker_uq", "@fields": "lockerId" } }] : []), + { "identity.reference": { name: "lockerId", "@fields": "lockerId", "@references": "Locker" } } ] } }, ]; test("a passthrough over a reverse hop loads when the holder's reference fields are a unique identity, and only then", async () => { - const projection = { "object.projection": { name: "CardRow", children: [ - { "source.rdb": { "@kind": "view", "@view": "v_cards" } }, - { "field.long": { name: "id", extends: "Card.id" } }, - { "field.string": { name: "note", children: [ { "origin.passthrough": { "@from": "CardGrant.note", "@via": "Card.cardGrants" } } ] } }, - { "identity.primary": { name: "id", extends: "Card.primary" } } ] } }; + const projection = { "object.projection": { name: "LockerRow", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_lockers" } }, + { "field.long": { name: "id", extends: "Locker.id" } }, + { "field.string": { name: "note", children: [ { "origin.passthrough": { "@from": "LockerKey.note", "@via": "Locker.lockerKeys" } } ] } }, + { "identity.primary": { name: "id", extends: "Locker.primary" } } ] } }; const withUnique = async (unique: boolean) => { const doc = { "metadata.root": { package: "acme", children: [...tph.slice(0, 3), ...viaCard(unique), projection] } }; const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]); @@ -274,7 +274,7 @@ describe("a projection over a TPH root reads its subtypes' columns; a unique rev }; const ok = await withUnique(true); expect(ok.errors).toEqual([]); - expect(buildProjectionViews(ok.root, { dialect: "postgres" })[0]!.sql).toContain("LEFT OUTER JOIN public.card_grants c0 ON c0.card_id = c.id"); + expect(buildProjectionViews(ok.root, { dialect: "postgres" })[0]!.sql).toContain("LEFT OUTER JOIN public.locker_keys l0 ON l0.locker_id = l.id"); expect((await withUnique(false)).errors.some((m) => /is to-many/.test(m))).toBe(true); }); }); diff --git a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts index 9bcd22f9a4..ca48c4dd99 100644 --- a/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts +++ b/server/typescript/packages/integration-tests/test/view-vocabulary-rc21-pg.test.ts @@ -47,7 +47,7 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "field.long": { name: "id" } }, { "field.long": { name: "customerId" } }, { "field.enum": { name: "status", "@values": ["Open", "Shipped"], "@intValueMap": { Open: 0, Shipped: 1 } } }, - { "field.int": { name: "cumulativeStatus" } }, + { "field.int": { name: "stage" } }, { "field.string": { name: "externalRef" } }, { "field.timestamp": { name: "updatedAt" } }, { "identity.primary": { name: "id", "@fields": "id" } }, @@ -57,7 +57,7 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "field.long": { name: "id" } }, { "field.long": { name: "orderId", "@required": true } }, { "field.long": { name: "customerId" } }, - { "field.int": { name: "cumulativeStatus" } }, + { "field.int": { name: "stage" } }, { "field.timestamp": { name: "createdAt" } }, { "identity.primary": { name: "id", "@fields": "id" } }, { "identity.reference": { name: "orderId", "@fields": "orderId", "@references": "Order" } } ] } }, @@ -66,7 +66,7 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "field.long": { name: "id", extends: "Order.id" } }, { "field.string": { name: "ref", children: [ { "origin.computed": { "@expr": { fn: "coalesce", args: [ { field: "externalRef" }, { cast: { field: "id" }, as: "string" } ] } } } ] } }, { "field.string": { name: "nothing", children: [ { "origin.computed": { "@expr": { cast: { value: null }, as: "string", dbColumnType: "varchar" } } } ] } }, - { "field.int": { name: "outcome", children: [ { "origin.computed": { "@expr": { case: [ { when: { op: "eq", left: { field: "cumulativeStatus" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } } ], else: { field: "cumulativeStatus" } } } } ] } }, + { "field.int": { name: "outcome", children: [ { "origin.computed": { "@expr": { case: [ { when: { op: "eq", left: { field: "stage" }, right: { value: 0 } }, then: { cast: { field: "status" }, as: "int" } } ], else: { field: "stage" } } } } ] } }, { "field.string": { name: "zip5", children: [ { "origin.computed": { "@expr": { fn: "splitPart", args: [ { field: "customerId.zip" }, { value: "-" }, { value: 1 } ] } } } ] } }, { "field.string": { name: "fullName", children: [ { "origin.computed": { "@expr": { fn: "btrim", args: [ { fn: "concatWs", args: [ { value: " " }, { field: "customerId.firstName" }, { field: "customerId.lastName" } ] } ] } } } ] } }, { "field.string": { name: "initials", children: [ { "origin.computed": { "@expr": { fn: "upper", args: [ { fn: "concat", args: [ { fn: "left", args: [ { field: "customerId.firstName" }, { value: 1 } ] }, { fn: "right", args: [ { fn: "lower", args: [ { field: "customerId.lastName" } ] }, { value: 1 } ] } ] } ] } } } ] } }, @@ -74,7 +74,7 @@ const MODEL = { "metadata.root": { package: "acme", children: [ { "field.string": { name: "noRef", children: [ { "origin.computed": { "@expr": { fn: "nullif", args: [ { field: "externalRef" }, { value: "NONE" } ] } } } ] } }, { "field.string": { name: "tier", children: [ { "origin.passthrough": { "@from": "Customer.loyaltyTier", "@via": "Order.customerId" } } ] } }, { "field.timestamp": { name: "lastEvent", children: [ { "origin.aggregate": { "@agg": "max", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents" } } ] } }, - { "field.timestamp": { name: "firstAtStatus", children: [ { "origin.aggregate": { "@agg": "min", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents", "@filter": { cumulativeStatus: { eq: { field: "cumulativeStatus" } } } } } ] } }, + { "field.timestamp": { name: "firstAtStatus", children: [ { "origin.aggregate": { "@agg": "min", "@of": "OrderEvent.createdAt", "@via": "Order.orderEvents", "@filter": { stage: { eq: { field: "stage" } } } } } ] } }, { "field.timestamp": { name: "touched", children: [ { "origin.computed": { "@expr": { fn: "greatest", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, { "field.timestamp": { name: "earliest", children: [ { "origin.computed": { "@expr": { fn: "least", args: [ { field: "updatedAt" }, { field: "lastEvent" } ] } } } ] } }, { "field.long": { name: "eventByCustomer", children: [ { "origin.first": { "@of": "OrderEvent.id", "@via": "Order.orderEvents", "@orderBy": ["createdAt"], "@filter": { customerId: { eq: { field: "customerId.id" } } } } } ] } }, @@ -152,11 +152,11 @@ describe("rc.21 part B view vocabulary — live Postgres", () => { (11, ' Alan', 'Turing ', '12345', 1, '[]'), (12, NULL, 'Hopper', NULL, NULL, NULL); INSERT INTO addresses (id, customer_id, street) VALUES (100, 10, 'Lovelace'), (101, 11, 'Main St'); - INSERT INTO orders (id, customer_id, status, cumulative_status, external_ref, updated_at) VALUES + INSERT INTO orders (id, customer_id, status, stage, external_ref, updated_at) VALUES (1, 10, 1, 0, NULL, '2026-01-05T00:00:00Z'), (2, 11, 0, 7, 'AXXBCD', '2026-03-01T00:00:00Z'), (3, 12, 0, 0, 'NONE', NULL); - INSERT INTO order_events (id, order_id, customer_id, cumulative_status, created_at) VALUES + INSERT INTO order_events (id, order_id, customer_id, stage, created_at) VALUES (1000, 1, 10, 0, '2026-01-01T00:00:00Z'), (1001, 1, 10, 0, '2026-02-01T00:00:00Z'), (1002, 1, 99, 3, '2026-01-02T00:00:00Z'), diff --git a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts index ae4787dd88..a5522146ee 100644 --- a/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/attr/attr-definition.embedded.ts @@ -73,7 +73,7 @@ export const ATTR_DEFINITION: ProviderDefinition = { "type": "attr", "subType": "expression", "dataType": "object", - "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." + "description": "A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: \"\", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159." } ] }; diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index bb8be747f5..3494630275 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -2032,7 +2032,7 @@ function checkCorrelatedOperands( )); } else if (typeof name !== "string" || !base.children().some((c) => c.type === TYPE_FIELD && c.name === name)) { // rc.21 part B (U4): on a projection, the operand may be a PATH of to-one hops from the base - // row and a field of the entity reached ("taskId.caseId"), joined on the outer row. + // row and a field of the entity reached ("orderId.customerId"), joined on the outer row. const path = typeof name === "string" && name.includes(".") && onProjection ? resolveFilterPath(base as MetaObject, name) : undefined; if (path !== undefined && typeof path !== "string") continue; diff --git a/site-reference/index.html b/site-reference/index.html index f3cec925e9..03aaa12a52 100644 --- a/site-reference/index.html +++ b/site-reference/index.html @@ -82,7 +82,7 @@
    attr.expressionA structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('patientId.currentMailingAddressId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159.A structured expression tree (closed node grammar: field/value refs, comparisons sharing the filter op vocabulary, isNull/isNotNull, and/or/not, coalesce, case, now). Backs origin.computed; a filter object embeds canonically. A { field } ref names one of the projection's own fields (a passthrough, joined or not, an origin.first or another origin.computed — never an aggregate, never itself), else a field of the base entity (rc.19 computed-over-joined). { case: [ { when, then }, ... ], else? } is a searched CASE (each when boolean); with operand: it is a simple CASE (each when a value compared with operand by equality); every then/else shares one type. { now: "", startOf? } is the current instant shifted by the duration (rc.19 now), its kind (date, local or instant timestamp) taken from the field it is compared with. rc.21: a { field } ref may also name a scalar origin.aggregate of the projection (read on the grouped row; such a value is not filterable) or, on a projection, a PATH of to-one hops from the base and a field of the entity reached ('customerId.regionId'), joined but not output. { fn } takes a closed, typed set: coalesce, greatest, least, nullif (arguments of one type), lower, upper, btrim (string[, chars]), splitPart (string, delimiter, int), concat (scalars; NULL reads as empty), concatWs (separator, scalars), substring (string, start[, length]), replace (string, from, to), left and right (string, int), length (string to int). { cast: , as: , dbColumnType? } converts to string, int, long, double, float, decimal, boolean, date, timestamp or uuid, optionally with a text @dbColumnType spelling for a string; an enum casts to an integer only when stored as one (@intValueMap). A cross-field validator's @condition (a CHECK) takes only fields, literals, comparisons, null tests, and/or/not and coalesce. Arithmetic is #159. types/attr.md#attrexpression
    origin.functionA value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. Each argument is typed by its field and the result by the carrying field's subtype, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. types/origin.md#originfunction
    metaobjects-core-typesThe fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field. Absent or empty: a function of no arguments.The fields passed to the function, in parameter order: field names of the host entity, or (on a projection) of the projection or its base entity. Each must be a scalar field whose subtype is the declared parameter type in @params; to pass another type, pass an origin.computed field that casts it ({ cast: { field: x }, as: }). Absent or empty: a function of no arguments.
    @function The function's name as the database names it: a plain identifier ([A-Za-z_][A-Za-z0-9_]*), quoted when it is not lowercase.
    @paramsstring[]nometaobjects-core-typesThe function's declared parameter types, one field subtype per @args entry, in order (string, int, long, double, float, decimal, boolean, date, timestamp, uuid). Required when @args is not empty; an argument of another type is refused (ERR_INVALID_ORIGIN).
    @returnsstringyesmetaobjects-core-typesThe function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns.
    @schema string no
    origin.functionA value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's column type, so the call is checked, never free SQL. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it. types/origin.md#originfunction
    metaobjects-core-typesThe function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's column type, so the column has that type whatever the function returns.The function's declared return type, a field subtype; it must be the carrying field's subtype (ERR_INVALID_ORIGIN). The view casts the call to the field's full column type, which would hide a wrong declaration, so meta verify --db checks it against the function's real return type (pg_proc).
    @schema
    metaobjects-core-typesThe name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).
    @dbSetName metaobjects-core-typesThe name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).
    @dbSetName metaobjects-core-typesOptional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('caseId.patientId.hasActiveHipaaConsent'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19).Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: "", startOf? }) on a date or timestamp field (rc.19).
    @grain metaobjects-core-typesThe name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: case_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).The name of this object's collection, in the object's own casing (e.g. 'ConsignmentHistory', 'Queues'): the C# DbSet property, the REST collection segment (snake_cased: consignment_history), the TypeScript collection exports and finders (list), and the reverse @via hop other objects walk to reach it. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own).
    @dbSetName