From b06cb5a8e0afa5220c4ceda45fa2a45d9f8ee8d1 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:02:39 -0500 Subject: [PATCH 1/9] fix: names constants skip derived fields (Java, Python), verify --db function matching, widened-extender warning, test the stringValueMap codec L3: Java and Python names generators emit no entry for a derived field of a table-read entity. L4: declared origin.function check allows integer widening, any* wildcards and variadics. L5: warn whenever an extender's base differs from the pre-rc.21 derivation. L8: JdbcCodecRoundTripTest covers the @stringValueMap enum. --- CHANGELOG.md | 19 ++++ .../spring/SpringNamesGenerator.java | 14 ++- .../spring/SpringNamesGeneratorTest.java | 34 ++++++ .../db/codec/JdbcCodecRoundTripTest.java | 105 ++++++++++++++++++ .../manager/db/test/CodecSchema.java | 5 +- .../omdb/src/test/resources/meta.codec.json | 8 ++ .../codegen/generators/names_generator.py | 11 ++ .../tests/codegen/test_names_derived_field.py | 58 ++++++++++ .../metadata/src/loader/validation-passes.ts | 44 +++++--- .../test/rc21b-view-vocabulary.test.ts | 32 ++++++ .../src/introspect/declared-functions.ts | 59 ++++++++-- .../test/declared-functions-match.test.ts | 56 ++++++++++ 12 files changed, 416 insertions(+), 29 deletions(-) create mode 100644 server/python/tests/codegen/test_names_derived_field.py create mode 100644 server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2667ad5c34..f89a48d1b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,25 @@ here.** no version, vocabulary or `metamodelVersion` changes here. See `docs/RELEASING.md`, "The vocabulary rule". +### Fixed + +- **Fix, Java and Python: `Names` has no entry for a derived field with no column.** The + TypeScript and C# names generators already left out a derived (`origin.*`) field of an entity + read from its table; Java and Python still emitted a column constant naming a column that does + not exist. They now match: a projection's or write-through entity's derived field keeps its + entry, an entity's does not. +- **Fix, TypeScript: `meta verify --db` accepts the function calls Postgres accepts.** The + declared `origin.function` signature check compared parameter types by exact name, so an + `integer` argument for a `bigint` or `numeric` parameter, a polymorphic `any*` parameter and a + variadic function were all reported as mismatches. It now allows integer to bigint to numeric + widening, treats `any*` parameters as wildcards and does not check a variadic function's arity. + A genuine mismatch (a narrowing, an unrelated type, a wrong return type) still fails. +- **Fix, TypeScript: the widened-extender warning covers every extender whose base changed.** An + extender with no identity of its own keeps its super's identity anchor (rc.21). The load warned + only for a TPH base read through a subtype column; it now warns whenever the base differs from + the pre-rc.21 derivation, naming both entities and the `identity.primary { extends: ... }` + that keeps the old one. + ## [1.3.0] — 2026-11-17 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 5a7b9f4ac1..5befb6cc23 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 @@ -248,6 +248,10 @@ static ObjectNames resolveObjectNames(MetaObject obj, String strategy) { // refusal at all -- see SourceResolution's class doc. MetaSource source = SourceResolution.primaryRdbSource(obj); if (source == null) return null; + // rc.21 (U7): a derived field of an object read from its table is no column of that + // table, so it has no names entry. A projection's or write-through entity's derived + // field is a column of its view and keeps its entry. + boolean columnless = source.isWritable() && !obj.isWriteThrough(); return new ObjectNames( obj.getType(), obj.getSubType(), @@ -259,7 +263,7 @@ static ObjectNames resolveObjectNames(MetaObject obj, String strategy) { // ADR-0039: getMetaFields() is the RESOLVING accessor (includeParentData // defaults to true) -- an inherited @column must resolve here, or the emitted // constant would disagree with the column a hand-written consumer binds to. - fieldMap(obj.getMetaFields(), strategy), fieldMap(obj.getMetaFields(false), strategy), + fieldMap(obj.getMetaFields(), strategy, columnless), fieldMap(obj.getMetaFields(false), strategy, columnless), keysOf(obj.getIdentities(true)), keysOf(obj.getIdentities(false)), keysOf(obj.getChildren(LookupIndex.class, true)), keysOf(obj.getChildren(LookupIndex.class, false)), @@ -385,9 +389,11 @@ static String flattenedColumnMember(String fieldName, String memberName) { return namesMember(fieldName) + "_" + namesMember(memberName) + "_COLUMN"; } - private static Map fieldMap(Collection src, String strategy) { + private static Map fieldMap( + Collection src, String strategy, boolean skipDerived) { Map out = new LinkedHashMap<>(); for (MetaField field : src) { + if (skipDerived && field.isDerived()) continue; out.put(field.getName(), fieldNamesOf(field, strategy)); } return out; @@ -454,10 +460,12 @@ static MetaObject namesArtifactSuperOf(MetaObject obj) { static ObjectNames resolveSuperFragmentNames(MetaObject obj, String strategy) { if (!declaresNamesContent(obj)) return null; Collection own = obj.getMetaFields(false); + // rc.21 (U7): an abstract ENTITY's derived field is no column of the tables extending it. + boolean columnless = MetaObject.SUBTYPE_ENTITY.equals(obj.getSubType()); return new ObjectNames( obj.getType(), obj.getSubType(), obj.getShortName(), Map.of(), Map.of(), - fieldMap(obj.getMetaFields(), strategy), fieldMap(own, strategy), + fieldMap(obj.getMetaFields(), strategy, columnless), fieldMap(own, strategy, columnless), keysOf(obj.getIdentities(true)), keysOf(obj.getIdentities(false)), keysOf(obj.getChildren(LookupIndex.class, true)), keysOf(obj.getChildren(LookupIndex.class, false)), 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 5d872b0986..4e2364371a 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 @@ -180,6 +180,40 @@ public void emitsStaticFinalConstantsForTableAndColumns() throws IOException { assertTrue(src, src.contains("protected AuthorNames() {}")); } + // rc.21 (U7): a derived field of an entity read from its table is no column of that table. + private static final String DERIVED_FIXTURE = """ + { + "metadata.root": { "package": "acme::ledger", "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": "pk", "@fields": ["id"] } } + ] } }, + { "object.projection": { "name": "AccountView", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_accounts" } }, + { "field.long": { "name": "id", "extends": "acme::ledger::Account.id" } }, + { "field.int": { "name": "doubled", "children": [ + { "origin.computed": { "@expr": { + "fn": "coalesce", "args": [ { "field": "score" }, { "value": 0 } ] } } } ] } }, + { "identity.primary": { "name": "pk", "extends": "acme::ledger::Account.pk" } } + ] } } + ] } + } + """; + + @Test + public void aTableEntitysDerivedFieldHasNoNamesEntryButAProjectionsKeepsItsColumn() throws IOException { + String account = emit(DERIVED_FIXTURE, "acme/ledger/AccountNames.java", Map.of()); + assertTrue(account, account.contains("SCORE_COLUMN")); + assertFalse(account, account.contains("IS_HIGH")); + String view = emit(DERIVED_FIXTURE, "acme/ledger/AccountViewNames.java", Map.of()); + assertTrue(view, view.contains("DOUBLED_COLUMN = \"doubled\";")); + } + @Test public void anImplicitlyNamedSourceStillResolvesItsPhysicalName() throws IOException { // The regression that matters: getTableName() returns null when @table is 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 1446b261a8..825644efe0 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 @@ -347,6 +347,111 @@ public void intBackedEnumThrowsOnAnUnmappedStoredValue() throws Exception { } } + private static ValueObject sampleRow(MetaObject mo, String label) { + ValueObject vo = (ValueObject) mo.newInstance(); + vo.setString("label", label); + vo.setInt("count", 1); + vo.setLong("bignum", 1L); + vo.setBoolean("active", false); + vo.setDouble("ratio", 0d); + vo.setFloat("rate", 0f); + vo.setObject("amount", java.math.BigDecimal.ZERO); + vo.setDate("createdAt", new Date(0)); + vo.setObject("startTime", LocalTime.of(0, 0, 0)); + return vo; + } + + /** + * A {@code @stringValueMap} enum stores the member's mapped string and hands the caller the + * member back, on a write, a read and a filter argument alike. Asks the database what it + * stored, because a symmetric bug (symbol written, symbol read) round-trips on its own. + */ + @Test + public void stringValueMapEnumRoundTripsThroughItsStoredString() throws Exception { + MetaObject mo = registry.findMetaObjectByName("codectest::Sample"); + assertNotNull(mo); + + ObjectConnection oc = omdb.getConnection(); + try { + String label = "string-map-enum-" + System.currentTimeMillis(); + ValueObject vo = sampleRow(mo, label); + vo.setString("stage", "Done"); + omdb.createObject(oc, vo); + + Collection rows = omdb.getObjects(oc, mo, + new QueryOptions(new Expression("label", label, Expression.EQUAL))); + assertEquals("exactly one row written", 1, rows.size()); + assertEquals("the caller gets the member, not the stored string", + "Done", ((ValueObject) rows.iterator().next()).getString("stage")); + + try (Connection c = getConnection(); + PreparedStatement ps = c.prepareStatement( + "SELECT stage FROM CODEC_SAMPLE WHERE label = ?")) { + ps.setString(1, label); + try (ResultSet rs = ps.executeQuery()) { + assertTrue("row present for raw column read", rs.next()); + assertEquals("the column must hold the mapped string, not the symbol", + "q_done", rs.getString(1)); + } + } + + // A filter on the member binds the stored string too. + Collection filtered = omdb.getObjects(oc, mo, new QueryOptions( + new Expression("stage", "Done", Expression.EQUAL))); + assertTrue("a filter on the member must match the row stored as its string", + filtered.stream().anyMatch(r -> label.equals(((ValueObject) r).getString("label")))); + } finally { + omdb.releaseConnection(oc); + } + } + + /** + * An unmapped member throws on a write, and a stored string with no member throws on a + * read: nothing in the model describes either, so binding the symbol or surfacing the raw + * string would be a silently wrong row. + */ + @Test + public void stringValueMapEnumThrowsOnAnUnmappedMemberAndAnUnmappedStoredString() throws Exception { + MetaObject mo = registry.findMetaObjectByName("codectest::Sample"); + assertNotNull(mo); + + ObjectConnection oc = omdb.getConnection(); + try { + String label = "string-map-unmapped-" + System.currentTimeMillis(); + ValueObject bad = sampleRow(mo, label); + bad.setString("stage", "Cancelled"); // no entry in @stringValueMap + try { + omdb.createObject(oc, bad); + fail("writing a member with no stored string must throw"); + } catch (Exception e) { + assertTrue("the failure must name the member: " + messageChain(e), + messageChain(e).contains("Cancelled")); + assertTrue("the failure must name the attribute: " + messageChain(e), + messageChain(e).contains("stringValueMap")); + } + + ValueObject ok = sampleRow(mo, label); + ok.setString("stage", "Queued"); + omdb.createObject(oc, ok); + try (Connection c = getConnection(); + PreparedStatement ps = c.prepareStatement( + "UPDATE CODEC_SAMPLE SET stage = 'q_gone' WHERE label = ?")) { + ps.setString(1, label); + assertEquals("exactly one row corrupted", 1, ps.executeUpdate()); + } + try { + omdb.getObjects(oc, mo, + new QueryOptions(new Expression("label", label, Expression.EQUAL))); + fail("reading a stored string with no member must throw, not surface it"); + } catch (Exception e) { + assertTrue("the failure must name the stored value: " + messageChain(e), + messageChain(e).contains("q_gone")); + } + } finally { + omdb.releaseConnection(oc); + } + } + /** Every message in a throwable's cause chain, joined — OMDB wraps driver exceptions. */ private static String messageChain(Throwable t) { StringBuilder sb = new StringBuilder(); diff --git a/server/java/omdb/src/test/java/com/metaobjects/manager/db/test/CodecSchema.java b/server/java/omdb/src/test/java/com/metaobjects/manager/db/test/CodecSchema.java index a1d8aab0ec..961bb7f42a 100644 --- a/server/java/omdb/src/test/java/com/metaobjects/manager/db/test/CodecSchema.java +++ b/server/java/omdb/src/test/java/com/metaobjects/manager/db/test/CodecSchema.java @@ -57,7 +57,10 @@ private CodecSchema() {} // int-backed field.enum (@intValueMap): the member symbol persists as // its declared INTEGER, so this column's type differs from `status` // above even though both are field.enum. - + " priority INTEGER\n" + + " priority INTEGER,\n" + // string-backed field.enum (@stringValueMap): the member persists as its mapped + // stored string, not its symbol. + + " stage VARCHAR(20)\n" + ")"; /** Executes the CODEC_SAMPLE DDL on a fresh connection from {@code connector}. */ diff --git a/server/java/omdb/src/test/resources/meta.codec.json b/server/java/omdb/src/test/resources/meta.codec.json index a717669e0a..454bfce1cf 100644 --- a/server/java/omdb/src/test/resources/meta.codec.json +++ b/server/java/omdb/src/test/resources/meta.codec.json @@ -103,6 +103,14 @@ "@intValueMap": {"DRAFT": 0, "PUBLISHED": 5, "ARCHIVED": 9} } }, + { + "field.enum": { + "name": "stage", + "@column": "stage", + "@values": ["Queued", "Done", "Failed"], + "@stringValueMap": {"Queued": "q_queued", "Done": "q_done", "Failed": "q_failed"} + } + }, { "identity.primary": { "name": "primary", diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index f814a083b0..f20e7070d8 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -110,6 +110,7 @@ ) from metaobjects.shared.base_types import TYPE_FIELD, TYPE_IDENTITY, TYPE_INDEX from metaobjects.naming_refs import ref_target +from metaobjects.meta.core.object.object_constants import OBJECT_SUBTYPE_ENTITY from metaobjects.source_resolution import primary_rdb_source #: The nodes whose DATABASE index name this module carries. @@ -466,7 +467,17 @@ def carried_by_super(node: MetaData) -> bool: # `.`, the path the naming corpus uses. columns: list[tuple[str, str]] = [] flattened: list[tuple[MetaData, list[tuple[str, _Const]]]] = [] + # rc.21 (U7): a derived field of an object read from its table (or of an abstract entity + # its tables extend) is no column, so it has no names entry. A projection's or + # write-through entity's derived field is a column of its view and keeps its entry. + columnless = ( + entity.sub_type == OBJECT_SUBTYPE_ENTITY + if fragment + else src is not None and src.is_writable() and not entity.is_write_through() + ) for field in sorted(entity.fields(), key=lambda f: f.name): + if columnless and field.is_derived(): + continue members = _flattened_members(field, strategy) if members is None: column = resolve_column_name(field, strategy) diff --git a/server/python/tests/codegen/test_names_derived_field.py b/server/python/tests/codegen/test_names_derived_field.py new file mode 100644 index 0000000000..485f053b9a --- /dev/null +++ b/server/python/tests/codegen/test_names_derived_field.py @@ -0,0 +1,58 @@ +"""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 module carries no entry for it. A projection's derived field IS a column of its +view and keeps its entry. Mirrors the TypeScript ``names-derived-field`` test.""" +from __future__ import annotations + +import json +from pathlib import Path + +import metaobjects.core_types # noqa: F401 — side-effect: registers attr classes +from metaobjects import InMemoryStringSource, MetaDataFormat, MetaDataLoader +from metaobjects.codegen.config import GenConfig +from metaobjects.codegen.generators.names_generator import names_generator +from metaobjects.codegen.runner import run_gen + +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"}}]}}, + ], + } +} + + +def test_a_table_entitys_derived_field_has_no_names_entry_but_a_projections_keeps_its_column( + tmp_path: Path, +) -> None: + result = MetaDataLoader().load([ + InMemoryStringSource(json.dumps(MODEL), format=MetaDataFormat.JSON, id="derived.json"), + ]) + assert [str(e) for e in result.errors] == [] + out = tmp_path / "gen" + run_gen(GenConfig(out_dir=str(out), column_naming="snake_case"), result.root, + generators=[names_generator()]) + files = {p.name: p.read_text() for p in out.rglob("*.py")} + + account = files["account_names.py"] + assert "ACCOUNT_SCORE_COLUMN" in account + assert "IS_HIGH" not in account + assert '"isHigh"' not in account + + view = files["account_view_names.py"] + assert 'ACCOUNTVIEW_DOUBLED_COLUMN: Final[str] = "doubled"' in view diff --git a/server/typescript/packages/metadata/src/loader/validation-passes.ts b/server/typescript/packages/metadata/src/loader/validation-passes.ts index 05a74b8019..da1c2f06ac 100644 --- a/server/typescript/packages/metadata/src/loader/validation-passes.ts +++ b/server/typescript/packages/metadata/src/loader/validation-passes.ts @@ -989,6 +989,7 @@ function _deriveBaseEntity( fieldName: string, originSource: ErrorSource, errors: ParseError[], + preRc21 = false, ): MetaData | undefined { if (obj.subType !== OBJECT_SUBTYPE_PROJECTION) return obj; // ADR-0042 — a bare extends owner resolves in this projection's package. @@ -1013,7 +1014,8 @@ function _deriveBaseEntity( // 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 + // `preRc21` re-derives the base as it was before 1b existed, so the widening warning can compare. + if (!preRc21 && !ownIdentity && superProjection !== undefined && superProjection.type === TYPE_OBJECT && superProjection.subType === OBJECT_SUBTYPE_PROJECTION && _anchorsByIdentity(superProjection)) { return _deriveBaseEntity(superProjection, root, fieldName, originSource, errors); } @@ -1042,7 +1044,7 @@ function _deriveBaseEntity( // base entity its super has (its inherited identity and fields are anchored there). const sup = obj.superResolved; if (targets.size === 0 && sup !== undefined && sup.type === TYPE_OBJECT && sup.subType === OBJECT_SUBTYPE_PROJECTION) { - return _deriveBaseEntity(sup, root, fieldName, originSource, errors); + return _deriveBaseEntity(sup, root, fieldName, originSource, errors, preRc21); } if (targets.size > 1) { const names = [...targets].map((t) => `"${t.name}"`).join(", "); @@ -1067,10 +1069,15 @@ function _deriveBaseEntity( } /** - * 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. + * rc.21 part B (I2, widened by L5): warn when an extender's base CHANGED with the identity-anchor + * rule. A projection with no identity of its own keeps the base its super anchors on; before rc.21 + * its base came from its own fields' entities. Whenever the two differ, the extender's view is no + * longer the one the old rule lowered, and the next `meta migrate` replaces it. + * + * The TPH case is named precisely: a field bound to a column only a subtype carries, over the TPH + * base, with no `@filter` on the discriminator, whose view held only the subtype's rows and now + * holds every row of the base. An extender that scopes its rows by the discriminator keeps the + * same rows and is not warned about. */ export function validateExtenderSubtypeScope(root: MetaData): string[] { const warnings: string[] = []; @@ -1083,20 +1090,24 @@ export function validateExtenderSubtypeScope(root: MetaData): string[] { 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; + // The base the pre-rc.21 derivation gave. None: no view was lowered before, so none is replaced. + const legacyBase = _deriveBaseEntity(obj, root, "@extends", obj.source, [], true); + if (legacyBase === undefined || legacyBase === base) 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; + if (discriminator !== undefined && filterKeys(effectiveProjectionFilter(obj)).includes(discriminator)) continue; const referrerPkg = obj.package ?? obj.fileDefaultPackage ?? ""; // 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 (discriminator !== 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( @@ -1105,6 +1116,13 @@ export function validateExtenderSubtypeScope(root: MetaData): string[] { `(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 }.`, ); + } else { + warnings.push( + `object.projection ${obj.name}: its base entity is now ${base.name}, where before it was ${legacyBase.name} ` + + `(rc.21: an extender with no identity of its own keeps its super's identity anchor), so its view is lowered ` + + `differently and the next meta migrate replaces it. To keep the old base, declare ` + + `identity.primary { extends: ${legacyBase.name}. }.`, + ); } } return warnings; 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 53f53731e3..c1b9cda6c9 100644 --- a/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts +++ b/server/typescript/packages/metadata/test/rc21b-view-vocabulary.test.ts @@ -287,6 +287,38 @@ describe("an extender whose view widened over a TPH base", () => { }); }); +// L5: the identity-anchor rule applies to EVERY extender with no identity of its own, not only a TPH +// one. An extender over plain entities whose base changed from the pre-rc.21 derivation warns too. +describe("an extender whose base changed, over a non-TPH base", () => { + const entities = [ + { "object.entity": { name: "Customer", children: [ + { "source.rdb": { "@table": "customers" } }, { "field.long": { name: "id" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { name: "Invoice", children: [ + { "source.rdb": { "@table": "invoices" } }, { "field.long": { name: "id" } }, { "field.string": { name: "ref" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.projection": { name: "CustomerBase", abstract: true, children: [ + { "field.long": { name: "customerId", extends: "Customer.id" } }, + { "identity.primary": { name: "id", extends: "Customer.primary" } } ] } }, + ]; + const row = (children: unknown[]) => ({ "object.projection": { name: "InvoiceRow", extends: "CustomerBase", children: [ + { "source.rdb": { "@kind": "view", "@view": "v_invoice_rows" } }, ...children ] } }); + async function warningsOf(...extra: unknown[]): Promise { + const { errors, warnings } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({ "metadata.root": { package: "acme", children: [...entities, ...extra] } }))]); + expect(errors).toEqual([]); + return warnings.map((w) => (typeof w === "string" ? w : (w as { message: string }).message)); + } + test("warns that the base is now the super's, naming both and the remedy", async () => { + const w = (await warningsOf(row([{ "field.string": { name: "ref", extends: "Invoice.ref" } }]))).filter((m) => m.includes("InvoiceRow")); + expect(w.length).toBe(1); + expect(w[0]).toMatch(/its base entity is now Customer, where before it was Invoice/); + expect(w[0]).toMatch(/identity.primary \{ extends: Invoice. \}/); + }); + test("an extender whose own fields still name the super's base is not warned about", async () => { + expect((await warningsOf(row([{ "field.long": { name: "other", extends: "Customer.id" } }]))).filter((m) => m.includes("InvoiceRow"))).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 () => { 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 41b3657ae0..2dbc12a2c2 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -8,6 +8,10 @@ // 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. +// +// What it accepts, as Postgres does: an `integer` argument for a `bigint` or `numeric` parameter (and +// `bigint` for `numeric`), any argument for a polymorphic `any*` parameter, and any arity for the +// trailing parameter of a `VARIADIC` function. import type { Kysely } from "kysely"; import { sql } from "kysely"; @@ -27,7 +31,7 @@ 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 { +export interface DeclaredFunction { readonly where: string; readonly schema: string; readonly name: string; @@ -37,12 +41,25 @@ interface DeclaredFunction { } /** One overload as `pg_proc` has it, its types spelled by `format_type(oid, NULL)`. */ -interface PgFunction { +export 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; + /** `provariadic <> 0`: the last parameter is `VARIADIC`, so a call may pass any number of it. */ + readonly variadic: boolean; +} + +/** Implicit numeric widening Postgres applies to a call argument: a declared type may call a wider parameter. */ +const WIDER_NUMERIC: Readonly> = { + integer: ["bigint", "numeric"], + bigint: ["numeric"], +}; + +/** A polymorphic parameter (`anyelement`, `anyarray`, `anycompatible`, the pseudo-type `"any"`, ...) takes any argument. */ +function isPolymorphic(pgType: string): boolean { + return pgType.replaceAll('"', "").startsWith("any"); } const TEXT_TYPES = ["text", "character varying", "character"] as const; @@ -127,21 +144,37 @@ export function declaredFunctions(root: MetaData): DeclaredFunction[] { } async function overloads(db: Kysely, schema: string, name: string): Promise { - const result = await sql<{ args: string[]; defaults: number; returns: string; retset: boolean }>` + const result = await sql<{ args: string[]; defaults: number; returns: string; retset: boolean; variadic: 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, - p.pronargdefaults::int AS defaults, 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, + (p.provariadic <> 0) AS variadic 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, defaults: Number(r.defaults), returns: r.returns, retset: r.retset })); + return result.rows.map((r) => ({ args: r.args, defaults: Number(r.defaults), returns: r.returns, retset: r.retset, variadic: r.variadic })); } -function matches(declared: DeclaredFunction, fn: PgFunction): boolean { +/** Whether Postgres accepts an argument of one of the `accepted` type names for a parameter of type `actual`. */ +function parameterAccepts(accepted: readonly string[], actual: string): boolean { + if (accepted.length === 0 || isPolymorphic(actual)) return true; + return accepted.some((a) => a === actual || (WIDER_NUMERIC[a]?.includes(actual) ?? false)); +} + +/** Exported for the unit tests: whether one `pg_proc` overload can serve the declared call. */ +export function signatureMatches(declared: DeclaredFunction, fn: PgFunction): boolean { + // A set-returning function is not a scalar call. + if (fn.retset) return false; + if (declared.returns.length > 0 && !declared.returns.includes(fn.returns)) return false; + // A variadic function takes any number of trailing arguments, so its arity and its trailing + // parameter types are not checked; the leading fixed parameters still are. + if (fn.variadic) { + const fixed = Math.min(fn.args.length - 1, declared.params.length); + return declared.params.slice(0, fixed).every((accepted, i) => parameterAccepts(accepted, fn.args[i]!)); + } // 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]!)); + if (declaredCount > fn.args.length || declaredCount < fn.args.length - fn.defaults) return false; + return declared.params.every((accepted, i) => parameterAccepts(accepted, fn.args[i]!)); } /** @@ -150,14 +183,16 @@ function matches(declared: DeclaredFunction, fn: PgFunction): boolean { */ /** 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."; + "origin.function signatures are compared by plain type name, allowing Postgres's implicit integer " + + "widening (integer to bigint to numeric) and treating polymorphic (any*) parameters as wildcards: " + + "a json, array, enum or user-defined kind is not type-checked (only the arity is), a variadic " + + "function's arity is not checked, 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)) { const found = await overloads(db, declared.schema, declared.name); - if (found.some((fn) => matches(declared, fn))) continue; + if (found.some((fn) => signatureMatches(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 diff --git a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts new file mode 100644 index 0000000000..2785f1cd45 --- /dev/null +++ b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts @@ -0,0 +1,56 @@ +// L4: `verify --db` compares a declared origin.function call to each pg_proc overload. The +// comparison must accept what Postgres accepts (implicit integer widening, polymorphic and +// variadic parameters) and still refuse a genuine mismatch. +import { describe, expect, test } from "bun:test"; +import { signatureMatches, type DeclaredFunction, type PgFunction } from "../src/introspect/declared-functions.js"; + +const declared = (params: readonly (readonly string[])[], returns: readonly string[] = ["numeric"]): DeclaredFunction => ({ + where: "Row.f", schema: "app", name: "f", declared: "(...)", params, returns, +}); +const pg = (args: string[], over: Partial = {}): PgFunction => ({ + args, defaults: 0, returns: "numeric", retset: false, variadic: false, ...over, +}); + +describe("declared origin.function signature matching", () => { + test("an exact signature matches", () => { + expect(signatureMatches(declared([["bigint"]]), pg(["bigint"]))).toBe(true); + }); + + test("Postgres's implicit integer widening is accepted: integer to bigint to numeric", () => { + expect(signatureMatches(declared([["integer"]]), pg(["bigint"]))).toBe(true); + expect(signatureMatches(declared([["integer"]]), pg(["numeric"]))).toBe(true); + expect(signatureMatches(declared([["bigint"]]), pg(["numeric"]))).toBe(true); + }); + + test("a narrowing is a mismatch: bigint to integer, numeric to bigint", () => { + expect(signatureMatches(declared([["bigint"]]), pg(["integer"]))).toBe(false); + expect(signatureMatches(declared([["numeric"]]), pg(["bigint"]))).toBe(false); + }); + + test("an unrelated parameter type is still a mismatch", () => { + expect(signatureMatches(declared([["bigint"]]), pg(["text"]))).toBe(false); + expect(signatureMatches(declared([["text", "character varying"]]), pg(["bigint"]))).toBe(false); + }); + + test("a polymorphic parameter takes any argument", () => { + for (const poly of ["anyelement", "anyarray", "anynonarray", "anycompatible", '"any"']) { + expect(signatureMatches(declared([["text"]]), pg([poly]))).toBe(true); + } + }); + + test("a variadic function takes any arity for its trailing parameter, its fixed ones still checked", () => { + const variadic = pg(["text", "anyarray"], { variadic: true }); + expect(signatureMatches(declared([["text"], ["integer"], ["integer"], ["integer"]]), variadic)).toBe(true); + expect(signatureMatches(declared([["text"]]), variadic)).toBe(true); + expect(signatureMatches(declared([["bigint"], ["integer"]]), variadic)).toBe(false); + }); + + test("the return type is still compared exactly, and a set-returning function never matches", () => { + expect(signatureMatches(declared([["bigint"]], ["integer"]), pg(["bigint"]))).toBe(false); + expect(signatureMatches(declared([["bigint"]]), pg(["bigint"], { retset: true }))).toBe(false); + }); + + test("a wrong arity is still a mismatch for a non-variadic function", () => { + expect(signatureMatches(declared([["bigint"], ["bigint"]]), pg(["bigint"]))).toBe(false); + }); +}); From acd363f76d4b71eb856db51a219f631c06bcfe95 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:22:44 -0500 Subject: [PATCH 2/9] no-mistakes(review): port M8 compensation; variadic arity check --- .../spring/SpringNamesGenerator.java | 26 +++++-- .../spring/SpringNamesGeneratorTest.java | 49 +++++++++++++ .../codegen/generators/names_generator.py | 22 +++++- .../tests/codegen/test_names_derived_field.py | 68 +++++++++++++++++++ .../src/introspect/declared-functions.ts | 10 ++- .../test/declared-functions-match.test.ts | 12 ++++ 6 files changed, 176 insertions(+), 11 deletions(-) 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 5befb6cc23..83cb76a804 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 @@ -252,6 +252,25 @@ static ObjectNames resolveObjectNames(MetaObject obj, String strategy) { // table, so it has no names entry. A projection's or write-through entity's derived // field is a column of its view and keeps its entry. boolean columnless = source.isWritable() && !obj.isWriteThrough(); + // ADR-0039: getMetaFields() is the RESOLVING accessor (includeParentData + // defaults to true) -- an inherited @column must resolve here, or the emitted + // constant would disagree with the column a hand-written consumer binds to. + Map fields = fieldMap(obj.getMetaFields(), strategy, columnless); + Map ownFields = fieldMap(obj.getMetaFields(false), strategy, columnless); + MetaObject 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 COLUMNS_BY_FIELD + // would reference a constant no emitted class declares. + if (!columnless && superObj != null + && MetaObject.SUBTYPE_ENTITY.equals(superObj.getSubType()) + && GeneratorUtil.isAbstract(superObj)) { + for (MetaField field : obj.getMetaFields()) { + if (field.isDerived() && !ownFields.containsKey(field.getName())) { + ownFields.put(field.getName(), fieldNamesOf(field, strategy)); + } + } + } return new ObjectNames( obj.getType(), obj.getSubType(), @@ -260,14 +279,11 @@ static ObjectNames resolveObjectNames(MetaObject obj, String strategy) { // stopped meaning a table, a view and a procedure depending on the object. obj.getShortName(), sourcesOf(obj, true), sourcesOf(obj, false), - // ADR-0039: getMetaFields() is the RESOLVING accessor (includeParentData - // defaults to true) -- an inherited @column must resolve here, or the emitted - // constant would disagree with the column a hand-written consumer binds to. - fieldMap(obj.getMetaFields(), strategy, columnless), fieldMap(obj.getMetaFields(false), strategy, columnless), + fields, ownFields, keysOf(obj.getIdentities(true)), keysOf(obj.getIdentities(false)), keysOf(obj.getChildren(LookupIndex.class, true)), keysOf(obj.getChildren(LookupIndex.class, false)), - namesArtifactSuperOf(obj)); + superObj); } /** 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 4e2364371a..42e572e234 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 @@ -214,6 +214,55 @@ public void aTableEntitysDerivedFieldHasNoNamesEntryButAProjectionsKeepsItsColum assertTrue(view, view.contains("DOUBLED_COLUMN = \"doubled\";")); } + // rc.21 fix round (M8): an abstract-entity fragment drops its derived field (no column of + // the tables extending it), so a write-through extender — whose read view HAS that column — + // declares the constant itself. Mirrors the TypeScript names-derived-field and C# + // NamesGeneratorTests M8 tests. + private static final String M8_FIXTURE = """ + { + "metadata.root": { "package": "acme::tracked", "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": "pk", "@fields": ["id"] } } + ] } }, + { "object.projection": { "name": "HighAccounts", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_high_accounts" } }, + { "field.long": { "name": "id", "extends": "acme::tracked::Account.id" } }, + { "identity.primary": { "name": "pk", "extends": "acme::tracked::Account.pk" } } + ] } } + ] } + } + """; + + @Test + public void aWriteThroughExtenderDeclaresTheDerivedColumnItsFragmentDrops() throws Exception { + Path outDir = tempFolder.newFolder().toPath(); + Path workspace = tempFolder.newFolder().toPath(); + SpringNamesGenerator gen = new SpringNamesGenerator(); + gen.setArgs(Map.of("outputDir", outDir.toString())); + gen.execute(SpringTestFixtures.loadFixture(workspace, "names-m8", M8_FIXTURE)); + + // The fragment drops the derived field: no table extending Tracked has an is_high column + // OF ITS OWN — Account's read view does, which is the other half of the assertion. + String tracked = Files.readString(outDir.resolve("acme/tracked/TrackedNames.java")); + assertFalse(tracked, tracked.contains("IS_HIGH")); + + // COLUMNS_BY_FIELD references IS_HIGH_COLUMN; without the re-declaration no emitted + // class declares it and the generated .java does not compile — which is what + // compileAll proves, not just the substring. + String account = Files.readString(outDir.resolve("acme/tracked/AccountNames.java")); + assertTrue(account, account.contains("public static final String IS_HIGH_COLUMN = \"is_high\";")); + compileAll(outDir); + } + @Test public void anImplicitlyNamedSourceStillResolvesItsPhysicalName() throws IOException { // The regression that matters: getTableName() returns null when @table is diff --git a/server/python/src/metaobjects/codegen/generators/names_generator.py b/server/python/src/metaobjects/codegen/generators/names_generator.py index f20e7070d8..44531d4a25 100644 --- a/server/python/src/metaobjects/codegen/generators/names_generator.py +++ b/server/python/src/metaobjects/codegen/generators/names_generator.py @@ -475,18 +475,34 @@ def carried_by_super(node: MetaData) -> bool: if fragment else src is not None and src.is_writable() and not entity.is_write_through() ) + + # 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, rather than + # re-exporting them from a super module that does not define them. + def dropped_by_super_fragment(field: MetaData) -> bool: + return ( + not fragment + and not columnless + and field.is_derived() + and super_obj is not None + and super_obj.sub_type == OBJECT_SUBTYPE_ENTITY + and super_obj.is_abstract + ) + for field in sorted(entity.fields(), key=lambda f: f.name): if columnless and field.is_derived(): continue + inherited = carried_by_super(field) and not dropped_by_super_fragment(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))) + groups.append(("fields", _field_consts(field, column), inherited)) else: # A flattened field has no column of its own: it keeps its `_FIELD` constant and # its members carry the columns. - groups.append(("fields", _field_consts(field, None), carried_by_super(field))) + groups.append(("fields", _field_consts(field, None), inherited)) if members: flattened.append((field, _flattened_member_consts(field, members))) @@ -510,7 +526,7 @@ def carried_by_super(node: MetaData) -> bool: kept.append(const) columns.append((key, const.member)) if kept: - groups.append(("fields", kept, carried_by_super(field))) + groups.append(("fields", kept, carried_by_super(field) and not dropped_by_super_fragment(field))) for type_name in (TYPE_IDENTITY, TYPE_INDEX): keys = sorted( diff --git a/server/python/tests/codegen/test_names_derived_field.py b/server/python/tests/codegen/test_names_derived_field.py index 485f053b9a..a98b9ddb21 100644 --- a/server/python/tests/codegen/test_names_derived_field.py +++ b/server/python/tests/codegen/test_names_derived_field.py @@ -4,7 +4,9 @@ view and keeps its entry. Mirrors the TypeScript ``names-derived-field`` test.""" from __future__ import annotations +import importlib import json +import sys from pathlib import Path import metaobjects.core_types # noqa: F401 — side-effect: registers attr classes @@ -56,3 +58,69 @@ def test_a_table_entitys_derived_field_has_no_names_entry_but_a_projections_keep view = files["account_view_names.py"] assert 'ACCOUNTVIEW_DOUBLED_COLUMN: Final[str] = "doubled"' in view + + +# rc.21 fix round (M8): an abstract-entity fragment drops its derived field (no column of the +# tables extending it), so a write-through extender — whose read view HAS that column — +# declares the constant itself rather than re-exporting it from a super module that does not +# define it. Mirrors the TypeScript/C# M8 tests. +M8_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"}}]}}, + # The projection's @filter reaching isHigh is what lets the abstract entity's + # derived field load clean (it is lowered inline where it is reached) — the same + # shape the TypeScript/C# M8 fixtures carry. + {"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"}}]}}, + ], + } +} + + +def test_a_write_through_extender_declares_the_derived_column_its_fragment_drops( + tmp_path: Path, +) -> None: + result = MetaDataLoader().load([ + InMemoryStringSource(json.dumps(M8_MODEL), format=MetaDataFormat.JSON, id="m8.json"), + ]) + assert [str(e) for e in result.errors] == [] + out = tmp_path / "gen" + run_gen(GenConfig(out_dir=str(out), column_naming="snake_case"), result.root, + generators=[names_generator()]) + files = {p.name: p.read_text() for p in out.rglob("*.py")} + + tracked = files["tracked_names.py"] + assert "IS_HIGH" not in tracked + account = files["account_names.py"] + assert 'ACCOUNT_IS_HIGH_COLUMN: Final[str] = "is_high"' in account + assert "TRACKED_IS_HIGH_COLUMN" not in account + + # The failure mode the fix closes is at IMPORT time: before it, account_names re-exported + # TRACKED_IS_HIGH_COLUMN from a module that does not define it — an ImportError. Import + # the generated package for real, as the compile-conformance lane does. + account_path = next(p for p in out.rglob("account_names.py")) + dotted = ".".join(account_path.relative_to(tmp_path).with_suffix("").parts) + saved = list(sys.path) + sys.path.insert(0, str(tmp_path)) + try: + module = importlib.import_module(dotted) + assert module.ACCOUNT_IS_HIGH_COLUMN == "is_high" + finally: + sys.path[:] = saved + for name in [m for m in sys.modules if m.split(".")[0] == dotted.split(".")[0]]: + del sys.modules[name] 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 2dbc12a2c2..75cb67883a 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -164,9 +164,12 @@ export function signatureMatches(declared: DeclaredFunction, fn: PgFunction): bo // A set-returning function is not a scalar call. if (fn.retset) return false; if (declared.returns.length > 0 && !declared.returns.includes(fn.returns)) return false; - // A variadic function takes any number of trailing arguments, so its arity and its trailing - // parameter types are not checked; the leading fixed parameters still are. + // A variadic function takes any number of trailing arguments, so its trailing parameter's + // count and type are not checked; Postgres still requires every non-defaulted fixed parameter + // (a VARIADIC parameter cannot itself carry a default), and the leading fixed parameter types + // still are. if (fn.variadic) { + if (declared.params.length < fn.args.length - 1 - fn.defaults) return false; const fixed = Math.min(fn.args.length - 1, declared.params.length); return declared.params.slice(0, fixed).every((accepted, i) => parameterAccepts(accepted, fn.args[i]!)); } @@ -186,7 +189,8 @@ export const DECLARED_FUNCTION_CHECK_LIMITS = "origin.function signatures are compared by plain type name, allowing Postgres's implicit integer " + "widening (integer to bigint to numeric) and treating polymorphic (any*) parameters as wildcards: " + "a json, array, enum or user-defined kind is not type-checked (only the arity is), a variadic " + - "function's arity is not checked, and a domain is compared by its own name, not its base type."; + "function's trailing parameter count and type are not checked (its required fixed 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[] = []; diff --git a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts index 2785f1cd45..80a633249f 100644 --- a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts +++ b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts @@ -45,6 +45,18 @@ describe("declared origin.function signature matching", () => { expect(signatureMatches(declared([["bigint"], ["integer"]]), variadic)).toBe(false); }); + test("a variadic function's required fixed parameters must all be declared", () => { + // Postgres rejects f() and f(5) against f(text, VARIADIC integer[]): every non-defaulted + // fixed parameter needs an argument (and a VARIADIC parameter cannot carry a default). + const variadic = pg(["text", "anyarray"], { variadic: true }); + expect(signatureMatches(declared([]), variadic)).toBe(false); + const twoFixed = pg(["text", "bigint", "anyarray"], { variadic: true }); + expect(signatureMatches(declared([["integer"]]), twoFixed)).toBe(false); + expect(signatureMatches(declared([["text"], ["integer"]]), twoFixed)).toBe(true); + // A defaulted trailing FIXED parameter may be omitted. + expect(signatureMatches(declared([["text"]]), pg(["text", "bigint", "anyarray"], { variadic: true, defaults: 1 }))).toBe(true); + }); + test("the return type is still compared exactly, and a set-returning function never matches", () => { expect(signatureMatches(declared([["bigint"]], ["integer"]), pg(["bigint"]))).toBe(false); expect(signatureMatches(declared([["bigint"]]), pg(["bigint"], { retset: true }))).toBe(false); From c008d1e9bd0198f58f9f31514641cd4dbe906b5c Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:29:47 -0500 Subject: [PATCH 3/9] no-mistakes(review): closed polymorphic pseudo-type set; anyflags test --- .../migrate-ts/src/introspect/declared-functions.ts | 8 +++++++- .../migrate-ts/test/declared-functions-match.test.ts | 7 +++++++ 2 files changed, 14 insertions(+), 1 deletion(-) 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 75cb67883a..433d2d8914 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -57,9 +57,15 @@ const WIDER_NUMERIC: Readonly> = { bigint: ["numeric"], }; +/** Postgres's closed set of polymorphic pseudo-types (`pg_type.typtype = 'p'`): each takes any argument. */ +const POLYMORPHIC_PSEUDOTYPES: readonly string[] = [ + "any", "anyarray", "anyelement", "anyenum", "anynonarray", "anyrange", "anymultirange", + "anycompatible", "anycompatiblearray", "anycompatiblenonarray", "anycompatiblerange", "anycompatiblemultirange", +]; + /** A polymorphic parameter (`anyelement`, `anyarray`, `anycompatible`, the pseudo-type `"any"`, ...) takes any argument. */ function isPolymorphic(pgType: string): boolean { - return pgType.replaceAll('"', "").startsWith("any"); + return POLYMORPHIC_PSEUDOTYPES.includes(pgType.replaceAll('"', "")); } const TEXT_TYPES = ["text", "character varying", "character"] as const; diff --git a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts index 80a633249f..36cd3b74a9 100644 --- a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts +++ b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts @@ -38,6 +38,13 @@ describe("declared origin.function signature matching", () => { } }); + test("a user-defined type merely named with the polymorphic prefix is not a wildcard", () => { + // Postgres's polymorphic pseudo-types are a closed set; `anyflags` is an ordinary user + // type, so a genuine mismatch on it is still reported rather than waved through. + expect(signatureMatches(declared([["text"]]), pg(["anyflags"]))).toBe(false); + expect(signatureMatches(declared([["anyflags"]]), pg(["anyflags"]))).toBe(true); + }); + test("a variadic function takes any arity for its trailing parameter, its fixed ones still checked", () => { const variadic = pg(["text", "anyarray"], { variadic: true }); expect(signatureMatches(declared([["text"], ["integer"], ["integer"], ["integer"]]), variadic)).toBe(true); From e53625088ed21058e4c553e6073cb5deedf3b4f0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:34:34 -0500 Subject: [PATCH 4/9] no-mistakes(review): apply reviewer inline fixes --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f89a48d1b3..fccd3d5d92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,9 @@ here.** declared `origin.function` signature check compared parameter types by exact name, so an `integer` argument for a `bigint` or `numeric` parameter, a polymorphic `any*` parameter and a variadic function were all reported as mismatches. It now allows integer to bigint to numeric - widening, treats `any*` parameters as wildcards and does not check a variadic function's arity. - A genuine mismatch (a narrowing, an unrelated type, a wrong return type) still fails. + widening, treats `any*` parameters as wildcards and does not check a variadic function's + trailing arity (its required fixed parameters still are). A genuine mismatch (a narrowing, + an unrelated type, a wrong return type) still fails. - **Fix, TypeScript: the widened-extender warning covers every extender whose base changed.** An extender with no identity of its own keeps its super's identity anchor (rc.21). The load warned only for a TPH base read through a subtype column; it now warns whenever the base differs from From fd45b0aa544f0d4b56f29f26b280639d9b351a75 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:45:35 -0500 Subject: [PATCH 5/9] no-mistakes(review): Port L5 warning to C# and L3 names fix to Kotlin --- CHANGELOG.md | 20 ++--- .../ViewVocabularyRc21LoaderTests.cs | 35 ++++++++ .../MetaObjects/Loader/ValidationPasses.cs | 56 +++++++++---- .../generator/kotlin/KotlinGenUtil.kt | 47 +++++++++-- .../kotlin/KotlinNamesGeneratorTest.kt | 84 +++++++++++++++++++ 5 files changed, 206 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fccd3d5d92..28c363e157 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,11 +41,11 @@ here.** ### Fixed -- **Fix, Java and Python: `Names` has no entry for a derived field with no column.** The - TypeScript and C# names generators already left out a derived (`origin.*`) field of an entity - read from its table; Java and Python still emitted a column constant naming a column that does - not exist. They now match: a projection's or write-through entity's derived field keeps its - entry, an entity's does not. +- **Fix, Java, Kotlin and Python: `Names` has no entry for a derived field with no + column.** The TypeScript and C# names generators already left out a derived (`origin.*`) field + of an entity read from its table; Java, Kotlin and Python still emitted a column constant + naming a column that does not exist. They now match: a projection's or write-through entity's + derived field keeps its entry, an entity's does not. - **Fix, TypeScript: `meta verify --db` accepts the function calls Postgres accepts.** The declared `origin.function` signature check compared parameter types by exact name, so an `integer` argument for a `bigint` or `numeric` parameter, a polymorphic `any*` parameter and a @@ -53,11 +53,11 @@ here.** widening, treats `any*` parameters as wildcards and does not check a variadic function's trailing arity (its required fixed parameters still are). A genuine mismatch (a narrowing, an unrelated type, a wrong return type) still fails. -- **Fix, TypeScript: the widened-extender warning covers every extender whose base changed.** An - extender with no identity of its own keeps its super's identity anchor (rc.21). The load warned - only for a TPH base read through a subtype column; it now warns whenever the base differs from - the pre-rc.21 derivation, naming both entities and the `identity.primary { extends: ... }` - that keeps the old one. +- **Fix, TypeScript and C#: the widened-extender warning covers every extender whose base + changed.** An extender with no identity of its own keeps its super's identity anchor (rc.21). + The load warned only for a TPH base read through a subtype column; it now warns whenever the + base differs from the pre-rc.21 derivation, naming both entities and the + `identity.primary { extends: ... }` that keeps the old one. ## [1.3.0] — 2026-11-17 diff --git a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs index 6987db82bd..9a5385e8f0 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/ViewVocabularyRc21LoaderTests.cs @@ -223,6 +223,41 @@ public void An_extender_whose_view_widened_over_a_tph_base_warns(string filter, else Assert.Empty(hit); } + // L5: the identity-anchor rule applies to EVERY extender with no identity of its own, not only a + // TPH one — an extender over plain entities whose base changed from the pre-rc.21 derivation warns too. + [Theory] + [InlineData("{ \"field.string\": { \"name\": \"ref\", \"extends\": \"Invoice.ref\" } }", true)] + [InlineData("{ \"field.long\": { \"name\": \"other\", \"extends\": \"Customer.id\" } }", false)] + public void An_extender_whose_base_changed_over_a_non_tph_base_warns(string ownField, bool warns) + { + var json = $$""" + { "metadata.root": { "package": "acme", "children": [ + { "object.entity": { "name": "Customer", "children": [ + { "source.rdb": { "@table": "customers" } }, { "field.long": { "name": "id" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.entity": { "name": "Invoice", "children": [ + { "source.rdb": { "@table": "invoices" } }, { "field.long": { "name": "id" } }, { "field.string": { "name": "ref" } }, + { "identity.primary": { "@fields": "id" } } ] } }, + { "object.projection": { "name": "CustomerBase", "abstract": true, "children": [ + { "field.long": { "name": "customerId", "extends": "Customer.id" } }, + { "identity.primary": { "name": "id", "extends": "Customer.primary" } } ] } }, + { "object.projection": { "name": "InvoiceRow", "extends": "CustomerBase", "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_invoice_rows" } }, + {{ownField}} ] } } ] } } + """; + var registry = Provider.ComposeRegistry(new[] { CoreTypes.CoreTypesProvider }); + var result = new MetaDataLoader(registry).Load([new InMemoryStringSource(json, format: MetaDataFormat.Json, id: "n.json")]); + Assert.Empty(result.Errors); + var hit = result.Warnings.Where(w => w.Contains("InvoiceRow", StringComparison.Ordinal)).ToList(); + if (warns) + { + var w = Assert.Single(hit); + Assert.Contains("its base entity is now Customer, where before it was Invoice", w); + Assert.Contains("identity.primary { extends: Invoice. }", w); + } + 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")] diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.cs index 608bc0ff38..53d6562753 100644 --- a/server/csharp/MetaObjects/Loader/ValidationPasses.cs +++ b/server/csharp/MetaObjects/Loader/ValidationPasses.cs @@ -1415,9 +1415,14 @@ 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. + /// rc.21 part B (I2, widened by L5): warn when an extender's base CHANGED with the identity-anchor + /// rule. A projection with no identity of its own keeps the base its super anchors on; before rc.21 + /// its base came from its own fields' entities. Whenever the two differ, the extender's view is no + /// longer the one the old rule lowered, and the next `meta migrate` replaces it. The TPH case is named + /// precisely: a field bound to a column only a subtype carries, over the TPH base, with no `@filter` + /// on the discriminator, whose view held only the subtype's rows and now holds every row of the base. + /// An extender that scopes its rows by the discriminator keeps the same rows and is not warned about. + /// TS validateExtenderSubtypeScope, message for message. /// public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) { @@ -1430,26 +1435,33 @@ public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) 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; + // The base the pre-rc.21 derivation gave. None: no view was lowered before, so none is replaced. + if (DeriveBaseEntity(obj, root, "@extends", obj.Source, new List(), preRc21: true) is not { } legacyBase + || ReferenceEquals(legacyBase, 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; + if (discriminator is not null + && ProjectionFilters.Effective(obj) is IReadOnlyDictionary filter + && FilterKeys(filter).Contains(discriminator)) continue; var pkg = NamingRefs.EffectivePackage(obj); // 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)) + if (discriminator is not null) { - 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; - subtypeFields.Add($"\"{f.Name}\" ({owner.Name}.{col})"); - subtype ??= owner; + 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; + 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; + subtypeFields.Add($"\"{f.Name}\" ({owner.Name}.{col})"); + subtype ??= owner; + } } if (subtype is not null) warnings.Add( @@ -1457,6 +1469,12 @@ public static IReadOnlyList ValidateExtenderSubtypeScope(MetaData root) $"{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 }}."); + else + warnings.Add( + $"object.projection {obj.Name}: its base entity is now {baseEntity.Name}, where before it was {legacyBase.Name} " + + "(rc.21: an extender with no identity of its own keeps its super's identity anchor), so its view is lowered " + + "differently and the next meta migrate replaces it. To keep the old base, declare " + + $"identity.primary {{ extends: {legacyBase.Name}. }}."); } return warnings.AsReadOnly(); } @@ -1470,7 +1488,8 @@ private static bool AnchorsByIdentity(MetaData obj) } private static MetaData? DeriveBaseEntity( - MetaData obj, MetaData root, string fieldName, ErrorSource originSource, List errors) + MetaData obj, MetaData root, string fieldName, ErrorSource originSource, List errors, + bool preRc21 = false) { if (obj.SubType != OBJECT_SUBTYPE_PROJECTION) return obj; @@ -1492,7 +1511,8 @@ private static bool AnchorsByIdentity(MetaData obj) // 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) + // `preRc21` re-derives the base as it was before 1b existed, so the widening warning can compare. + if (!preRc21 && !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); @@ -1516,7 +1536,7 @@ private static bool AnchorsByIdentity(MetaData obj) // A projection that extends another projection, and anchors nothing of its own, has // the base entity its super has. if (targets.Count == 0 && obj.SuperData is { Type: TYPE_OBJECT, SubType: OBJECT_SUBTYPE_PROJECTION } superProjection) - return DeriveBaseEntity(superProjection, root, fieldName, originSource, errors); + return DeriveBaseEntity(superProjection, root, fieldName, originSource, errors, preRc21); if (targets.Count > 1) { string names = string.Join(", ", targets.Select(t => $"\"{t.Name}\"")); 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 9cfdf763d8..f5e6d99609 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 @@ -474,8 +474,18 @@ public object KotlinGenUtil { return out } - private fun fieldMap(fields: Collection>, strategy: String): Map = - fields.associate { f -> f.name to fieldNamesOf(f, strategy) } + private fun fieldMap( + fields: Collection>, + strategy: String, + skipDerived: Boolean, + ): Map { + val out = LinkedHashMap() + for (f in fields) { + if (skipDerived && f.isDerived) continue + out[f.name] = fieldNamesOf(f, strategy) + } + return out + } /** * The flattened test is migrate's own: a `field.object` whose RESOLVED `@storage` is @@ -514,12 +524,13 @@ public object KotlinGenUtil { ): KotlinObjectNames? { if (!declaresNamesContent(obj)) return null val own = obj.getMetaFields(false) + val columnless = obj.subType == MetaObject.SUBTYPE_ENTITY return KotlinObjectNames( type = obj.type, subType = obj.subType, name = obj.shortName, - fields = fieldMap(obj.metaFields, strategy), - ownFields = fieldMap(own, strategy), + fields = fieldMap(obj.metaFields, strategy, columnless), + ownFields = fieldMap(own, strategy, columnless), identities = keysOf(obj.getIdentities(true)), ownIdentities = keysOf(obj.getIdentities(false)), indexes = keysOf(obj.getChildren(LookupIndex::class.java, true)), @@ -544,7 +555,11 @@ public object KotlinGenUtil { // firstRdbSource nor writableRdbSource/readOnlyRdbSource is the right selector. // It also carries the divergence refusal that used to live in THIS function; see // below. - primaryRdbSource(obj) ?: return null + val source = primaryRdbSource(obj) ?: return null + // rc.21 (U7): a derived field of an object read from its table is no column of that + // table, so it has no names entry. A projection's or write-through entity's derived + // field is a column of its view and keeps its entry. + val columnless = source.isWritable() && !obj.isWriteThrough // D4 -- every consumer downstream is meant to reference this name // UNCONDITIONALLY, no per-site equality guard, so an object whose @role: primary @@ -567,6 +582,22 @@ public object KotlinGenUtil { // entities each declaring their own table reach direction 2. Both are pinned by // KotlinNamesDivergentSourceTest, which asserts zero load errors first. + val superObj = namesArtifactSuperOf(obj) + val ownFields = fieldMap(obj.getMetaFields(false), strategy, columnless).toMutableMap() + // 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 COLUMNS_BY_FIELD + // would reference a constant no emitted object declares. + if (!columnless && superObj != null + && superObj.subType == MetaObject.SUBTYPE_ENTITY + && isAbstractEntity(superObj)) { + for (field in obj.metaFields) { + if (field.isDerived && !ownFields.containsKey(field.name)) { + ownFields[field.name] = fieldNamesOf(field, strategy) + } + } + } + return KotlinObjectNames( type = obj.type, subType = obj.subType, @@ -580,14 +611,14 @@ public object KotlinGenUtil { // ADR-0039: metaFields is the RESOLVING accessor (getMetaFields() defaults to // includeParentData=true) -- an inherited @column must resolve here, or the // constant disagrees with the column the Exposed binding actually names. - fields = fieldMap(obj.metaFields, strategy), + fields = fieldMap(obj.metaFields, strategy, columnless), // ADR-0039's sanctioned own-accessor use: what this object DECLARES. - ownFields = fieldMap(obj.getMetaFields(false), strategy), + ownFields = ownFields, identities = keysOf(obj.getIdentities(true)), ownIdentities = keysOf(obj.getIdentities(false)), indexes = keysOf(obj.getChildren(LookupIndex::class.java, true)), ownIndexes = keysOf(obj.getChildren(LookupIndex::class.java, false)), - superObject = namesArtifactSuperOf(obj), + superObject = superObj, ) } 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 7b5fc9b9d4..158638b088 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 @@ -499,6 +499,90 @@ class KotlinNamesGeneratorTest { } + // rc.21 (U7): a derived field of an entity read from its table is no column of that table, + // so it has no names entry; a projection's derived field is a column of its view and keeps it. + // Mirrors the Java SpringNamesGeneratorTest U7 test and the TS names-derived-field test. + private val derivedModel = """{ + "metadata.root": { "package": "acme::ledger", "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": "pk", "@fields": ["id"] } } + ] } }, + { "object.projection": { "name": "AccountView", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_accounts" } }, + { "field.long": { "name": "id", "extends": "acme::ledger::Account.id" } }, + { "field.int": { "name": "doubled", "children": [ + { "origin.computed": { "@expr": { + "fn": "coalesce", "args": [ { "field": "score" }, { "value": 0 } ] } } } ] } }, + { "identity.primary": { "name": "pk", "extends": "acme::ledger::Account.pk" } } + ] } } + ] } + }""".trimIndent() + + @Test fun `a table entity's derived field has no names entry but a projection's keeps its column`() { + val files = emit(derivedModel) + val account = files.getValue("acme/ledger/AccountNames.kt") + assertTrue("SCORE_COLUMN" in account, account) + assertFalse("IS_HIGH" in account, account) + val view = files.getValue("acme/ledger/AccountViewNames.kt") + assertTrue("const val DOUBLED_COLUMN: String = \"doubled\"" in view, view) + } + + // rc.21 fix round (M8): an abstract-entity fragment drops its derived field (no column of + // the tables extending it), so a write-through extender — whose read view HAS that column — + // declares the constant itself. Mirrors the Java, TypeScript and C# M8 tests. + private val m8Model = """{ + "metadata.root": { "package": "acme::tracked", "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": "pk", "@fields": ["id"] } } + ] } }, + { "object.projection": { "name": "HighAccounts", "@filter": { "isHigh": true }, "children": [ + { "source.rdb": { "@kind": "view", "@view": "v_high_accounts" } }, + { "field.long": { "name": "id", "extends": "acme::tracked::Account.id" } }, + { "identity.primary": { "name": "pk", "extends": "acme::tracked::Account.pk" } } + ] } } + ] } + }""".trimIndent() + + @Test fun `a write-through extender declares the derived column its fragment drops`() { + val files = emit(m8Model) + + // The fragment drops the derived field: no table extending Tracked has an is_high column + // OF ITS OWN — Account's read view does, which is the other half of the assertion. + val tracked = files.getValue("acme/tracked/TrackedNames.kt") + assertFalse("IS_HIGH" in tracked, tracked) + + // COLUMNS_BY_FIELD references IS_HIGH_COLUMN; without the re-declaration the inherited + // half would re-export TrackedNames.IS_HIGH_COLUMN, which no emitted object declares, and + // the generated .kt would not compile — which is what the compilation below proves. + val account = files.getValue("acme/tracked/AccountNames.kt") + assertTrue("const val IS_HIGH_COLUMN: String = \"is_high\"" in account, account) + assertTrue("\"isHigh\" to IS_HIGH_COLUMN" in account, account) + + val sources = files.map { (path, text) -> SourceFile.kotlin(path.substringAfterLast('/'), text) } + val result = KotlinCompilation().apply { + this.sources = sources + inheritClassPath = true + messageOutputStream = System.out + }.compile() + assertEquals(KotlinCompilation.ExitCode.OK, result.exitCode, + "generated names objects failed to compile:\n${result.messages}") + } + @Test fun `a child field colliding with an INHERITED one is refused, naming the model`() { // The guard has to see the WHOLE field set, not just what this object declares. Once // a child stopped restating its inherited constants, an own-only check could no From 02198de52b264b420a2c3fa0844255e3e194c953 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:50:39 -0500 Subject: [PATCH 6/9] no-mistakes(review): Extend verify --db numeric widening to floats --- CHANGELOG.md | 5 +++-- .../src/introspect/declared-functions.ts | 6 ++++-- .../test/declared-functions-match.test.ts | 15 +++++++++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 28c363e157..2c4ffcc1b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,8 +50,9 @@ here.** declared `origin.function` signature check compared parameter types by exact name, so an `integer` argument for a `bigint` or `numeric` parameter, a polymorphic `any*` parameter and a variadic function were all reported as mismatches. It now allows integer to bigint to numeric - widening, treats `any*` parameters as wildcards and does not check a variadic function's - trailing arity (its required fixed parameters still are). A genuine mismatch (a narrowing, + widening and the float widenings onto real and double precision, treats `any*` parameters as + wildcards and does not check a variadic function's trailing arity (its required fixed + parameters still are). A genuine mismatch (a narrowing, an unrelated type, a wrong return type) still fails. - **Fix, TypeScript and C#: the widened-extender warning covers every extender whose base changed.** An extender with no identity of its own keeps its super's identity anchor (rc.21). 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 433d2d8914..66ff73eef1 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -53,8 +53,10 @@ export interface PgFunction { /** Implicit numeric widening Postgres applies to a call argument: a declared type may call a wider parameter. */ const WIDER_NUMERIC: Readonly> = { - integer: ["bigint", "numeric"], - bigint: ["numeric"], + integer: ["bigint", "numeric", "real", "double precision"], + bigint: ["numeric", "real", "double precision"], + numeric: ["real", "double precision"], + real: ["double precision"], }; /** Postgres's closed set of polymorphic pseudo-types (`pg_type.typtype = 'p'`): each takes any argument. */ diff --git a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts index 36cd3b74a9..c0a31bd0c6 100644 --- a/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts +++ b/server/typescript/packages/migrate-ts/test/declared-functions-match.test.ts @@ -22,6 +22,21 @@ describe("declared origin.function signature matching", () => { expect(signatureMatches(declared([["bigint"]]), pg(["numeric"]))).toBe(true); }); + test("Postgres's implicit float widening is accepted: each numeric to real, to double precision", () => { + expect(signatureMatches(declared([["integer"]]), pg(["real"]))).toBe(true); + expect(signatureMatches(declared([["integer"]]), pg(["double precision"]))).toBe(true); + expect(signatureMatches(declared([["bigint"]]), pg(["real"]))).toBe(true); + expect(signatureMatches(declared([["bigint"]]), pg(["double precision"]))).toBe(true); + expect(signatureMatches(declared([["numeric"]]), pg(["real"]))).toBe(true); + expect(signatureMatches(declared([["numeric"]]), pg(["double precision"]))).toBe(true); + expect(signatureMatches(declared([["real"]]), pg(["double precision"]))).toBe(true); + }); + + test("a float narrowing is a mismatch: double precision to real, real to integer", () => { + expect(signatureMatches(declared([["double precision"]]), pg(["real"]))).toBe(false); + expect(signatureMatches(declared([["real"]]), pg(["integer"]))).toBe(false); + }); + test("a narrowing is a mismatch: bigint to integer, numeric to bigint", () => { expect(signatureMatches(declared([["bigint"]]), pg(["integer"]))).toBe(false); expect(signatureMatches(declared([["numeric"]]), pg(["bigint"]))).toBe(false); From f4a081c157d6c4586178380fa46366a7d2544b15 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:58:15 -0500 Subject: [PATCH 7/9] no-mistakes(review): apply reviewer inline fixes --- .../migrate-ts/src/introspect/declared-functions.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) 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 66ff73eef1..e8c4484742 100644 --- a/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts +++ b/server/typescript/packages/migrate-ts/src/introspect/declared-functions.ts @@ -9,9 +9,10 @@ // 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. // -// What it accepts, as Postgres does: an `integer` argument for a `bigint` or `numeric` parameter (and -// `bigint` for `numeric`), any argument for a polymorphic `any*` parameter, and any arity for the -// trailing parameter of a `VARIADIC` function. +// What it accepts, as Postgres does: implicit numeric widening (an `integer` argument for a +// `bigint`, `numeric`, `real` or `double precision` parameter, `bigint`/`numeric`/`real` for a +// wider float), any argument for a polymorphic `any*` parameter, and any arity for the trailing +// parameter of a `VARIADIC` function. import type { Kysely } from "kysely"; import { sql } from "kysely"; @@ -194,8 +195,8 @@ export function signatureMatches(declared: DeclaredFunction, fn: PgFunction): bo */ /** 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, allowing Postgres's implicit integer " + - "widening (integer to bigint to numeric) and treating polymorphic (any*) parameters as wildcards: " + + "origin.function signatures are compared by plain type name, allowing Postgres's implicit numeric " + + "widening (integer to bigint to numeric, and each onto real or double precision) and treating polymorphic (any*) parameters as wildcards: " + "a json, array, enum or user-defined kind is not type-checked (only the arity is), a variadic " + "function's trailing parameter count and type are not checked (its required fixed arity is), and " + "a domain is compared by its own name, not its base type."; From e36d5bd2d02db6846dfffd2dcd1a1e111b54de04 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 14:07:57 -0500 Subject: [PATCH 8/9] no-mistakes(document): origin.function verify docs follow widening --- docs/features/relationships.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/features/relationships.md b/docs/features/relationships.md index 873c063677..fe94417660 100644 --- a/docs/features/relationships.md +++ b/docs/features/relationships.md @@ -286,11 +286,14 @@ 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`. 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 +type that Postgres would not accept for the call, 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). A declared `integer`, `bigint`, `numeric` or `real` matches a wider numeric +parameter that Postgres widens it to implicitly, and a polymorphic `any*` parameter takes any +type. A variadic function's trailing parameter count and type are not checked, though its required +fixed parameters still are. Beyond those, 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. From d3fed5c35786437b593ffd2b604516f3025bcc73 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 14:10:52 -0500 Subject: [PATCH 9/9] no-mistakes(document): names docs: derived fields have no entry --- agent-context/skills/metaobjects-codegen/references/csharp.md | 2 +- agent-context/skills/metaobjects-codegen/references/java.md | 2 +- agent-context/skills/metaobjects-codegen/references/kotlin.md | 2 +- agent-context/skills/metaobjects-codegen/references/python.md | 2 +- .../skills/metaobjects-codegen/references/typescript.md | 2 +- docs/ports/python.md | 2 +- .../.claude/skills/metaobjects-codegen/references/csharp.md | 2 +- .../.claude/skills/metaobjects-codegen/references/java.md | 2 +- .../.claude/skills/metaobjects-codegen/references/kotlin.md | 2 +- .../.claude/skills/metaobjects-codegen/references/java.md | 2 +- .../.claude/skills/metaobjects-codegen/references/python.md | 2 +- .../.claude/skills/metaobjects-codegen/references/typescript.md | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/agent-context/skills/metaobjects-codegen/references/csharp.md b/agent-context/skills/metaobjects-codegen/references/csharp.md index 5807adbd34..0ee7406d34 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 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. | +| `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 (a derived `origin.*` field of an entity read from its table has neither, since it is no column of that table, and is not in `ColumnsByField`; a projection's or write-through entity's derived field is a column of its view and keeps both), 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 0b1d5763f3..f0ad24b4cb 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 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. | +| `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 (a derived `origin.*` field of an entity read from its table has neither, since it is no column of that table, and is not in `COLUMNS_BY_FIELD`; a projection's or write-through entity's derived field is a column of its view and keeps both) 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/kotlin.md b/agent-context/skills/metaobjects-codegen/references/kotlin.md index da1178b4de..f9cfdaa8e7 100644 --- a/agent-context/skills/metaobjects-codegen/references/kotlin.md +++ b/agent-context/skills/metaobjects-codegen/references/kotlin.md @@ -224,7 +224,7 @@ All live in `metaobjects-codegen-kotlin` under | `KotlinRenderHelperGenerator` | the typed render helper for a `template.prompt` payload | | `KotlinValidatorGenerator` | `MetadataStartupValidator.kt` + `ExposedTableValidator.kt` (once per project) | | `KotlinSpringConfigGenerator` | `MetadataExposedConfig.kt` — `@Configuration` wiring `Database.connect()` + the startup validator (once per project) | -| `KotlinNamesGenerator` | `Names.kt` — an `object` of `const val` 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). Kotlin has no static inheritance — an `object` cannot extend another — so an artifact whose object extends another **re-exports** the parent's constants by reference (`const val SOURCE_PRIMARY_TABLE: String = AuthNames.SOURCE_PRIMARY_TABLE`) instead of restating the literal. Wire it alongside `KotlinExposedTableGenerator`: the Maven plugin then turns the table binding's constant substitution ON automatically (`AuthorTable : Table(AuthorNames.SOURCE_PRIMARY_TABLE)`); a run without it keeps the literals, so the output still compiles. | +| `KotlinNamesGenerator` | `Names.kt` — an `object` of `const val` 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 (a derived `origin.*` field of an entity read from its table has neither, since it is no column of that table, and is not in `COLUMNS_BY_FIELD`; a projection's or write-through entity's derived field is a column of its view and keeps both) 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). Kotlin has no static inheritance — an `object` cannot extend another — so an artifact whose object extends another **re-exports** the parent's constants by reference (`const val SOURCE_PRIMARY_TABLE: String = AuthNames.SOURCE_PRIMARY_TABLE`) instead of restating the literal. Wire it alongside `KotlinExposedTableGenerator`: the Maven plugin then turns the table binding's constant substitution ON automatically (`AuthorTable : Table(AuthorNames.SOURCE_PRIMARY_TABLE)`); a run without it keeps the literals, so the output still compiles. | | `KotlinStoredProcGenerator` | stored-procedure call wrappers for `source.rdb` `@kind="storedProc"` | | `KotlinFilterAllowlistGenerator` | per-entity filter allowlist | diff --git a/agent-context/skills/metaobjects-codegen/references/python.md b/agent-context/skills/metaobjects-codegen/references/python.md index 9c73346741..d9b9ccac55 100644 --- a/agent-context/skills/metaobjects-codegen/references/python.md +++ b/agent-context/skills/metaobjects-codegen/references/python.md @@ -158,7 +158,7 @@ a renamed physical column). | `routes` | a **FastAPI `APIRouter`** per writable entity (`source.rdb @kind="table"`) on the cross-port REST contract (`?filter[field][op]=`, `?sort=field:asc`, `?limit`/`?offset`, `?withCount=1` envelope, 400/404 envelopes). The router declares a repository **`Protocol`** you implement and inject. A TPH `@discriminator` base emits ONE polymorphic router: `GET /(+/{id})` plus a per-subtype CRUD set at `//` — create injects the discriminator from the URL (never the body); get/update/delete scoped to the subtype (cross-subtype → 404); discriminator immutable. Its repository `Protocol` is subtype-keyed (`subtype=None` for the polymorphic base) so your implementation applies the single-table discriminator scope. | | `filter-allowlist` | per-entity filter allowlist (FR-009 — the server-side field+operator allowlist the routes validate against). | | `output-parser` / `output-prompt` / `extractor` / `render-helper` / `trace-helper` | 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) — plus the render helper for a `template.output`. The strict parser (`